Apply simple sonar fixes 67/89767/2
authorJim Hahn <jrh3@att.com>
Wed, 12 Jun 2019 18:32:25 +0000 (14:32 -0400)
committerJim Hahn <jrh3@att.com>
Wed, 12 Jun 2019 21:36:59 +0000 (17:36 -0400)
Note: A number of these were identified, by SonarLint, in the Test
classes, which are not typically scanned by Sonar.

Removed unnecessary imports.
Removed unneeded "throws Xxx".
Replaced lambda with method references.
Replaced duplicate strings with constants.
Replaced try-fail-catch with assert-j methods to eliminate sonar
complaints about duplicate failure messages.
Added missing @Override annotations.
Use map.computeIfAbsent() where appropriate.
Also fixed some minor checkstyle issues.
Removed unneeded "volatile" declarations.
Replaced some if-else constructs with "?:" construct, per sonar.
Replaced Object.wait() with CountDownLatch.await(); according to sonar
(and javadocs), Object.wait() can return due to "spurious wakeups".
Fixed issue whereby CryptoUtilsTest wouldn't run in my Eclipse.

Change-Id: Ib6b71ed65662cfd6209400dac57ed69279bf29ec
Issue-ID: POLICY-1791
Signed-off-by: Jim Hahn <jrh3@att.com>
59 files changed:
common-parameters/pom.xml
common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java
common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java
common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java
common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java
common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java
gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java
gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java
gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java
gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/AnyGetterSerializerTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/AnySetterDeserializerTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/ClassWalkerTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java
gson/src/test/java/org/onap/policy/common/gson/internal/LifterTest.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSink.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSource.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java
policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java
utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java
utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java
utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java
utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java
utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java
utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java
utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java
utils/src/main/java/org/onap/policy/common/utils/services/Registry.java
utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java
utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java
utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java
utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java
utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java
utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java
utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java
utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java
utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java

index 0f1e9df..fc47b40 100644 (file)
@@ -1,6 +1,7 @@
 <!--
   ============LICENSE_START=======================================================
    Copyright (C) 2018 Ericsson. All rights reserved.
+   Modifications 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.
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
index b65db95..b874db6 100644 (file)
@@ -1,19 +1,20 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
- * 
+ *
  * SPDX-License-Identifier: Apache-2.0
  * ============LICENSE_END=========================================================
  */
@@ -27,32 +28,32 @@ import java.io.IOException;
 import org.junit.Test;
 
 public class ExceptionTest {
+    private static final String PARAMETER_EXCEPTION = "Parameter Exception";
+    private static final String EXCEPTION_OBJECT = "Exception Object";
 
     @Test
     public void testParameterException() {
-        assertEquals("Parameter Exception", new ParameterException("Parameter Exception").getMessage());
+        assertEquals(PARAMETER_EXCEPTION, new ParameterException(PARAMETER_EXCEPTION).getMessage());
 
-        String exceptionObject = "Exception Object";
-        assertEquals("Exception Object",
-                        new ParameterException("Parameter Exception", exceptionObject).getObject().toString());
+        assertEquals(EXCEPTION_OBJECT,
+                        new ParameterException(PARAMETER_EXCEPTION, EXCEPTION_OBJECT).getObject().toString());
 
         Exception testException = new IOException("IO Exception");
         assertEquals("Parameter Exception\ncaused by: Parameter Exception\ncaused by: IO Exception",
-                        new ParameterException("Parameter Exception", testException, exceptionObject)
+                        new ParameterException(PARAMETER_EXCEPTION, testException, EXCEPTION_OBJECT)
                                         .getCascadedMessage());
     }
 
     @Test
     public void testParameterRuntimeException() {
-        assertEquals("Parameter Exception", new ParameterRuntimeException("Parameter Exception").getMessage());
+        assertEquals(PARAMETER_EXCEPTION, new ParameterRuntimeException(PARAMETER_EXCEPTION).getMessage());
 
-        String exceptionObject = "Exception Object";
-        assertEquals("Exception Object",
-                        new ParameterRuntimeException("Parameter Exception", exceptionObject).getObject().toString());
+        assertEquals(EXCEPTION_OBJECT,
+                        new ParameterRuntimeException(PARAMETER_EXCEPTION, EXCEPTION_OBJECT).getObject().toString());
 
         Exception testException = new IOException("IO Exception");
         assertEquals("Parameter Exception\ncaused by: Parameter Exception\ncaused by: IO Exception",
-                        new ParameterRuntimeException("Parameter Exception", testException, exceptionObject)
+                        new ParameterRuntimeException(PARAMETER_EXCEPTION, testException, EXCEPTION_OBJECT)
                                         .getCascadedMessage());
     }
 }
index 30e2c0d..12cd80c 100644 (file)
@@ -37,6 +37,7 @@ public class TestBeanValidationResult {
     private static final String NEXT_INDENT = "yy ";
     private static final String MID_INDENT = "xx yy ";
     private static final String NAME = "my-name";
+    private static final String MY_LIST_INVALID = "  'my-list' INVALID, item has status INVALID\n    ";
     private static final String BEAN_INVALID_MSG = requote("'my-name' INVALID, item has status INVALID\n");
 
     private String cleanMsg;
@@ -105,14 +106,14 @@ public class TestBeanValidationResult {
         list = Arrays.asList(invalid, invalid);
         assertFalse(bean.validateNotNullList(MY_LIST, list, item -> item));
         assertFalse(bean.isValid());
-        assertEquals(requote(BEAN_INVALID_MSG + "  'my-list' INVALID, item has status INVALID\n    " + invalidMsg
+        assertEquals(requote(BEAN_INVALID_MSG + MY_LIST_INVALID + invalidMsg
                         + "    " + invalidMsg), bean.getResult());
     }
 
     @Test
     public void testValidateNotNullList_NullList() {
         List<ValidationResult> list = null;
-        assertFalse(bean.validateNotNullList("my-list", list, item -> item));
+        assertFalse(bean.validateNotNullList(MY_LIST, list, item -> item));
         assertFalse(bean.isValid());
         assertEquals(requote(BEAN_INVALID_MSG + "  item 'my-list' value 'null' INVALID, is null\n"), bean.getResult());
 
@@ -137,14 +138,14 @@ public class TestBeanValidationResult {
         bean = new BeanValidationResult(NAME, OBJECT);
         assertFalse(bean.validateList(MY_LIST, list, item -> item));
         assertFalse(bean.isValid());
-        assertEquals(requote(BEAN_INVALID_MSG + "  'my-list' INVALID, item has status INVALID\n    "
+        assertEquals(requote(BEAN_INVALID_MSG + MY_LIST_INVALID
                         + "item 'item' value 'null' INVALID, null\n"), bean.getResult());
 
         list = Arrays.asList(invalid, invalid);
         bean = new BeanValidationResult(NAME, OBJECT);
         assertFalse(bean.validateList(MY_LIST, list, item -> item));
         assertFalse(bean.isValid());
-        assertEquals(requote(BEAN_INVALID_MSG + "  'my-list' INVALID, item has status INVALID\n    " + invalidMsg
+        assertEquals(requote(BEAN_INVALID_MSG + MY_LIST_INVALID + invalidMsg
                         + "    " + invalidMsg), bean.getResult());
 
     }
index ae4dbd2..abef552 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
@@ -22,16 +23,13 @@ package org.onap.policy.common.parameters;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-
 import java.io.FileReader;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-
 import org.junit.Test;
 import org.onap.policy.common.parameters.testclasses.TestParametersL00;
 
@@ -42,15 +40,10 @@ public class TestJsonInput {
     public void testJsonInput() throws IOException {
         TestParametersL00 testParameterGroup = null;
 
-        // Read the parameters
-        try {
-            // Read the parameters from JSON using Gson
-            final Gson gson = new GsonBuilder().create();
-            testParameterGroup = gson.fromJson(new FileReader("src/test/resources/parameters/TestParameters.json"),
-                            TestParametersL00.class);
-        } catch (final Exception e) {
-            fail("test should not throw an exception here: " + e.getMessage());
-        }
+        // Read the parameters from JSON using Gson
+        final Gson gson = new GsonBuilder().create();
+        testParameterGroup = gson.fromJson(new FileReader("src/test/resources/parameters/TestParameters.json"),
+                        TestParametersL00.class);
 
         GroupValidationResult validationResult = testParameterGroup.validate();
         assertTrue(validationResult.isValid());
index 2dad428..fda3781 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
 
 package org.onap.policy.common.parameters;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import org.junit.Test;
-import org.onap.policy.common.parameters.ParameterRuntimeException;
-import org.onap.policy.common.parameters.ParameterService;
 import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup;
 
 public class TestParameterService {
+    private static final String EMPTY_GROUP = "Empty Group";
 
     @Test
     public void testParameterService() {
         ParameterService.clear();
 
         assertFalse(ParameterService.contains("EmptyGroup"));
-        try {
-            ParameterService.get("EmptyGroup");
-            fail("Test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("\"EmptyGroup\" not found in parameter service", e.getMessage());
-        }
-
-        ParameterService.register(new EmptyParameterGroup("Empty Group"));
-        assertTrue(ParameterService.contains("Empty Group"));
-        assertNotNull(ParameterService.get("Empty Group"));
-        
-        try {
-            ParameterService.register(new EmptyParameterGroup("Empty Group"));
-            fail("this test should throw an exception");
-        }
-        catch (ParameterRuntimeException e) {
-            assertEquals("\"Empty Group\" already registered in parameter service", e.getMessage());
-        }
-
-        try {
-            ParameterService.register(new EmptyParameterGroup("Empty Group"), false);
-            fail("this test should throw an exception");
-        }
-        catch (ParameterRuntimeException e) {
-            assertEquals("\"Empty Group\" already registered in parameter service", e.getMessage());
-        }
-
-        ParameterService.register(new EmptyParameterGroup("Empty Group"), true);
-        assertTrue(ParameterService.contains("Empty Group"));
-
-        ParameterService.deregister("Empty Group");
-        assertFalse(ParameterService.contains("Empty Group"));
-
-        ParameterService.register(new EmptyParameterGroup("Empty Group"), true);
-        assertTrue(ParameterService.contains("Empty Group"));
-
-        ParameterService.deregister("Empty Group");
-        assertFalse(ParameterService.contains("Empty Group"));
-
-        EmptyParameterGroup epg = new EmptyParameterGroup("Empty Group");
+
+        assertThatThrownBy(() -> ParameterService.get("EmptyGroup"))
+                        .hasMessage("\"EmptyGroup\" not found in parameter service");
+
+        ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP));
+        assertTrue(ParameterService.contains(EMPTY_GROUP));
+        assertNotNull(ParameterService.get(EMPTY_GROUP));
+
+        assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)))
+                        .hasMessage("\"Empty Group\" already registered in parameter service");
+
+        assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), false))
+                        .hasMessage("\"Empty Group\" already registered in parameter service");
+
+        ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true);
+        assertTrue(ParameterService.contains(EMPTY_GROUP));
+
+        ParameterService.deregister(EMPTY_GROUP);
+        assertFalse(ParameterService.contains(EMPTY_GROUP));
+
+        ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true);
+        assertTrue(ParameterService.contains(EMPTY_GROUP));
+
+        ParameterService.deregister(EMPTY_GROUP);
+        assertFalse(ParameterService.contains(EMPTY_GROUP));
+
+        EmptyParameterGroup epg = new EmptyParameterGroup(EMPTY_GROUP);
         ParameterService.register(epg);
-        assertTrue(ParameterService.contains("Empty Group"));
-        assertNotNull(ParameterService.get("Empty Group"));
+        assertTrue(ParameterService.contains(EMPTY_GROUP));
+        assertNotNull(ParameterService.get(EMPTY_GROUP));
 
         ParameterService.deregister(epg);
-        assertFalse(ParameterService.contains("Empty Group"));
-
-        try {
-            ParameterService.deregister("Empty Group");
-            fail("this test should throw an exception");
-        }
-        catch (ParameterRuntimeException e) {
-            assertEquals("\"Empty Group\" not registered in parameter service", e.getMessage());
-        }
-
-        try {
-            ParameterService.get("Empty Group");
-            fail("Test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("\"Empty Group\" not found in parameter service", e.getMessage());
-        }
-
-        ParameterService.register(new EmptyParameterGroup("Empty Group"));
-        assertTrue(ParameterService.contains("Empty Group"));
-        assertNotNull(ParameterService.get("Empty Group"));
+        assertFalse(ParameterService.contains(EMPTY_GROUP));
+
+        assertThatThrownBy(() -> ParameterService.deregister(EMPTY_GROUP))
+                        .hasMessage("\"Empty Group\" not registered in parameter service");
+
+        assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP))
+                        .hasMessage("\"Empty Group\" not found in parameter service");
+
+        ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP));
+        assertTrue(ParameterService.contains(EMPTY_GROUP));
+        assertNotNull(ParameterService.get(EMPTY_GROUP));
 
         assertEquals(1, ParameterService.getAll().size());
         ParameterService.clear();
         assertEquals(0, ParameterService.getAll().size());
-        assertFalse(ParameterService.contains("Empty Group"));
-        try {
-            ParameterService.get("Empty Group");
-            fail("Test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("\"Empty Group\" not found in parameter service", e.getMessage());
-        }
+        assertFalse(ParameterService.contains(EMPTY_GROUP));
+
+        assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP))
+                        .hasMessage("\"Empty Group\" not found in parameter service");
     }
 }
index eb67322..9e7121c 100644 (file)
@@ -38,6 +38,8 @@ import org.onap.policy.common.parameters.testclasses.TestParametersL00;
 import org.onap.policy.common.parameters.testclasses.TestParametersL10;
 
 public class TestValidation {
+    private static final String L0_PARAMETERS = "l0Parameters";
+
     private static final String NOT_BLANK_STRING_MESSAGE =
                     "field 'notBlankString' type 'java.lang.String' value '' INVALID, must be a non-blank string\n"
                                     .replace('\'', '"');
@@ -73,7 +75,7 @@ public class TestValidation {
 
     @Test
     public void testValidationOk() throws IOException {
-        TestParametersL00 l0Parameters = new TestParametersL00("l0Parameters");
+        TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
 
         GroupValidationResult validationResult = l0Parameters.validate();
         assertTrue(validationResult.isValid());
@@ -90,7 +92,7 @@ public class TestValidation {
 
     @Test
     public void testValidationObservation() throws IOException {
-        TestParametersL00 l0Parameters = new TestParametersL00("l0Parameters");
+        TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
 
         l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 3);
 
@@ -135,7 +137,7 @@ public class TestValidation {
 
     @Test
     public void testValidationWarning() throws IOException {
-        TestParametersL00 l0Parameters = new TestParametersL00("l0Parameters");
+        TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
 
         l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 3);
 
@@ -179,7 +181,7 @@ public class TestValidation {
 
     @Test
     public void testValidationInvalid() throws IOException {
-        TestParametersL00 l0Parameters = new TestParametersL00("l0Parameters");
+        TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS);
 
         l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 3);
 
@@ -222,7 +224,7 @@ public class TestValidation {
     }
 
     @Test
-    public void testValidationEmptySubGroup() throws IOException {
+    public void testValidationEmptySubGroup() {
         TestParametersL10 l10Parameters = new TestParametersL10("l10Parameters");
 
         l10Parameters.setL10LGenericNested0(null);
@@ -234,7 +236,7 @@ public class TestValidation {
     }
 
     @Test
-    public void testGetValidationResult() throws Exception {
+    public void testGetValidationResult() {
         Contained item = new Contained();
         item.setName("item");
 
index 2c1e2f1..b02022d 100644 (file)
@@ -1,29 +1,29 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
- * 
+ *
  * SPDX-License-Identifier: Apache-2.0
  * ============LICENSE_END=========================================================
  */
 
 package org.onap.policy.common.parameters;
 
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import org.junit.Test;
 import org.onap.policy.common.parameters.testclasses.ParameterGroupMissingGetter;
@@ -51,25 +51,18 @@ public class TestValidationErrors {
 
         ParameterGroupWithParameterGroupCollection illegalCollection = new ParameterGroupWithParameterGroupCollection(
                         "Illegal Collection");
-        try {
-            illegalCollection.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("collection parameter \"parameterGroupArrayList\" is illegal,"
-                            + " parameter groups are not allowed as collection members", e.getMessage());
-        }
+
+        assertThatThrownBy(illegalCollection::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("collection parameter \"parameterGroupArrayList\" is illegal,"
+                                        + " parameter groups are not allowed as collection members");
     }
 
     @Test
     public void testNullCollection() {
         ParameterGroupWithNullCollection nullCollection = new ParameterGroupWithNullCollection("Null Collection");
 
-        try {
-            nullCollection.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("collection parameter \"nullList\" is null", e.getMessage());
-        }
+        assertThatThrownBy(nullCollection::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("collection parameter \"nullList\" is null");
     }
 
     @Test
@@ -83,59 +76,42 @@ public class TestValidationErrors {
     @Test
     public void testMapNullValueValidation() {
         ParameterGroupWithNullMapValue nullMap = new ParameterGroupWithNullMapValue("Null Map value");
-        try {
-            nullMap.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("map parameter \"nullMap\" is null", e.getMessage());
-        }
+
+        assertThatThrownBy(nullMap::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("map parameter \"nullMap\" is null");
     }
 
     @Test
     public void testBadMapKeyValidation() {
         ParameterGroupWithIllegalMapKey illegalMap = new ParameterGroupWithIllegalMapKey("Illegal Map");
-        try {
-            illegalMap.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("map entry is not a parameter group keyed by a string, key \"1\" "
-                            + "in map \"badMap\" is not a string", e.getMessage());
-        }
+
+        assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("map entry is not a parameter group keyed by a string, key \"1\" "
+                                        + "in map \"badMap\" is not a string");
     }
 
     @Test
     public void testBadMapValueValidation() {
         ParameterGroupWithIllegalMapValue illegalMap = new ParameterGroupWithIllegalMapValue("Illegal Map");
-        try {
-            illegalMap.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("map entry is not a parameter group keyed by a string, value \"1\" in "
-                            + "map \"intMap\" is not a parameter group", e.getMessage());
-        }
+
+        assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("map entry is not a parameter group keyed by a string, value \"1\" in "
+                                        + "map \"intMap\" is not a parameter group");
     }
-    
+
     @Test
     public void testMissingGetter() {
         ParameterGroupMissingGetter badGetterName = new ParameterGroupMissingGetter("BGN");
-        try {
-            badGetterName.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("could not get getter method for parameter \"value\"", e.getMessage());
-        }
-        
+
+        assertThatThrownBy(badGetterName::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("could not get getter method for parameter \"value\"");
     }
-    
+
     @Test
     public void testPrivateGetter() {
         ParameterGroupPrivateGetter privateGetter = new ParameterGroupPrivateGetter("privateGetter");
-        try {
-            privateGetter.isValid();
-            fail("test should throw an exception");
-        } catch (ParameterRuntimeException e) {
-            assertEquals("could not get getter method for parameter \"value\"", e.getMessage());
-        }
-        
+
+        assertThatThrownBy(privateGetter::isValid).isInstanceOf(ParameterRuntimeException.class)
+                        .hasMessage("could not get getter method for parameter \"value\"");
     }
 }
index f745105..46360ef 100644 (file)
@@ -1,53 +1,61 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
- * 
+ *
  * SPDX-License-Identifier: Apache-2.0
  * ============LICENSE_END=========================================================
  */
 
 package org.onap.policy.common.parameters;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import java.util.LinkedHashMap;
 import java.util.Map;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.onap.policy.common.parameters.testclasses.TestParametersL10;
 import org.onap.policy.common.parameters.testclasses.TestParametersLGeneric;
 
 public class TestValidationResults {
+    private static final String NON_EXISTANT_PARAMETER = "nonExistantParameter";
+    private static final String L10L_GENERIC_NESTED_MAP_VAL0 = "l10LGenericNestedMapVal0";
+    private static final String L10_INT_FIELD = "l10IntField";
+    private static final String ENTRY0 = "entry0";
+    private static final String THIS_VALUE_IS_INVALID = "This value is invalid";
+    private static final String SOMETHING_WAS_OBSERVED = "Something was observed";
+    private static final String PG_MAP = "pgMap";
+
     private Map<String, ParameterGroup> pgMap = new LinkedHashMap<>();
     private ParameterGroup pg = new TestParametersL10("pg");
 
     @Before
     public void initMap() {
-        pgMap.put("entry0", new TestParametersLGeneric("entry0"));
+        pgMap.put(ENTRY0, new TestParametersLGeneric(ENTRY0));
     }
 
     @Test
-    public void testGroupMapValidationResult() throws NoSuchFieldException, SecurityException {
-        GroupMapValidationResult result = new GroupMapValidationResult(this.getClass().getDeclaredField("pgMap"),
+    public void testGroupMapValidationResult() throws NoSuchFieldException {
+        GroupMapValidationResult result = new GroupMapValidationResult(this.getClass().getDeclaredField(PG_MAP),
                         pgMap);
 
         assertTrue(result.isValid());
-        assertEquals("pgMap", result.getName());
+        assertEquals(PG_MAP, result.getName());
 
         result.setResult(ValidationStatus.OBSERVATION);
         assertTrue(result.isValid());
@@ -58,26 +66,22 @@ public class TestValidationResults {
         assertTrue(result.isValid());
         assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
 
-        result.setResult(ValidationStatus.OBSERVATION, "Something was observed");
+        result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
         assertTrue(result.isValid());
         assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
         assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim());
 
-        result.setResult("entry0", new GroupValidationResult(pgMap.get("entry0")));
+        result.setResult(ENTRY0, new GroupValidationResult(pgMap.get(ENTRY0)));
         assertTrue(result.isValid());
         assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
         assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim());
 
-        try {
-            result.setResult("nonExistantEntry", new GroupValidationResult(pgMap.get("entry0")));
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no entry with name \"nonExistantEntry\" exists", e.getMessage());
-        }
+        assertThatThrownBy(() -> result.setResult("nonExistantEntry", new GroupValidationResult(pgMap.get(ENTRY0))))
+                        .hasMessage("no entry with name \"nonExistantEntry\" exists");
     }
 
     @Test
-    public void testGroupValidationResult() throws NoSuchFieldException, SecurityException {
+    public void testGroupValidationResult() throws NoSuchFieldException {
         GroupValidationResult result = new GroupValidationResult(pg);
 
         assertTrue(result.isValid());
@@ -93,79 +97,47 @@ public class TestValidationResults {
         assertTrue(result.isValid());
         assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
 
-        result.setResult(ValidationStatus.OBSERVATION, "Something was observed");
+        result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
         assertTrue(result.isValid());
         assertEquals(ValidationStatus.OBSERVATION, result.getStatus());
         assertEquals("parameter group \"pg\" type \"org.onap.policy.common.parameters.testclasses.TestParametersL10\""
                         + " OBSERVATION, Something was observed", result.getResult().trim());
 
-        try {
-            result.setResult("nonExistantParameter", ValidationStatus.OBSERVATION, "Something was observed");
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no parameter field exists for parameter: nonExistantParameter", e.getMessage());
-        }
+        assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ValidationStatus.OBSERVATION,
+                        SOMETHING_WAS_OBSERVED))
+                                        .hasMessage("no parameter field exists for parameter: nonExistantParameter");
 
-        result.setResult("l10IntField", ValidationStatus.OBSERVATION, "Something was observed");
+        result.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED);
         assertTrue(result.isValid());
 
-        try {
-            result.setResult("nonExistantParameter", new GroupValidationResult(pg));
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no nested parameter field exists for parameter: nonExistantParameter", e.getMessage());
-        }
+        assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, new GroupValidationResult(pg)))
+                        .hasMessage("no nested parameter field exists for parameter: nonExistantParameter");
 
-        try {
-            result.setResult("l10IntField", new GroupValidationResult(pg));
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("parameter is not a nested group parameter: l10IntField", e.getMessage());
-        }
+        assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, new GroupValidationResult(pg)))
+                        .hasMessage("parameter is not a nested group parameter: l10IntField");
 
         GroupMapValidationResult groupMapResult = new GroupMapValidationResult(
-                        this.getClass().getDeclaredField("pgMap"), pgMap);
-
-        try {
-            result.setResult("nonExistantParameter", "entry0", groupMapResult);
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no group map parameter field exists for parameter: nonExistantParameter", e.getMessage());
-        }
-
-        try {
-            result.setResult("l10IntField", "entry0", groupMapResult);
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("parameter is not a nested group map parameter: l10IntField", e.getMessage());
-        }
-
-        result.setResult("l10LGenericNestedMap", "l10LGenericNestedMapVal0", ValidationStatus.INVALID,
-                        "This value is invalid");
+                        this.getClass().getDeclaredField(PG_MAP), pgMap);
+
+        assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ENTRY0, groupMapResult))
+                        .hasMessage("no group map parameter field exists for parameter: nonExistantParameter");
+
+        assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, ENTRY0, groupMapResult))
+                        .hasMessage("parameter is not a nested group map parameter: l10IntField");
+
+        result.setResult("l10LGenericNestedMap", L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID,
+                        THIS_VALUE_IS_INVALID);
         assertEquals(ValidationStatus.INVALID, result.getStatus());
-        
-        try {
-            result.setResult("l10IntField", "l10LGenericNestedMapVal0", ValidationStatus.INVALID,
-                            "This value is invalid");
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("parameter is not a nested group map parameter: l10IntField", e.getMessage());
-        }
-        
-        try {
-            result.setResult("nonExistantParameter", "l10LGenericNestedMapVal0", ValidationStatus.INVALID,
-                            "This value is invalid");
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no group map parameter field exists for parameter: nonExistantParameter", e.getMessage());
-        }
-        
-        try {
-            result.setResult("l10LGenericNestedMap", "NonExistantKey", ValidationStatus.INVALID,
-                            "This value is invalid");
-            fail("test shold throw an exception here");
-        } catch (Exception e) {
-            assertEquals("no entry with name \"NonExistantKey\" exists", e.getMessage());
-        }
+
+        assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID,
+                        THIS_VALUE_IS_INVALID))
+                                        .hasMessage("parameter is not a nested group map parameter: l10IntField");
+
+        assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, L10L_GENERIC_NESTED_MAP_VAL0,
+                        ValidationStatus.INVALID, THIS_VALUE_IS_INVALID)).hasMessage(
+                                        "no group map parameter field exists for parameter: nonExistantParameter");
+
+        assertThatThrownBy(() -> result.setResult("l10LGenericNestedMap", "NonExistantKey", ValidationStatus.INVALID,
+                        THIS_VALUE_IS_INVALID)).hasMessage("no entry with name \"NonExistantKey\" exists");
     }
 }
index e24f1c8..6665684 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
@@ -22,13 +23,11 @@ package org.onap.policy.common.parameters;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import java.io.FileReader;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-
 import org.junit.Test;
 import org.onap.policy.common.parameters.testclasses.TestParametersL00;
 import org.yaml.snakeyaml.Yaml;
@@ -38,15 +37,10 @@ public class TestYamlInput {
     public void testYamlInput() throws IOException {
         TestParametersL00 testParameterGroup = null;
 
-        // Read the parameters
-        try {
-            // Read the parameters from JSON using Gson
-            final Yaml yaml = new Yaml();
-            testParameterGroup = yaml.loadAs(new FileReader("src/test/resources/parameters/TestParameters.yaml"),
-                            TestParametersL00.class);
-        } catch (final Exception e) {
-            fail("test should not throw an exception here: " + e.getMessage());
-        }
+        // Read the parameters from JSON using Gson
+        final Yaml yaml = new Yaml();
+        testParameterGroup = yaml.loadAs(new FileReader("src/test/resources/parameters/TestParameters.yaml"),
+                        TestParametersL00.class);
 
         GroupValidationResult validationResult = testParameterGroup.validate();
         assertTrue(validationResult.isValid());
index 748eb90..ea5ae85 100644 (file)
@@ -30,6 +30,9 @@ import org.onap.policy.common.parameters.ParameterGroupImpl;
 import org.onap.policy.common.parameters.ValidationStatus;
 
 public class TestParametersL00 extends ParameterGroupImpl {
+    private static final String L00_INT_FIELD = "l00IntField";
+    private static final String L00_STRING_FIELD = "l00StringField";
+
     private static final String A_CONSTANT = "A Constant";
 
     private int l00IntField = 0;
@@ -136,7 +139,7 @@ public class TestParametersL00 extends ParameterGroupImpl {
                 l00IntField = 2;
                 break;
             case WARNING:
-                l00StringField = "l00StringField";
+                l00StringField = L00_STRING_FIELD;
                 l00IntField = 3;
                 break;
             case INVALID:
@@ -165,29 +168,29 @@ public class TestParametersL00 extends ParameterGroupImpl {
         }
 
         if (l00StringField == null || l00StringField.trim().length() == 0) {
-            validationResult.setResult("l00StringField", ValidationStatus.INVALID,
+            validationResult.setResult(L00_STRING_FIELD, ValidationStatus.INVALID,
                             "l00StringField must be a non-blank string");
-        } else if (l00StringField.equals("l00StringField")) {
-            validationResult.setResult("l00StringField", ValidationStatus.WARNING,
+        } else if (l00StringField.equals(L00_STRING_FIELD)) {
+            validationResult.setResult(L00_STRING_FIELD, ValidationStatus.WARNING,
                             "using the field name for the parameter value is dangerous");
         } else if (l00StringField.equals("aString")) {
-            validationResult.setResult("l00StringField", ValidationStatus.OBSERVATION,
+            validationResult.setResult(L00_STRING_FIELD, ValidationStatus.OBSERVATION,
                             "this value for name is unhelpful");
         } else {
-            validationResult.setResult("l00StringField", ValidationStatus.CLEAN,
+            validationResult.setResult(L00_STRING_FIELD, ValidationStatus.CLEAN,
                             ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
         }
 
         if (l00IntField < 0) {
-            validationResult.setResult("l00IntField", ValidationStatus.INVALID,
+            validationResult.setResult(L00_INT_FIELD, ValidationStatus.INVALID,
                             "l00IntField must be a positive integer");
         } else if (l00IntField > 2) {
-            validationResult.setResult("l00IntField", ValidationStatus.WARNING,
+            validationResult.setResult(L00_INT_FIELD, ValidationStatus.WARNING,
                             "values greater than 2 are not recommended");
         } else if (l00IntField == 2) {
-            validationResult.setResult("l00IntField", ValidationStatus.OBSERVATION, "this field has been set to 2");
+            validationResult.setResult(L00_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2");
         } else {
-            validationResult.setResult("l00IntField", ValidationStatus.CLEAN,
+            validationResult.setResult(L00_INT_FIELD, ValidationStatus.CLEAN,
                             ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
         }
 
index 8ad682f..2fba9ba 100644 (file)
@@ -30,6 +30,9 @@ import org.onap.policy.common.parameters.ParameterGroupImpl;
 import org.onap.policy.common.parameters.ValidationStatus;
 
 public class TestParametersL10 extends ParameterGroupImpl {
+    private static final String L10_INT_FIELD = "l10IntField";
+    private static final String L10_STRING_FIELD = "l10StringField";
+
     private int l10IntField = 0;
     private String l10StringField = "Legal " + this.getClass().getCanonicalName();
     private TestParametersLGeneric l10LGenericNested0 = new TestParametersLGeneric("l10LGenericNested0");
@@ -120,7 +123,7 @@ public class TestParametersL10 extends ParameterGroupImpl {
                 l10IntField = 2;
                 break;
             case WARNING:
-                l10StringField = "l10StringField";
+                l10StringField = L10_STRING_FIELD;
                 l10IntField = 3;
                 break;
             case INVALID:
@@ -144,29 +147,29 @@ public class TestParametersL10 extends ParameterGroupImpl {
         GroupValidationResult validationResult = super.validate();
 
         if (l10StringField == null || l10StringField.trim().length() == 0) {
-            validationResult.setResult("l10StringField", ValidationStatus.INVALID,
+            validationResult.setResult(L10_STRING_FIELD, ValidationStatus.INVALID,
                             "l10StringField must be a non-blank string");
-        } else if (l10StringField.equals("l10StringField")) {
-            validationResult.setResult("l10StringField", ValidationStatus.WARNING,
+        } else if (l10StringField.equals(L10_STRING_FIELD)) {
+            validationResult.setResult(L10_STRING_FIELD, ValidationStatus.WARNING,
                             "using the field name for the parameter value is dangerous");
         } else if (l10StringField.equals("aString")) {
-            validationResult.setResult("l10StringField", ValidationStatus.OBSERVATION,
+            validationResult.setResult(L10_STRING_FIELD, ValidationStatus.OBSERVATION,
                             "this value for name is unhelpful");
         } else {
-            validationResult.setResult("l10StringField", ValidationStatus.CLEAN,
+            validationResult.setResult(L10_STRING_FIELD, ValidationStatus.CLEAN,
                             ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
         }
 
         if (l10IntField < 0) {
-            validationResult.setResult("l10IntField", ValidationStatus.INVALID,
+            validationResult.setResult(L10_INT_FIELD, ValidationStatus.INVALID,
                             "l10IntField must be a positive integer");
         } else if (l10IntField > 2) {
-            validationResult.setResult("l10IntField", ValidationStatus.WARNING,
+            validationResult.setResult(L10_INT_FIELD, ValidationStatus.WARNING,
                             "values greater than 2 are not recommended");
         } else if (l10IntField == 2) {
-            validationResult.setResult("l10IntField", ValidationStatus.OBSERVATION, "this field has been set to 2");
+            validationResult.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2");
         } else {
-            validationResult.setResult("l10IntField", ValidationStatus.CLEAN,
+            validationResult.setResult(L10_INT_FIELD, ValidationStatus.CLEAN,
                             ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString());
         }
 
index 2fc0418..44ec713 100644 (file)
@@ -28,6 +28,9 @@ import org.onap.policy.common.parameters.annotations.NotBlank;
 import org.onap.policy.common.parameters.annotations.NotNull;
 
 public class TestParametersLGeneric extends ParameterGroupImpl {
+    private static final String LGENERIC_INT_FIELD = "lgenericIntField";
+    private static final String LGENERIC_STRING_FIELD = "lgenericStringField";
+
     private int lgenericIntField = 0;
 
     @NotNull @NotBlank
@@ -74,9 +77,6 @@ public class TestParametersLGeneric extends ParameterGroupImpl {
         if (level == 0) {
             return;
         }
-        else {
-            level--;
-        }
 
         switch (triggerStatus) {
             case CLEAN:
@@ -88,7 +88,7 @@ public class TestParametersLGeneric extends ParameterGroupImpl {
                 lgenericIntField = 2;
                 break;
             case WARNING:
-                lgenericStringField = "lgenericStringField";
+                lgenericStringField = LGENERIC_STRING_FIELD;
                 lgenericIntField = 3;
                 break;
             case INVALID:
@@ -105,22 +105,22 @@ public class TestParametersLGeneric extends ParameterGroupImpl {
     public GroupValidationResult validate() {
         GroupValidationResult validationResult = super.validate();
 
-        if ("lgenericStringField".equals(lgenericStringField)) {
-            validationResult.setResult("lgenericStringField", ValidationStatus.WARNING,
+        if (LGENERIC_STRING_FIELD.equals(lgenericStringField)) {
+            validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.WARNING,
                             "using the field name for the parameter value is dangerous");
         } else if ("aString".equals(lgenericStringField)) {
-            validationResult.setResult("lgenericStringField", ValidationStatus.OBSERVATION,
+            validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.OBSERVATION,
                             "this value for name is unhelpful");
         }
 
         if (lgenericIntField < 0) {
-            validationResult.setResult("lgenericIntField", ValidationStatus.INVALID,
+            validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.INVALID,
                             "lgenericIntField must be a positive integer");
         } else if (lgenericIntField > 2) {
-            validationResult.setResult("lgenericIntField", ValidationStatus.WARNING,
+            validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.WARNING,
                             "values greater than 2 are not recommended");
         } else if (lgenericIntField == 2) {
-            validationResult.setResult("lgenericIntField", ValidationStatus.OBSERVATION,
+            validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.OBSERVATION,
                             "this field has been set to 2");
         }
 
index 65baaee..c7b3bc9 100644 (file)
@@ -59,7 +59,7 @@ public class Adapter {
     /**
      * Converter used when writing, allocated lazily, once an actual type is determined.
      */
-    private volatile ConvInfo writer = null;
+    private ConvInfo writer = null;
 
     /**
      * Name of the item being lifted - used when throwing exceptions.
@@ -318,7 +318,7 @@ public class Adapter {
          * Converter to use, initialized lazily.
          */
         @SuppressWarnings("rawtypes")
-        private volatile TypeAdapter conv = null;
+        private TypeAdapter conv = null;
 
         /**
          * Constructs the object.
index 4b5473c..3ce1696 100644 (file)
@@ -33,7 +33,6 @@ import java.util.LinkedList;
 import java.util.TreeMap;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
 
 public class JacksonExclusionStrategyTest {
 
index 9d4b438..bbeb1e2 100644 (file)
@@ -32,8 +32,6 @@ import com.google.gson.reflect.TypeToken;
 import java.util.ArrayList;
 import java.util.List;
 import org.junit.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.JacksonFieldAdapterFactory;
 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
 
index 47cf4b3..6377420 100644 (file)
@@ -33,8 +33,6 @@ import com.google.gson.reflect.TypeToken;
 import java.util.Map;
 import java.util.TreeMap;
 import org.junit.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.JacksonMethodAdapterFactory;
 import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
 import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
index 04f3716..3316000 100644 (file)
@@ -34,11 +34,12 @@ import java.util.List;
 import org.junit.Test;
 import org.onap.policy.common.gson.JacksonExclusionStrategy;
 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-import org.onap.policy.common.gson.internal.Adapter;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.DerivedData;
 
 public class AdapterTest {
+    private static final String EMPTY_ALIAS = "emptyAlias";
+    private static final String GET_VALUE = ".getValue";
     private static final String GET_VALUE_NAME = "getValue";
     private static final String VALUE_NAME = "value";
     private static final String MY_NAME = AdapterTest.class.getName();
@@ -171,9 +172,9 @@ public class AdapterTest {
         adapter = new Adapter(gson, mget(GET_VALUE_NAME), String.class);
 
         assertEquals(VALUE_NAME, adapter.getPropName());
-        assertEquals(MY_NAME + ".getValue", adapter.getFullName());
+        assertEquals(MY_NAME + GET_VALUE, adapter.getFullName());
 
-        assertEquals("hello: " + MY_NAME + ".getValue", adapter.makeError("hello: "));
+        assertEquals("hello: " + MY_NAME + GET_VALUE, adapter.makeError("hello: "));
 
 
         // test setter
@@ -201,7 +202,7 @@ public class AdapterTest {
 
     @Test
     public void testDetmPropName() {
-        assertEquals("emptyAlias", Adapter.detmPropName(field("emptyAlias")));
+        assertEquals(EMPTY_ALIAS, Adapter.detmPropName(field(EMPTY_ALIAS)));
         assertEquals("name-with-alias", Adapter.detmPropName(field("nameWithAlias")));
         assertEquals("unaliased", Adapter.detmPropName(field("unaliased")));
         assertEquals(null, Adapter.detmPropName(field("$invalidFieldName")));
@@ -209,7 +210,7 @@ public class AdapterTest {
 
     @Test
     public void testDetmGetterPropName() {
-        assertEquals("emptyAlias", Adapter.detmGetterPropName(mget("getEmptyAlias")));
+        assertEquals(EMPTY_ALIAS, Adapter.detmGetterPropName(mget("getEmptyAlias")));
         assertEquals("get-with-alias", Adapter.detmGetterPropName(mget("getWithAlias")));
         assertEquals("plain", Adapter.detmGetterPropName(mget("getPlain")));
         assertEquals("primBool", Adapter.detmGetterPropName(mget("isPrimBool")));
@@ -222,7 +223,7 @@ public class AdapterTest {
 
     @Test
     public void testDetmSetterPropName() {
-        assertEquals("emptyAlias", Adapter.detmSetterPropName(mset("setEmptyAlias")));
+        assertEquals(EMPTY_ALIAS, Adapter.detmSetterPropName(mset("setEmptyAlias")));
         assertEquals("set-with-alias", Adapter.detmSetterPropName(mset("setWithAlias")));
         assertEquals("plain", Adapter.detmSetterPropName(mset("setPlain")));
         assertEquals(null, Adapter.detmSetterPropName(mset("noSet")));
@@ -236,8 +237,8 @@ public class AdapterTest {
     }
 
     @Test
-    public void testGetQualifiedNameMethod() throws Exception {
-        assertEquals(MY_NAME + ".getValue", Adapter.getQualifiedName(mget(GET_VALUE_NAME)));
+    public void testGetQualifiedNameMethod() {
+        assertEquals(MY_NAME + GET_VALUE, Adapter.getQualifiedName(mget(GET_VALUE_NAME)));
     }
 
     /**
index 7512842..f68e3e3 100644 (file)
@@ -36,7 +36,6 @@ import java.util.Set;
 import org.junit.Before;
 import org.junit.Test;
 import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.AnyGetterSerializer;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
 
 public class AnyGetterSerializerTest {
@@ -61,7 +60,7 @@ public class AnyGetterSerializerTest {
     }
 
     @Test
-    public void testAddToTree_testCopyLiftedItems() throws Exception {
+    public void testAddToTree_testCopyLiftedItems() {
         JsonObject tree = new JsonObject();
         tree.addProperty("hello", "world");
 
@@ -84,7 +83,7 @@ public class AnyGetterSerializerTest {
     }
 
     @Test
-    public void testAddToTree_NullMap() throws Exception {
+    public void testAddToTree_NullMap() {
         JsonObject tree = new JsonObject();
         tree.addProperty("hello", "world");
 
index b180605..c03e369 100644 (file)
@@ -36,7 +36,6 @@ import java.util.TreeMap;
 import org.junit.Before;
 import org.junit.Test;
 import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.AnySetterDeserializer;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
 
 public class AnySetterDeserializerTest {
index 1a15be0..6af4ae4 100644 (file)
@@ -42,11 +42,11 @@ import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
 import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-import org.onap.policy.common.gson.internal.Adapter;
-import org.onap.policy.common.gson.internal.ClassWalker;
 
 public class ClassWalkerTest {
 
+    private static final String SET_OVERRIDE = ".setOverride";
+
     private MyWalker walker;
 
     /**
@@ -63,12 +63,12 @@ public class ClassWalkerTest {
 
         assertEquals("[Intfc1, Intfc2, Intfc1, Intfc3, Bottom, DerivedFromBottom]", walker.classes.toString());
 
-        List<String> inFields = walker.getInProps(Field.class).stream().map(field -> field.getName())
+        List<String> inFields = walker.getInProps(Field.class).stream().map(Field::getName)
                         .collect(Collectors.toList());
         Collections.sort(inFields);
         assertEquals("[exposedField, overriddenValue, transField]", inFields.toString());
 
-        List<String> outFields = walker.getInProps(Field.class).stream().map(field -> field.getName())
+        List<String> outFields = walker.getInProps(Field.class).stream().map(Field::getName)
                         .collect(Collectors.toList());
         Collections.sort(outFields);
         assertEquals("[exposedField, overriddenValue, transField]", outFields.toString());
@@ -125,7 +125,7 @@ public class ClassWalkerTest {
         assertNotNull(walker.getAnyGetter());
         assertEquals("getTheMap", walker.getAnyGetter().getName());
 
-        List<String> getters = walker.getOutProps(Method.class).stream().map(method -> method.getName())
+        List<String> getters = walker.getOutProps(Method.class).stream().map(Method::getName)
                         .collect(Collectors.toList());
         Collections.sort(getters);
         assertEquals("[getId, getOnlyOut, getValue]", getters.toString());
@@ -133,7 +133,7 @@ public class ClassWalkerTest {
         assertNotNull(walker.getAnySetter());
         assertEquals("setMapValue", walker.getAnySetter().getName());
 
-        List<String> setters = walker.getInProps(Method.class).stream().map(method -> method.getName())
+        List<String> setters = walker.getInProps(Method.class).stream().map(Method::getName)
                         .collect(Collectors.toList());
         Collections.sort(setters);
         assertEquals("[setId, setOnlyIn, setValue]", setters.toString());
@@ -146,17 +146,17 @@ public class ClassWalkerTest {
         // setter with too few parameters
         assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterTooFewParams.class))
                         .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_MISMATCH_ERR
-                                        + AnySetterTooFewParams.class.getName() + ".setOverride");
+                                        + AnySetterTooFewParams.class.getName() + SET_OVERRIDE);
 
         // setter with too many parameters
         assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterTooManyParams.class))
                         .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_MISMATCH_ERR
-                                        + AnySetterTooManyParams.class.getName() + ".setOverride");
+                                        + AnySetterTooManyParams.class.getName() + SET_OVERRIDE);
 
         // setter with invalid parameter type
         assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterInvalidParam.class))
                         .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_TYPE_ERR
-                                        + AnySetterInvalidParam.class.getName() + ".setOverride");
+                                        + AnySetterInvalidParam.class.getName() + SET_OVERRIDE);
     }
 
     @Test
@@ -317,10 +317,12 @@ public class ClassWalkerTest {
 
         private String value;
 
+        @Override
         public String getValue() {
             return value;
         }
 
+        @Override
         public void setValue(String value) {
             this.value = value;
         }
index 62bab23..509ddb7 100644 (file)
@@ -34,7 +34,6 @@ import java.util.List;
 import org.junit.Test;
 import org.onap.policy.common.gson.JacksonExclusionStrategy;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-import org.onap.policy.common.gson.internal.FieldDeserializer;
 
 public class FieldDeserializerTest {
     private static final String TEXT_FIELD_NAME = "text";
index 18167fc..cc5ef92 100644 (file)
@@ -33,7 +33,6 @@ import java.util.List;
 import org.junit.Test;
 import org.onap.policy.common.gson.JacksonExclusionStrategy;
 import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-import org.onap.policy.common.gson.internal.FieldSerializer;
 
 public class FieldSerializerTest {
     private static final String TEXT_FIELD_NAME = "text";
index a75fe17..6be4e59 100644 (file)
@@ -135,7 +135,7 @@ public class JacksonTypeAdapterTest {
 
         String data = stringAdapter.read(new JsonReader(new StringReader("'read text'".replace('\'', '"'))));
 
-        assertEquals("read text", data.toString());
+        assertEquals("read text", data);
     }
 
     private static class Data {
index 55a3b67..e0b9eb3 100644 (file)
@@ -28,7 +28,6 @@ import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Set;
 import org.junit.Test;
-import org.onap.policy.common.gson.internal.Lifter;
 
 public class LifterTest {
 
index ef002f5..73c6165 100644 (file)
@@ -39,7 +39,7 @@ public abstract class NoopTopicEndpoint extends TopicBase {
     private static Logger logger = LoggerFactory.getLogger(NoopTopicEndpoint.class);
 
     /**
-     * {@inheritDoc}.
+     * Constructs the object.
      */
     public NoopTopicEndpoint(List<String> servers, String topic) {
         super(servers, topic);
index d374594..c52a30b 100644 (file)
@@ -35,7 +35,7 @@ public class NoopTopicSink extends NoopTopicEndpoint implements TopicSink {
     public static final NoopTopicSinkFactory factory = new NoopTopicSinkFactory();
 
     /**
-     * {@inheritDoc}.
+     * Constructs the object.
      */
     public NoopTopicSink(List<String> servers, String topic) {
         super(servers, topic);
index 95ed0fe..a5b9349 100644 (file)
@@ -35,7 +35,7 @@ public class NoopTopicSource extends NoopTopicEndpoint implements TopicSource {
     public static final NoopTopicSourceFactory factory = new NoopTopicSourceFactory();
 
     /**
-     * {@inheritDoc}.
+     * Constructs the object.
      */
     public NoopTopicSource(List<String> servers, String topic) {
         super(servers, topic);
index e20fb59..abf793d 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -31,7 +31,8 @@ import java.security.GeneralSecurityException;
 import java.util.ArrayList;
 import java.util.Map;
 import java.util.Properties;
-
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.dmaap.mr.client.MRClientFactory;
 import org.onap.dmaap.mr.client.impl.MRConsumerImpl;
@@ -112,7 +113,7 @@ public interface BusConsumer {
         /**
          * close condition.
          */
-        protected Object closeCondition = new Object();
+        protected CountDownLatch closeCondition = new CountDownLatch(1);
 
         /**
          * Cambria Consumer Wrapper.
@@ -172,10 +173,9 @@ public interface BusConsumer {
                 return getCurrentConsumer().fetch();
             } catch (final IOException e) {
                 logger.error("{}: cannot fetch because of {} - backoff for {} ms.", this, e.getMessage(),
-                        this.fetchTimeout);
-                synchronized (this.closeCondition) {
-                    this.closeCondition.wait(this.fetchTimeout);
-                }
+                        this.fetchTimeout, e);
+
+                this.closeCondition.await(this.fetchTimeout, TimeUnit.MILLISECONDS);
 
                 throw e;
             }
@@ -183,10 +183,7 @@ public interface BusConsumer {
 
         @Override
         public void close() {
-            synchronized (closeCondition) {
-                closeCondition.notifyAll();
-            }
-
+            this.closeCondition.countDown();
             getCurrentConsumer().close();
         }
 
@@ -267,7 +264,7 @@ public interface BusConsumer {
         /**
          * close condition.
          */
-        protected Object closeCondition = new Object();
+        protected CountDownLatch closeCondition = new CountDownLatch(1);
 
         /**
          * MR Consumer.
@@ -276,7 +273,7 @@ public interface BusConsumer {
 
         /**
          * MR Consumer Wrapper.
-         * 
+         *
          * <p>servers          messaging bus hosts
          * topic            topic
          * apiKey           API Key
@@ -314,12 +311,10 @@ public interface BusConsumer {
             if (response == null) {
                 logger.warn("{}: DMaaP NULL response received", this);
 
-                synchronized (closeCondition) {
-                    closeCondition.wait(fetchTimeout);
-                }
+                closeCondition.await(fetchTimeout, TimeUnit.MILLISECONDS);
                 return new ArrayList<>();
             } else {
-                logger.debug("DMaaP consumer received {} : {}" + response.getResponseCode(),
+                logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(),
                         response.getResponseMessage());
 
                 if (!"200".equals(response.getResponseCode())) {
@@ -327,9 +322,7 @@ public interface BusConsumer {
                     logger.error("DMaaP consumer received: {} : {}", response.getResponseCode(),
                             response.getResponseMessage());
 
-                    synchronized (closeCondition) {
-                        closeCondition.wait(fetchTimeout);
-                    }
+                    closeCondition.await(fetchTimeout, TimeUnit.MILLISECONDS);
 
                     /* fall through */
                 }
@@ -344,10 +337,7 @@ public interface BusConsumer {
 
         @Override
         public void close() {
-            synchronized (closeCondition) {
-                closeCondition.notifyAll();
-            }
-
+            this.closeCondition.countDown();
             this.consumer.close();
         }
 
@@ -372,7 +362,7 @@ public interface BusConsumer {
         /**
          * BusTopicParams contain the following parameters.
          * MR Consumer Wrapper.
-         * 
+         *
          * <p>servers messaging bus hosts
          * topic topic
          * apiKey API Key
@@ -432,9 +422,9 @@ public interface BusConsumer {
 
         /**
          * Constructor.
-         * 
+         *
          * @param busTopicParams topic paramters
-         * 
+         *
          * @throws MalformedURLException must provide a valid URL
          */
         public DmaapDmeConsumerWrapper(BusTopicParams busTopicParams) throws MalformedURLException {
index 1c2d6ee..1c85fa9 100644 (file)
@@ -8,9 +8,9 @@
  * 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.
@@ -49,7 +49,7 @@ public interface BusPublisher {
 
     /**
      * sends a message.
-     * 
+     *
      * @param partitionId id
      * @param message the message
      * @return true if success, false otherwise
@@ -74,11 +74,11 @@ public interface BusPublisher {
          */
         @JsonIgnore
         @GsonJsonIgnore
-        protected volatile CambriaBatchingPublisher publisher;
+        protected CambriaBatchingPublisher publisher;
 
         /**
          * Constructor.
-         * 
+         *
          * @param busTopicParams topic parameters
          */
         public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
@@ -290,10 +290,10 @@ public interface BusPublisher {
     }
 
     public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper {
-        
+
         /**
          * Constructor.
-         * 
+         *
          * @param busTopicParams topic parameters
          */
         public DmaapDmePublisherWrapper(BusTopicParams busTopicParams) {
index b7bafe0..0aaf1cc 100644 (file)
@@ -145,14 +145,14 @@ public class JettyJerseyServer extends JettyServletServer {
      */
     protected synchronized ServletHolder getServlet(String servletPath) {
 
-        ServletHolder jerseyServlet = servlets.get(servletPath);
-        if (jerseyServlet == null) {
-            jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, servletPath);
+        return servlets.computeIfAbsent(servletPath, key -> {
+
+            ServletHolder jerseyServlet =
+                            context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, servletPath);
             jerseyServlet.setInitOrder(0);
-            servlets.put(servletPath, jerseyServlet);
-        }
 
-        return jerseyServlet;
+            return jerseyServlet;
+        });
     }
 
     @Override
@@ -238,7 +238,7 @@ public class JettyJerseyServer extends JettyServletServer {
         }
 
         jerseyServlet.setInitParameter(ServerProperties.PROVIDER_CLASSNAMES, initClasses);
-        
+
         jerseyServlet.setInitParameter(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
     }
 
index 919397d..b5c9e61 100644 (file)
@@ -34,7 +34,7 @@ import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperti
 import java.util.Arrays;
 import java.util.List;
 import java.util.Properties;
-import java.util.function.Function;
+import java.util.function.Predicate;
 import org.onap.policy.common.endpoints.event.comm.Topic;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 
@@ -192,7 +192,7 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
      * @param values the values to which the property should be set, defaults to
      *        {@code null} and ""
      */
-    protected void checkDefault(String builderName, Function<BusTopicParams, Boolean> validate, Object... values) {
+    protected void checkDefault(String builderName, Predicate<BusTopicParams> validate, Object... values) {
         Object[] values2 = (values.length > 0 ? values : new Object[] {null, ""});
 
         for (Object value : values2) {
@@ -209,7 +209,7 @@ public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFact
             }
 
             assertEquals("size for default " + value, 1, buildTopics(builder.build()).size());
-            assertTrue("default for " + value, validate.apply(getLastParams()));
+            assertTrue("default for " + value, validate.test(getLastParams()));
         }
     }
 
index b4c7fff..6c9dfcb 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -41,6 +41,7 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
      * Creates the object to be tested.
      */
     @Before
+    @Override
     public void setUp() {
         super.setUp();
 
@@ -53,17 +54,20 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
     }
 
     @Test
+    @Override
     public void testBuildBusTopicParams() {
         super.testBuildBusTopicParams();
         super.testBuildBusTopicParams_Ex();
     }
 
     @Test
+    @Override
     public void testBuildListOfStringString() {
         super.testBuildListOfStringString();
     }
 
     @Test
+    @Override
     public void testBuildProperties() {
         super.testBuildProperties();
         super.testBuildProperties_Variations();
@@ -75,12 +79,14 @@ public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTo
     }
 
     @Test
+    @Override
     public void testDestroyString_testGet_testInventory() {
         super.testDestroyString_testGet_testInventory();
         super.testDestroyString_Ex();
     }
 
     @Test
+    @Override
     public void testDestroy() {
         super.testDestroy();
     }
index ec6fcfc..d618742 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine - Common Modules
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -44,6 +44,7 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
      * Creates the object to be tested.
      */
     @Before
+    @Override
     public void setUp() {
         super.setUp();
 
@@ -56,12 +57,14 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
     }
 
     @Test
+    @Override
     public void testBuildBusTopicParams() {
         super.testBuildBusTopicParams();
         super.testBuildBusTopicParams_Ex();
     }
 
     @Test
+    @Override
     public void testBuildProperties() {
         super.testBuildProperties();
 
@@ -79,7 +82,7 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
         checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX,
             params2 -> params2.getFetchLimit() == DmaapTopicSource.DEFAULT_LIMIT_FETCH,
             null, "", "invalid-limit-number");
-        
+
         checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX,
             params2 -> params2.getFetchTimeout() == DmaapTopicSource.DEFAULT_TIMEOUT_MS_FETCH,
             null, "", "invalid-timeout-number");
@@ -99,6 +102,7 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
     }
 
     @Test
+    @Override
     public void testBuildListOfStringString() {
         super.testBuildListOfStringString();
 
@@ -111,12 +115,14 @@ public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<Dmaap
     }
 
     @Test
+    @Override
     public void testDestroyString_testGet_testInventory() {
         super.testDestroyString_testGet_testInventory();
         super.testDestroyString_Ex();
     }
 
     @Test
+    @Override
     public void testDestroy() {
         super.testDestroy();
     }
index c9064d4..ae07798 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -47,6 +47,7 @@ import org.powermock.reflect.Whitebox;
 public class BusConsumerTest extends TopicTestBase {
 
     @Before
+    @Override
     public void setUp() {
         super.setUp();
     }
@@ -88,13 +89,17 @@ public class BusConsumerTest extends TopicTestBase {
             cons.fetch();
             fail("missing exception");
 
-        } catch (IOException | InterruptedException e) {
+        } catch (IOException e) {
+            assertEquals(ex, e);
+
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
             assertEquals(ex, e);
         }
     }
 
     @Test
-    public void testCambriaConsumerWrapperClose() throws Exception {
+    public void testCambriaConsumerWrapperClose() {
         CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build());
 
         // set filter several times to cause different branches of close() to be executed
index 9c1e4af..283d44d 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -48,6 +48,7 @@ import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.Dma
 public class BusPublisherTest extends TopicTestBase {
 
     @Before
+    @Override
     public void setUp() {
         super.setUp();
     }
@@ -90,7 +91,7 @@ public class BusPublisherTest extends TopicTestBase {
     }
 
     @Test
-    public void testCambriaPublisherWrapperClose() throws Exception {
+    public void testCambriaPublisherWrapperClose() {
         CambriaBatchingPublisher pub = mock(CambriaBatchingPublisher.class);
         CambriaPublisherWrapper cambria = new CambriaPublisherWrapper(makeBuilder().build());
         cambria.publisher = pub;
@@ -146,7 +147,7 @@ public class BusPublisherTest extends TopicTestBase {
     }
 
     @Test
-    public void testDmaapPublisherWrapperSend() throws Exception {
+    public void testDmaapPublisherWrapperSend() {
         MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class);
         DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASSWD, true);
         dmaap.publisher = pub;
@@ -168,7 +169,7 @@ public class BusPublisherTest extends TopicTestBase {
     }
 
     @Test(expected = IllegalArgumentException.class)
-    public void testDmaapPublisherWrapperSend_NullMessage() throws Exception {
+    public void testDmaapPublisherWrapperSend_NullMessage() {
         MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class);
         DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASSWD, true);
         dmaap.publisher = pub;
index 8d1c634..54531c5 100644 (file)
@@ -35,6 +35,7 @@ import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.T
 public class BusTopicParamsTest extends TopicTestBase {
 
     @Before
+    @Override
     public void setUp() {
         super.setUp();
     }
@@ -123,7 +124,7 @@ public class BusTopicParamsTest extends TopicTestBase {
      * Tests the boolean methods by applying a function, once with {@code false} and once
      * with {@code true}. Verifies that all of the boolean methods return the correct
      * value by concatenating them.
-     * 
+     *
      * @param expectedTrue the string that is expected when {@code true} is passed to the
      *        method
      * @param function function to be applied to the builder
index 1f1f117..4f7a5a9 100644 (file)
@@ -47,6 +47,20 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 import org.onap.policy.common.utils.network.NetworkUtil;
 
 public class HttpClientTest {
+    private static final String TEST_HTTP_NO_AUTH_CLIENT = "testHttpNoAuthClient";
+    private static final String TEST_HTTP_AUTH_CLIENT = "testHttpAuthClient";
+    private static final String LOCALHOST = "localhost";
+    private static final String JUNIT_ECHO = "junit/echo";
+    private static final String HELLO = "hello";
+    private static final String MY_VALUE = "myValue";
+    private static final String FALSE_STRING = "false";
+    private static final String ALPHA123 = "alpha123";
+    private static final String PUT_HELLO = "PUT:hello:{myParameter=myValue}";
+    private static final String DOT_GSON = "." + "GSON";
+    private static final String DOT_JACKSON = "." + "JACKSON";
+    private static final String DOT_PDP = "." + "PDP";
+    private static final String DOT_PAP = "." + "PAP";
+
     private static final HashMap<String, String> savedValuesMap = new HashMap<>();
 
     /**
@@ -60,11 +74,11 @@ public class HttpClientTest {
         /* echo server - http + no auth */
 
         final HttpServletServer echoServerNoAuth =
-                HttpServletServer.factory.build("echo", "localhost", 6666, "/", false, true);
+                HttpServletServer.factory.build("echo", LOCALHOST, 6666, "/", false, true);
         echoServerNoAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName());
         echoServerNoAuth.waitedStart(5000);
 
-        if (!NetworkUtil.isTcpPortOpen("localhost", echoServerNoAuth.getPort(), 5, 10000L)) {
+        if (!NetworkUtil.isTcpPortOpen(LOCALHOST, echoServerNoAuth.getPort(), 5, 10000L)) {
             throw new IllegalStateException("cannot connect to port " + echoServerNoAuth.getPort());
         }
 
@@ -101,7 +115,7 @@ public class HttpClientTest {
         /* echo server - https + basic auth */
 
         final HttpServletServer echoServerAuth =
-                HttpServletServer.factory.build("echo", true, "localhost", 6667, "/", false, true);
+                HttpServletServer.factory.build("echo", true, LOCALHOST, 6667, "/", false, true);
         echoServerAuth.setBasicAuthentication("x", "y", null);
         echoServerAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName());
         echoServerAuth.addFilterClass("/*", TestFilter.class.getCanonicalName());
@@ -110,7 +124,7 @@ public class HttpClientTest {
         echoServerAuth.addFilterClass("/*", TestAafGranularAuthFilter.class.getCanonicalName());
         echoServerAuth.waitedStart(5000);
 
-        if (!NetworkUtil.isTcpPortOpen("localhost", echoServerAuth.getPort(), 5, 10000L)) {
+        if (!NetworkUtil.isTcpPortOpen(LOCALHOST, echoServerAuth.getPort(), 5, 10000L)) {
             throw new IllegalStateException("cannot connect to port " + echoServerAuth.getPort());
         }
     }
@@ -171,34 +185,34 @@ public class HttpClientTest {
 
     @Test
     public void testHttpGetNoAuthClient() throws Exception {
-        final HttpClient client = getNoAuthHttpClient("testHttpNoAuthClient", false,
+        final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
             6666);
-        final Response response = client.get("hello");
+        final Response response = client.get(HELLO);
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("hello", body);
+        assertEquals(HELLO, body);
     }
 
     @Test
     public void testHttpPutNoAuthClient() throws Exception {
-        final HttpClient client = getNoAuthHttpClient("testHttpNoAuthClient", false, 6666);
+        final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666);
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
-        final Response response = client.put("hello", entity, Collections.emptyMap());
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+        final Response response = client.put(HELLO, entity, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
     }
 
     @Test
     public void testHttpPostNoAuthClient() throws Exception {
-        final HttpClient client = getNoAuthHttpClient("testHttpNoAuthClient", false,
+        final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
             6666);
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
-        final Response response = client.post("hello", entity, Collections.emptyMap());
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+        final Response response = client.post(HELLO, entity, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
@@ -207,10 +221,10 @@ public class HttpClientTest {
 
     @Test
     public void testHttpDeletetNoAuthClient() throws Exception {
-        final HttpClient client = getNoAuthHttpClient("testHttpNoAuthClient", false,
+        final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false,
             6666);
 
-        final Response response = client.delete("hello", Collections.emptyMap());
+        final Response response = client.delete(HELLO, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
@@ -221,38 +235,38 @@ public class HttpClientTest {
     public void testHttpGetAuthClient() throws Exception {
         final HttpClient client = getAuthHttpClient();
 
-        final Response response = client.get("hello");
+        final Response response = client.get(HELLO);
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("hello", body);
+        assertEquals(HELLO, body);
     }
 
     @Test
     public void testHttpPutAuthClient() throws Exception {
         final HttpClient client = getAuthHttpClient();
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
-        final Response response = client.put("hello", entity, Collections.emptyMap());
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+        final Response response = client.put(HELLO, entity, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
     }
 
     @Test
     public void testHttpPutAuthClient_JacksonProvider() throws Exception {
-        final HttpClient client = HttpClient.factory.build(BusTopicParams.builder().clientName("testHttpAuthClient")
-                        .useHttps(true).allowSelfSignedCerts(true).hostname("localhost").port(6667)
-                        .basePath("junit/echo").userName("x").password("y").managed(true)
+        final HttpClient client = HttpClient.factory.build(BusTopicParams.builder().clientName(TEST_HTTP_AUTH_CLIENT)
+                        .useHttps(true).allowSelfSignedCerts(true).hostname(LOCALHOST).port(6667)
+                        .basePath(JUNIT_ECHO).userName("x").password("y").managed(true)
                         .serializationProvider(MyJacksonProvider.class.getCanonicalName()).build());
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
-        final Response response = client.put("hello", entity, Collections.emptyMap());
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+        final Response response = client.put(HELLO, entity, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
 
         assertTrue(MyJacksonProvider.hasWrittenSome());
 
@@ -261,17 +275,17 @@ public class HttpClientTest {
 
     @Test
     public void testHttpPutAuthClient_GsonProvider() throws Exception {
-        final HttpClient client = HttpClient.factory.build(BusTopicParams.builder().clientName("testHttpAuthClient")
-                        .useHttps(true).allowSelfSignedCerts(true).hostname("localhost").port(6667)
-                        .basePath("junit/echo").userName("x").password("y").managed(true)
+        final HttpClient client = HttpClient.factory.build(BusTopicParams.builder().clientName(TEST_HTTP_AUTH_CLIENT)
+                        .useHttps(true).allowSelfSignedCerts(true).hostname(LOCALHOST).port(6667)
+                        .basePath(JUNIT_ECHO).userName("x").password("y").managed(true)
                         .serializationProvider(MyGsonProvider.class.getCanonicalName()).build());
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
-        final Response response = client.put("hello", entity, Collections.emptyMap());
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
+        final Response response = client.put(HELLO, entity, Collections.emptyMap());
         final String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
 
         assertTrue(MyGsonProvider.hasWrittenSome());
 
@@ -282,7 +296,7 @@ public class HttpClientTest {
     public void testHttpAuthClient401() throws Exception {
         final HttpClient client = getNoAuthHttpClient("testHttpAuthClient401", true,
             6667);
-        final Response response = client.get("hello");
+        final Response response = client.get(HELLO);
         assertEquals(401, response.getStatus());
     }
 
@@ -291,70 +305,70 @@ public class HttpClientTest {
         final Properties httpProperties = new Properties();
 
         httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "PAP,PDP");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, ALPHA123);
         httpProperties.setProperty(
-                PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                        + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
-                RestMockHealthCheck.class.getName());
+                        PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                                        + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
+                        RestMockHealthCheck.class.getName());
         httpProperties.setProperty(
-            PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX,
-            TestFilter.class.getName());
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
-
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123");
+                        PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP
+                                        + PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX,
+                        TestFilter.class.getName());
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, ALPHA123);
         httpProperties.setProperty(
-                PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP"
-                        + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
-                RestMockHealthCheck.class.getName());
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+                        PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP
+                                        + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
+                        RestMockHealthCheck.class.getName());
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
 
         httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "PAP,PDP");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pap/test");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
-
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pdp");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pap/test");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, ALPHA123);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pdp");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, ALPHA123);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
 
         final List<HttpServletServer> servers = HttpServletServer.factory.build(httpProperties);
         assertEquals(2, servers.size());
@@ -383,51 +397,51 @@ public class HttpClientTest {
         final Properties httpProperties = new Properties();
 
         httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "GSON,JACKSON");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "junit/echo");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, JUNIT_ECHO);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
         httpProperties.setProperty(
-                        PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "GSON"
+                        PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_GSON
                                         + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
                         MyGsonProvider.class.getCanonicalName());
 
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "junit/echo");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
-                + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
-        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
-                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "6666");
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, JUNIT_ECHO);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
+                        + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING);
+        httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
+                        + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
         httpProperties.setProperty(
-                        PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "JACKSON"
+                        PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_JACKSON
                                         + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
                         MyJacksonProvider.class.getCanonicalName());
 
         final List<HttpClient> clients = HttpClient.factory.build(httpProperties);
         assertEquals(2, clients.size());
 
-        Entity<MyEntity> entity = Entity.entity(new MyEntity("myValue"), MediaType.APPLICATION_JSON);
+        Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON);
 
         // use gson client
         MyGsonProvider.resetSome();
         MyJacksonProvider.resetSome();
         HttpClient client = HttpClient.factory.get("GSON");
 
-        Response response = client.put("hello", entity, Collections.emptyMap());
+        Response response = client.put(HELLO, entity, Collections.emptyMap());
         String body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
 
         assertTrue(MyGsonProvider.hasWrittenSome());
         assertFalse(MyJacksonProvider.hasWrittenSome());
@@ -437,11 +451,11 @@ public class HttpClientTest {
         MyJacksonProvider.resetSome();
         client = HttpClient.factory.get("JACKSON");
 
-        response = client.put("hello", entity, Collections.emptyMap());
+        response = client.put(HELLO, entity, Collections.emptyMap());
         body = HttpClient.getBody(response, String.class);
 
         assertEquals(200, response.getStatus());
-        assertEquals("PUT:hello:{myParameter=myValue}", body);
+        assertEquals(PUT_HELLO, body);
 
         assertTrue(MyJacksonProvider.hasWrittenSome());
         assertFalse(MyGsonProvider.hasWrittenSome());
@@ -449,15 +463,15 @@ public class HttpClientTest {
 
     private HttpClient getAuthHttpClient()
                     throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
-        return HttpClient.factory.build(BusTopicParams.builder().clientName("testHttpAuthClient")
-            .useHttps(true).allowSelfSignedCerts(true).hostname("localhost").port(6667).basePath("junit/echo")
+        return HttpClient.factory.build(BusTopicParams.builder().clientName(TEST_HTTP_AUTH_CLIENT)
+            .useHttps(true).allowSelfSignedCerts(true).hostname(LOCALHOST).port(6667).basePath(JUNIT_ECHO)
             .userName("x").password("y").managed(true).build());
     }
 
     private HttpClient getNoAuthHttpClient(String clientName, boolean https, int port)
         throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
         return HttpClient.factory.build(BusTopicParams.builder().clientName(clientName)
-            .useHttps(https).allowSelfSignedCerts(https).hostname("localhost").port(port).basePath("junit/echo")
+            .useHttps(https).allowSelfSignedCerts(https).hostname(LOCALHOST).port(port).basePath(JUNIT_ECHO)
             .userName(null).password(null).managed(true).build());
     }
 
index 972fc66..3ae39eb 100644 (file)
@@ -47,6 +47,12 @@ import org.slf4j.LoggerFactory;
  * HttpServletServer JUNIT tests.
  */
 public class HttpServerTest {
+    private static final String LOCALHOST = "localhost";
+    private static final String SWAGGER_JSON = "/swagger.json";
+    private static final String JUNIT_ECHO_HELLO = "/junit/echo/hello";
+    private static final String JUNIT_ECHO_FULL_REQUEST = "/junit/echo/full/request";
+    private static final String SOME_TEXT = "some text";
+    private static final String HELLO = "hello";
 
     /**
      * Logger.
@@ -87,7 +93,7 @@ public class HttpServerTest {
     public void testDefaultPackageServer() throws Exception {
         logger.info("-- testDefaultPackageServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.addServletPackage("/*", this.getClass().getPackage().getName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
         server.waitedStart(5000);
@@ -96,10 +102,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
     }
 
@@ -107,7 +113,7 @@ public class HttpServerTest {
     public void testJacksonPackageServer() throws Exception {
         logger.info("-- testJacksonPackageServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
 
         server.setSerializationProvider(MyJacksonProvider.class.getCanonicalName());
         server.addServletPackage("/*", this.getClass().getPackage().getName());
@@ -118,10 +124,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
 
         assertTrue(MyJacksonProvider.hasReadSome());
@@ -135,7 +141,7 @@ public class HttpServerTest {
     public void testGsonPackageServer() throws Exception {
         logger.info("-- testGsonPackageServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
 
         server.setSerializationProvider(MyGsonProvider.class.getCanonicalName());
         server.addServletPackage("/*", this.getClass().getPackage().getName());
@@ -146,10 +152,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
 
         assertTrue(MyGsonProvider.hasReadSome());
@@ -163,7 +169,7 @@ public class HttpServerTest {
     public void testDefaultClassServer() throws Exception {
         logger.info("-- testDefaultClassServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.addServletClass("/*", RestEchoService.class.getCanonicalName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
         server.waitedStart(5000);
@@ -172,10 +178,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
     }
 
@@ -183,7 +189,7 @@ public class HttpServerTest {
     public void testJacksonClassServer() throws Exception {
         logger.info("-- testJacksonClassServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.setSerializationProvider(MyJacksonProvider.class.getCanonicalName());
         server.addServletClass("/*", RestEchoService.class.getCanonicalName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
@@ -193,10 +199,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
 
         assertTrue(MyJacksonProvider.hasReadSome());
@@ -210,7 +216,7 @@ public class HttpServerTest {
     public void testGsonClassServer() throws Exception {
         logger.info("-- testGsonClassServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.setSerializationProvider(MyGsonProvider.class.getCanonicalName());
         server.addServletClass("/*", RestEchoService.class.getCanonicalName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
@@ -220,10 +226,10 @@ public class HttpServerTest {
 
         RestEchoReqResp request = new RestEchoReqResp();
         request.setRequestId(100);
-        request.setText("some text");
+        request.setText(SOME_TEXT);
         String reqText = gson.toJson(request);
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/full/request", reqText);
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText);
         assertEquals(reqText, response);
 
         assertTrue(MyGsonProvider.hasReadSome());
@@ -235,7 +241,7 @@ public class HttpServerTest {
 
     @Test
     public void testSerialize() {
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.addServletPackage("/*", this.getClass().getPackage().getName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
 
@@ -247,7 +253,7 @@ public class HttpServerTest {
     public void testSingleServer() throws Exception {
         logger.info("-- testSingleServer() --");
 
-        HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build("echo", LOCALHOST, port, "/", false, true);
         server.addServletPackage("/*", this.getClass().getPackage().getName());
         server.addFilterClass("/*", TestFilter.class.getCanonicalName());
         server.waitedStart(5000);
@@ -255,12 +261,12 @@ public class HttpServerTest {
         assertTrue(HttpServletServer.factory.get(port).isAlive());
         assertFalse(HttpServletServer.factory.get(port).isAaf());
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO);
+        assertEquals(HELLO, response);
 
         response = null;
         try {
-            response = http(HttpServletServer.factory.get(port), portUrl + "/swagger.json");
+            response = http(HttpServletServer.factory.get(port), portUrl + SWAGGER_JSON);
         } catch (IOException e) {
             // Expected
         }
@@ -283,38 +289,38 @@ public class HttpServerTest {
     public void testMultipleServers() throws Exception {
         logger.info("-- testMultipleServers() --");
 
-        HttpServletServer server1 = HttpServletServer.factory.build("echo-1", false,"localhost", port, "/", true, true);
+        HttpServletServer server1 = HttpServletServer.factory.build("echo-1", false,LOCALHOST, port, "/", true, true);
         server1.addServletPackage("/*", this.getClass().getPackage().getName());
         server1.waitedStart(5000);
 
         int port2 = port + 1;
 
-        HttpServletServer server2 = HttpServletServer.factory.build("echo-2", "localhost", port2, "/", false, true);
+        HttpServletServer server2 = HttpServletServer.factory.build("echo-2", LOCALHOST, port2, "/", false, true);
         server2.addServletPackage("/*", this.getClass().getPackage().getName());
         server2.waitedStart(5000);
 
         assertTrue(HttpServletServer.factory.get(port).isAlive());
         assertTrue(HttpServletServer.factory.get(port2).isAlive());
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO);
+        assertTrue(HELLO.equals(response));
 
-        response = http(HttpServletServer.factory.get(port), portUrl + "/swagger.json");
+        response = http(HttpServletServer.factory.get(port), portUrl + SWAGGER_JSON);
         assertTrue(response != null);
 
-        response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + JUNIT_ECHO_HELLO);
+        assertTrue(HELLO.equals(response));
 
         response = null;
         try {
-            response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + "/swagger.json");
+            response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + SWAGGER_JSON);
         } catch (IOException e) {
             // Expected
         }
         assertTrue(response == null);
 
         HttpServletServer.factory.destroy();
-        assertTrue(HttpServletServer.factory.inventory().size() == 0);
+        assertTrue(HttpServletServer.factory.inventory().isEmpty());
     }
 
     @Test
@@ -323,20 +329,20 @@ public class HttpServerTest {
 
         String randomName = UUID.randomUUID().toString();
 
-        HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build(randomName, LOCALHOST, port, "/", false, true);
         server.addServletPackage("/*", this.getClass().getPackage().getName());
         server.waitedStart(5000);
 
         assertTrue(HttpServletServer.factory.get(port).isAlive());
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO);
+        assertTrue(HELLO.equals(response));
 
         response = http(HttpServletServer.factory.get(port), portUrl + "/junit/endpoints/http/servers");
         assertTrue(response.contains(randomName));
 
         HttpServletServer.factory.destroy();
-        assertTrue(HttpServletServer.factory.inventory().size() == 0);
+        assertTrue(HttpServletServer.factory.inventory().isEmpty());
     }
 
     @Test
@@ -344,17 +350,17 @@ public class HttpServerTest {
         logger.info("-- testServiceClass() --");
         String randomName = UUID.randomUUID().toString();
 
-        HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build(randomName, LOCALHOST, port, "/", false, true);
         server.addServletClass("/*", RestEchoService.class.getCanonicalName());
         server.waitedStart(5000);
 
         assertTrue(HttpServletServer.factory.get(port).isAlive());
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO);
+        assertTrue(HELLO.equals(response));
 
         HttpServletServer.factory.destroy();
-        assertTrue(HttpServletServer.factory.inventory().size() == 0);
+        assertTrue(HttpServletServer.factory.inventory().isEmpty());
     }
 
     @Test
@@ -363,21 +369,21 @@ public class HttpServerTest {
 
         String randomName = UUID.randomUUID().toString();
 
-        HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", port, "/", false, true);
+        HttpServletServer server = HttpServletServer.factory.build(randomName, LOCALHOST, port, "/", false, true);
         server.addServletClass("/*", RestEchoService.class.getCanonicalName());
         server.addServletClass("/*", RestEndpoints.class.getCanonicalName());
         server.waitedStart(5000);
 
         assertTrue(HttpServletServer.factory.get(port).isAlive());
 
-        String response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello");
-        assertTrue("hello".equals(response));
+        String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO);
+        assertTrue(HELLO.equals(response));
 
         response = http(HttpServletServer.factory.get(port), portUrl + "/junit/endpoints/http/servers");
         assertTrue(response.contains(randomName));
 
         HttpServletServer.factory.destroy();
-        assertTrue(HttpServletServer.factory.inventory().size() == 0);
+        assertTrue(HttpServletServer.factory.inventory().isEmpty());
     }
 
     /**
@@ -388,7 +394,7 @@ public class HttpServerTest {
      * @throws InterruptedException thrown if thread interrupted occurs
      */
     protected String http(HttpServletServer server, String urlString)
-            throws MalformedURLException, IOException, InterruptedException {
+            throws IOException, InterruptedException {
         URL url = new URL(urlString);
         String response = null;
         int numRetries = 1;
@@ -418,7 +424,7 @@ public class HttpServerTest {
      * @throws InterruptedException thrown if thread interrupted occurs
      */
     protected String http(HttpServletServer server, String urlString, String post)
-            throws MalformedURLException, IOException, InterruptedException {
+            throws IOException, InterruptedException {
         URL url = new URL(urlString);
         String response = null;
         int numRetries = 1;
@@ -453,14 +459,14 @@ public class HttpServerTest {
      * @throws IOException if an I/O error occurs
      */
     protected String response(URLConnection conn) throws IOException {
-        String response = "";
+        StringBuilder response = new StringBuilder();
         try (BufferedReader ioReader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
             String line;
             while ((line = ioReader.readLine()) != null) {
-                response += line;
+                response.append(line);
             }
         }
-        return response;
+        return response.toString();
     }
 
 }
index d3354e4..f37f32a 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-management
  * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -61,7 +61,7 @@ public class GsonTestUtils {
     /**
      * Engine used to interpolate strings before they're compared.
      */
-    private static volatile ScriptEngine engineInstance = null;
+    private static ScriptEngine engineInstance = null;
 
     /**
      * Used to encode and decode an object via gson.
@@ -258,7 +258,7 @@ public class GsonTestUtils {
      */
     public String gsonEncode(Object object) {
         String sgson = gson.toJson(object);
-        logger.debug("gson=" + sgson);
+        logger.debug("gson={}", sgson);
         return sgson;
     }
 
index 3e4244d..466041e 100644 (file)
@@ -35,13 +35,11 @@ import org.junit.Test;
 
 public class GsonTestUtilsBuilderTest {
 
-    private GsonTestUtilsBuilder bldr;
     private GsonTestUtils utils;
 
     @Before
     public void setUp() {
-        bldr = new MyBuilder();
-        utils = bldr.build();
+        utils = new MyBuilder().build();
     }
 
     @Test
index ee66195..95abd4d 100644 (file)
@@ -44,6 +44,7 @@ import org.onap.policy.common.utils.io.Serializer.Factory;
 import org.powermock.reflect.Whitebox;
 
 public class SerializerTest {
+    private static final String FACTORY = "factory";
 
     /**
      * Saved and restored when tests complete. Also restored at the start of each test.
@@ -52,12 +53,12 @@ public class SerializerTest {
 
     @BeforeClass
     public static void setUpBeforeClass() {
-        saveFactory = Whitebox.getInternalState(Serializer.class, "factory");
+        saveFactory = Whitebox.getInternalState(Serializer.class, FACTORY);
     }
 
     @AfterClass
     public static void tearDownAfterClass() {
-        Whitebox.setInternalState(Serializer.class, "factory", saveFactory);
+        Whitebox.setInternalState(Serializer.class, FACTORY, saveFactory);
     }
 
     @Before
@@ -89,7 +90,7 @@ public class SerializerTest {
     }
 
     @Test
-    public void testSerialize_ArrayCloseEx() throws Exception {
+    public void testSerialize_ArrayCloseEx() {
         IOException ex = new IOException("testSerialize_ArrayCloseEx");
 
         /*
@@ -123,7 +124,7 @@ public class SerializerTest {
     }
 
     @Test
-    public void testSerialize_ObjectWriteEx() throws Exception {
+    public void testSerialize_ObjectWriteEx() {
         IOException ex = new IOException("testSerialize_ObjectWriteEx");
 
         /*
@@ -158,7 +159,7 @@ public class SerializerTest {
 
             @Override
             public void writeObject(Object object, ObjectOutputStream oos) throws IOException {
-                return;
+                // do nothing
             }
         });
 
@@ -205,7 +206,7 @@ public class SerializerTest {
 
             @Override
             public void writeObject(Object object, ObjectOutputStream oos) throws IOException {
-                return;
+                // do nothing
             }
         });
 
@@ -370,7 +371,7 @@ public class SerializerTest {
      * @param factory new factory to be set
      */
     private void setFactory(Factory factory) {
-        Whitebox.setInternalState(Serializer.class, "factory", factory);
+        Whitebox.setInternalState(Serializer.class, FACTORY, factory);
     }
 
     /**
index 710926d..8a60a5d 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * Common Utils-Test
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -27,7 +27,7 @@ import org.junit.Test;
 public class ConstructionErrorTest extends ErrorsTester {
 
     @Test
-    public void test() throws Exception {
+    public void test() {
         assertEquals(4, testAllError(ConstructionError.class));
     }
 
index 4d289c6..3cb53d8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Common Utils-Test
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -71,7 +71,7 @@ public class ThrowablesTesterTest {
 
     @Test(expected = ConstructionError.class)
     public void testThrowInstantiationException() {
-        new ThrowablesTester().testAllThrowable(ThrowInstantiationException.class);
+        new ThrowablesTester().testAllThrowable(ThrowInstantiationThrowable.class);
     }
 
     /**
@@ -159,10 +159,10 @@ public class ThrowablesTesterTest {
     /**
      * Used to test a failure case - throws InstantiationException when constructed.
      */
-    public static class ThrowInstantiationException extends Throwable {
+    public static class ThrowInstantiationThrowable extends Throwable {
         private static final long serialVersionUID = 1L;
 
-        public ThrowInstantiationException(String message, Throwable cause, boolean enableSuppression,
+        public ThrowInstantiationThrowable(String message, Throwable cause, boolean enableSuppression,
                 boolean writableStackTrace) throws InstantiationException {
 
             throw new InstantiationException(ThrowablesTester.EXPECTED_EXCEPTION_MSG);
index e01ed41..cd6edf7 100644 (file)
@@ -40,6 +40,16 @@ import org.junit.Test;
 import org.slf4j.LoggerFactory;
 
 public class ExtractAppenderTest {
+    private static final String ABC_DIGIT = "abc[0-9]";
+    private static final String ABC_DIGIT1 = "abc[1-9]";
+    private static final String DEF_DIGIT = "def[0-9]";
+    private static final String HELLO = "hello";
+    private static final String HELLO_ABC = "hello abc";
+    private static final String HELLO_ABC1_WORLD = "hello abc1 world";
+    private static final String HELLO_ABC3 = "hello abc3";
+    private static final String WORLD = "world";
+    private static final String WORLD_ABC = "world abc";
+    private static final String WORLD_GHI2_WORLD = "world ghi2 world";
 
     /**
      * Milliseconds to wait for a thread to terminate.
@@ -51,13 +61,13 @@ public class ExtractAppenderTest {
     private List<Thread> threads;
 
     @BeforeClass
-    public static void setUpBeforeClass() throws Exception {
+    public static void setUpBeforeClass() {
         logger = (Logger) LoggerFactory.getLogger(ExtractAppenderTest.class);
         logger.setLevel(Level.INFO);
     }
 
     @Before
-    public void setUp() throws Exception {
+    public void setUp() {
         threads = new LinkedList<>();
     }
 
@@ -88,31 +98,31 @@ public class ExtractAppenderTest {
 
         addAppender(appender);
 
-        logger.info("hello");
-        logger.info("world");
+        logger.info(HELLO);
+        logger.info(WORLD);
 
         // "append" should always be called
         assertEquals(2, count.get());
 
         // appender with no patterns - everything should match
-        assertEquals(strList("hello", "world"), appender.getExtracted());
+        assertEquals(strList(HELLO, WORLD), appender.getExtracted());
 
         // add a pattern and verify match
-        appender.setPattern("abc[0-9]");
+        appender.setPattern(ABC_DIGIT);
         logger.info("hello abc1");
 
         // this should not match
         logger.info("hello def2");
 
         assertEquals(4, count.get());
-        assertEquals(strList("hello", "world", "abc1"), appender.getExtracted());
+        assertEquals(strList(HELLO, WORLD, "abc1"), appender.getExtracted());
     }
 
     @Test
     public void testExtractAppenderStringArray() {
         AtomicInteger count = new AtomicInteger(0);
 
-        ExtractAppender appender = new ExtractAppender("abc[0-9]", "def[0-9]") {
+        ExtractAppender appender = new ExtractAppender(ABC_DIGIT, DEF_DIGIT) {
             @Override
             protected void append(ILoggingEvent event) {
                 count.incrementAndGet();
@@ -122,8 +132,8 @@ public class ExtractAppenderTest {
 
         addAppender(appender);
 
-        logger.info("hello abc1 world");
-        logger.info("world ghi2 world"); // no match
+        logger.info(HELLO_ABC1_WORLD);
+        logger.info(WORLD_GHI2_WORLD); // no match
         logger.info("world def3 world");
         logger.info("hello abc4");
         logger.info("abc5 world");
@@ -168,7 +178,7 @@ public class ExtractAppenderTest {
             }
         };
 
-        ExtractAppender appender = new ExtractAppender(queue, "abc[0-9]");
+        ExtractAppender appender = new ExtractAppender(queue, ABC_DIGIT);
         addAppender(appender);
 
         // these shouldn't match
@@ -182,7 +192,7 @@ public class ExtractAppenderTest {
 
         for (int x = 0; x < nmatches; ++x) {
             String msg = "abc" + x;
-            logger.info(msg + " world");
+            logger.info("{} world", msg);
 
             if (x < nallowed) {
                 expected.add(msg);
@@ -199,10 +209,10 @@ public class ExtractAppenderTest {
     public void testAppendILoggingEvent_NoPatterns() {
         ExtractAppender appender = makeAppender();
 
-        logger.info("hello");
-        logger.info("world");
+        logger.info(HELLO);
+        logger.info(WORLD);
 
-        assertEquals(strList("hello", "world"), appender.getExtracted());
+        assertEquals(strList(HELLO, WORLD), appender.getExtracted());
     }
 
     @Test
@@ -216,7 +226,7 @@ public class ExtractAppenderTest {
 
     @Test
     public void testAppendILoggingEvent_MatchFirstPattern() {
-        ExtractAppender appender = makeAppender("abc[0-9]", "def[0-9]");
+        ExtractAppender appender = makeAppender(ABC_DIGIT, DEF_DIGIT);
 
         logger.info("hello abc1");
         logger.info("world xyz2");
@@ -226,7 +236,7 @@ public class ExtractAppenderTest {
 
     @Test
     public void testAppendILoggingEvent_MatchLastPattern() {
-        ExtractAppender appender = makeAppender("abc[0-9]", "def[0-9]");
+        ExtractAppender appender = makeAppender(ABC_DIGIT, DEF_DIGIT);
 
         logger.info("hello def1");
         logger.info("world xyz2");
@@ -236,41 +246,41 @@ public class ExtractAppenderTest {
 
     @Test
     public void testAppendILoggingEvent_Group1() {
-        ExtractAppender appender = makeAppender("hello (abc)|(xyz)", "def[0-9]");
+        ExtractAppender appender = makeAppender("hello (abc)|(xyz)", DEF_DIGIT);
 
         logger.info("hello abc, world!");
-        logger.info("world abc");
+        logger.info(WORLD_ABC);
 
         assertEquals(strList("abc"), appender.getExtracted());
     }
 
     @Test
     public void testAppendILoggingEvent_Group3() {
-        ExtractAppender appender = makeAppender("hello (abc)|(pdq)|(xyz)", "def[0-9]");
+        ExtractAppender appender = makeAppender("hello (abc)|(pdq)|(xyz)", DEF_DIGIT);
 
         logger.info("say hello xyz, world!");
-        logger.info("world abc");
+        logger.info(WORLD_ABC);
 
         assertEquals(strList("xyz"), appender.getExtracted());
     }
 
     @Test
     public void testAppendILoggingEvent_NoGroup() {
-        ExtractAppender appender = makeAppender("hello abc");
+        ExtractAppender appender = makeAppender(HELLO_ABC);
 
         logger.info("say hello abc, world!");
-        logger.info("world abc");
+        logger.info(WORLD_ABC);
 
-        assertEquals(strList("hello abc"), appender.getExtracted());
+        assertEquals(strList(HELLO_ABC), appender.getExtracted());
     }
 
     @Test
     public void testGetExtracted() {
-        ExtractAppender appender = makeAppender("abc[1-9]");
+        ExtractAppender appender = makeAppender(ABC_DIGIT1);
 
-        logger.info("hello abc1 world");
-        logger.info("world ghi2 world"); // no match
-        logger.info("hello abc3");
+        logger.info(HELLO_ABC1_WORLD);
+        logger.info(WORLD_GHI2_WORLD); // no match
+        logger.info(HELLO_ABC3);
 
         List<String> oldlst = appender.getExtracted();
         assertEquals(strList("abc1", "abc3"), oldlst);
@@ -282,11 +292,11 @@ public class ExtractAppenderTest {
 
     @Test
     public void testClearExtractions() {
-        final ExtractAppender appender = makeAppender("abc[1-9]");
+        final ExtractAppender appender = makeAppender(ABC_DIGIT1);
 
-        logger.info("hello abc1 world");
-        logger.info("world ghi2 world");
-        logger.info("hello abc3");
+        logger.info(HELLO_ABC1_WORLD);
+        logger.info(WORLD_GHI2_WORLD);
+        logger.info(HELLO_ABC3);
 
         assertEquals(strList("abc1", "abc3"), appender.getExtracted());
 
@@ -305,11 +315,11 @@ public class ExtractAppenderTest {
 
     @Test
     public void testSetPattern() {
-        final ExtractAppender appender = makeAppender("abc[1-9]");
+        final ExtractAppender appender = makeAppender(ABC_DIGIT1);
 
-        logger.info("hello abc1 world");
-        logger.info("world ghi2 world"); // no match
-        logger.info("hello abc3");
+        logger.info(HELLO_ABC1_WORLD);
+        logger.info(WORLD_GHI2_WORLD); // no match
+        logger.info(HELLO_ABC3);
 
         assertEquals(strList("abc1", "abc3"), appender.getExtracted());
 
@@ -351,28 +361,20 @@ public class ExtractAppenderTest {
             }
         };
 
-        ExtractAppender app = new ExtractAppender(queue, "abc[1-9]");
+        ExtractAppender app = new ExtractAppender(queue, ABC_DIGIT1);
         addAppender(app);
 
         // create some threads to add another pattern
-        addThread(tend, err, xtxt -> {
-            app.setPattern("def[0-9]");
-        });
+        addThread(tend, err, xtxt -> app.setPattern(DEF_DIGIT));
 
         // create some threads to log "abc" messages
-        addThread(tend, err, xtxt -> {
-            logger.info("hello abc" + xtxt + "world!");
-        });
+        addThread(tend, err, xtxt -> logger.info("{}{}world!", HELLO_ABC, xtxt));
 
         // create some threads to log "def" messages
-        addThread(tend, err, xtxt -> {
-            logger.info("hello def" + xtxt + "world!");
-        });
+        addThread(tend, err, xtxt -> logger.info("hello def{}world!", xtxt));
 
         // create some threads to get extractions
-        addThread(tend, err, xtxt -> {
-            app.getExtracted();
-        });
+        addThread(tend, err, xtxt -> app.getExtracted());
 
         // create some threads to clear extractions
         addThread(tend, err, xtxt -> {
@@ -381,7 +383,7 @@ public class ExtractAppenderTest {
             // don't want to clear the list too frequently
             // so sleep a bit in between
             try {
-                Thread.sleep(10 + Integer.valueOf(xtxt));
+                Thread.sleep(10L + Integer.valueOf(xtxt));
 
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
index ebe0483..579eed9 100644 (file)
 
 package org.onap.policy.common.utils.security;
 
-import com.google.common.base.Charsets;
-
+import java.nio.charset.StandardCharsets;
 import java.security.GeneralSecurityException;
-
 import java.security.SecureRandom;
 import javax.crypto.Cipher;
 import javax.crypto.spec.IvParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
 import javax.xml.bind.DatatypeConverter;
-
 import org.apache.commons.lang3.ArrayUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -65,7 +62,7 @@ public class CryptoUtils {
 
     /**
      * CryptoUtils - encryption tool constructor.
-     * @param secretKey
+     * @param secretKeySpec
      *  AES supports 128, 192 or 256-bit long key size, it can be plain text or generated with key generator
      */
     public CryptoUtils(SecretKeySpec secretKeySpec) {
@@ -80,7 +77,7 @@ public class CryptoUtils {
      * Encrypt a value based on the Policy Encryption Key.
      * Equivalent openssl command: echo -n "123456" | openssl aes-128-cbc -e -K PrivateHexkey
      * -iv 16BytesIV | xxd -u -g100
-     * 
+     *
      * <p>Final result is to put in properties file is: IV + Outcome of openssl command
      *
      * @param value
@@ -123,7 +120,7 @@ public class CryptoUtils {
             cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
 
             return "enc:" + DatatypeConverter.printBase64Binary(
-                    ArrayUtils.addAll(iv, cipher.doFinal(value.getBytes(Charsets.UTF_8))));
+                    ArrayUtils.addAll(iv, cipher.doFinal(value.getBytes(StandardCharsets.UTF_8))));
         } catch (Exception e) {
             logger.error("Could not encrypt value - exception: ", e);
             return value;
@@ -181,7 +178,7 @@ public class CryptoUtils {
 
             cipher.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
             byte[] decrypted = cipher.doFinal(realData);
-            return new String(decrypted, Charsets.UTF_8);
+            return new String(decrypted, StandardCharsets.UTF_8);
         } catch (Exception e) {
             logger.error("Could not decrypt value - exception: ", e);
         }
@@ -224,6 +221,7 @@ public class CryptoUtils {
             return null;
         }
     }
+
     /**
      * Check if string is encrypted by verify if string prefix with 'enc:'.
      *
@@ -243,12 +241,12 @@ public class CryptoUtils {
         if (args.length == 3) {
             if ("enc".equals(args[0])) {
                 String encryptedValue = encrypt(args[1], args[2]);
-                logger.info("original value: " + args[1] + " encrypted value: " + encryptedValue);
+                logger.info("original value: {} encrypted value: {}", args[1], encryptedValue);
             } else if ("dec".equals(args[0])) {
                 String decryptedValue = decrypt(args[1], args[2]);
-                logger.info("original value: " + args[1] + " decrypted value: " + decryptedValue);
+                logger.info("original value: {} decrypted value: {}", args[1], decryptedValue);
             } else {
-                logger.info("Unknown request: " + args[0]);
+                logger.info("Unknown request: {}", args[0]);
             }
         } else {
             logger.info("Usage  : CryptoUtils enc/dec password   secretKey");
index 13fb338..c3eabe8 100644 (file)
@@ -32,7 +32,7 @@ import org.slf4j.LoggerFactory;
 public class Registry {
     private static final Logger logger = LoggerFactory.getLogger(Registry.class);
 
-    private static volatile Registry instance = new Registry();
+    private static Registry instance = new Registry();
 
     /**
      * Registry map.
index e2e462d..f15d936 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
@@ -27,6 +28,10 @@ package org.onap.policy.common.utils.validation;
  */
 public class ParameterValidationUtils {
 
+    private ParameterValidationUtils() {
+
+    }
+
     /**
      * Validates the given string input.
      *
@@ -34,10 +39,7 @@ public class ParameterValidationUtils {
      * @return the boolean validation result
      */
     public static boolean validateStringParameter(final String inputString) {
-        if (inputString == null || inputString.trim().length() == 0) {
-            return false;
-        }
-        return true;
+        return (inputString != null && !inputString.trim().isEmpty());
     }
 
     /**
@@ -47,10 +49,7 @@ public class ParameterValidationUtils {
      * @return the boolean validation result
      */
     public static boolean validateIntParameter(final int input) {
-        if (input <= 0) {
-            return false;
-        }
-        return true;
+        return (input > 0);
     }
 
     /**
@@ -60,9 +59,6 @@ public class ParameterValidationUtils {
      * @return the boolean validation result
      */
     public static boolean validateLongParameter(final long input) {
-        if (input <= 0) {
-            return false;
-        }
-        return true;
+        return (input > 0);
     }
 }
index e791e08..589d092 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * Common Utils
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -36,7 +36,7 @@ public class EntityMgrCloserTest {
 
 
     @Before
-    public void setUp() throws Exception {
+    public void setUp() {
         mgr = mock(EntityManager.class);
     }
 
index 8f2c015..ca2b722 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * Common Utils
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -36,7 +36,7 @@ public class EntityMgrFactoryCloserTest {
 
 
     @Before
-    public void setUp() throws Exception {
+    public void setUp() {
         factory = mock(EntityManagerFactory.class);
     }
 
index 9a499e4..d764e9d 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * Common Utils
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -40,7 +40,7 @@ public class EntityTransCloserTest {
      * Set up EntityTransaction mock.
      */
     @Before
-    public void setUp() throws Exception {
+    public void setUp() {
         trans = mock(EntityTransaction.class);
 
         when(trans.isActive()).thenReturn(true);
index beca88f..07e0795 100644 (file)
@@ -39,6 +39,11 @@ import org.onap.policy.common.utils.properties.exception.PropertyMissingExceptio
  * Test class for PropertyConfiguration.
  */
 public class BeanConfiguratorTest {
+    private static final String EXPECTED_EXCEPTION = "expected exception";
+    private static final String FALSE_STRING = "false";
+    private static final String A_VALUE = "a.value";
+    private static final String NUMBER_STRING_LONG = "20000";
+    private static final String NUMBER_STRING = "200";
 
     /**
      * Property used for most of the simple configuration subclasses.
@@ -141,7 +146,7 @@ public class BeanConfiguratorTest {
         // now a different set of values
         props.setProperty(THE_VALUE, STRING_VALUE + "x");
         props.setProperty("parent.value", "50001");
-        props.setProperty("grandparent.value", "false");
+        props.setProperty("grandparent.value", FALSE_STRING);
         beancfg.configureFromProperties(cfg, props);
 
         assertEquals(STRING_VALUE + "x", cfg.value);
@@ -240,7 +245,7 @@ public class BeanConfiguratorTest {
         beancfg = new BeanConfigurator() {
             @Override
             protected Object getValue(Field field, Properties props, Property prop) {
-                throw new IllegalArgumentException("expected exception");
+                throw new IllegalArgumentException(EXPECTED_EXCEPTION);
             }
         };
 
@@ -253,7 +258,7 @@ public class BeanConfiguratorTest {
 
             @Override
             public void setValue(String value) {
-                throw new IllegalArgumentException("expected exception");
+                throw new IllegalArgumentException(EXPECTED_EXCEPTION);
             }
         }
 
@@ -384,11 +389,11 @@ public class BeanConfiguratorTest {
             }
         }
 
-        props.setProperty("string", "a string");
+        props.setProperty("string", STRING_VALUE);
         props.setProperty("boolean.true", "true");
-        props.setProperty("boolean.false", "false");
+        props.setProperty("boolean.false", FALSE_STRING);
         props.setProperty("primitive.boolean.true", "true");
-        props.setProperty("primitive.boolean.false", "false");
+        props.setProperty("primitive.boolean.false", FALSE_STRING);
         props.setProperty("integer", "100");
         props.setProperty("primitive.integer", "101");
         props.setProperty("long", "10000");
@@ -397,7 +402,7 @@ public class BeanConfiguratorTest {
         Config cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
 
-        assertEquals("a string", cfg.stringValue);
+        assertEquals(STRING_VALUE, cfg.stringValue);
         assertEquals(true, cfg.boolTrueValue);
         assertEquals(false, cfg.boolFalseValue);
         assertEquals(true, cfg.primBoolTrueValue);
@@ -553,7 +558,7 @@ public class BeanConfiguratorTest {
         assertEquals(true, cfg.value);
 
         // try again, with the property defined as false
-        props.setProperty(THE_VALUE, "false");
+        props.setProperty(THE_VALUE, FALSE_STRING);
         cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
         assertEquals(false, cfg.value);
@@ -563,7 +568,7 @@ public class BeanConfiguratorTest {
     public void testGetBooleanValue_ValidDefault_False() throws PropertyException {
         class Config {
 
-            @Property(name = THE_VALUE, defaultValue = "false")
+            @Property(name = THE_VALUE, defaultValue = FALSE_STRING)
             private Boolean value;
 
             @SuppressWarnings("unused")
@@ -584,7 +589,7 @@ public class BeanConfiguratorTest {
         assertEquals(true, cfg.value);
 
         // try again, with the property defined as false
-        props.setProperty(THE_VALUE, "false");
+        props.setProperty(THE_VALUE, FALSE_STRING);
         cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
         assertEquals(false, cfg.value);
@@ -603,7 +608,7 @@ public class BeanConfiguratorTest {
             }
         }
 
-        props.setProperty(THE_VALUE, "200");
+        props.setProperty(THE_VALUE, NUMBER_STRING);
         Config cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
 
@@ -623,7 +628,7 @@ public class BeanConfiguratorTest {
             }
         }
 
-        props.setProperty(THE_VALUE, "200");
+        props.setProperty(THE_VALUE, NUMBER_STRING);
         beancfg.configureFromProperties(new Config(), props);
     }
 
@@ -646,7 +651,7 @@ public class BeanConfiguratorTest {
         assertEquals(201, cfg.value.intValue());
 
         // try again, with the property defined
-        props.setProperty(THE_VALUE, "200");
+        props.setProperty(THE_VALUE, NUMBER_STRING);
         cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
         assertEquals(200, cfg.value.intValue());
@@ -665,7 +670,7 @@ public class BeanConfiguratorTest {
             }
         }
 
-        props.setProperty(THE_VALUE, "20000");
+        props.setProperty(THE_VALUE, NUMBER_STRING_LONG);
         Config cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
 
@@ -685,7 +690,7 @@ public class BeanConfiguratorTest {
             }
         }
 
-        props.setProperty(THE_VALUE, "20000");
+        props.setProperty(THE_VALUE, NUMBER_STRING_LONG);
         beancfg.configureFromProperties(new Config(), props);
     }
 
@@ -708,7 +713,7 @@ public class BeanConfiguratorTest {
         assertEquals(20001L, cfg.value.longValue());
 
         // try again, with the property defined
-        props.setProperty(THE_VALUE, "20000");
+        props.setProperty(THE_VALUE, NUMBER_STRING_LONG);
         cfg = new Config();
         beancfg.configureFromProperties(cfg, props);
         assertEquals(20000L, cfg.value.longValue());
@@ -869,7 +874,7 @@ public class BeanConfiguratorTest {
 
     @Test
     public void testMakeBoolean_False() throws PropertyException {
-        props.setProperty(THE_VALUE, "false");
+        props.setProperty(THE_VALUE, FALSE_STRING);
         PlainBooleanConfig cfg = new PlainBooleanConfig();
         beancfg.configureFromProperties(cfg, props);
 
@@ -1095,7 +1100,7 @@ public class BeanConfiguratorTest {
         beancfg.addToProperties(cfg, props, "the", "a");
 
         assertEquals("1010", props.getProperty("a.parent.value"));
-        assertEquals(STRING_VALUE, props.getProperty("a.value"));
+        assertEquals(STRING_VALUE, props.getProperty(A_VALUE));
         assertEquals("other", props.getProperty("a.other.value"));
 
         // original prefix is empty
@@ -1104,7 +1109,7 @@ public class BeanConfiguratorTest {
 
         // original prefix is ends with "."
         beancfg.addToProperties(cfg, props, "the.", "a");
-        assertEquals(STRING_VALUE, props.getProperty("a.value"));
+        assertEquals(STRING_VALUE, props.getProperty(A_VALUE));
 
         // new prefix is empty
         beancfg.addToProperties(cfg, props, "", "");
@@ -1162,7 +1167,7 @@ public class BeanConfiguratorTest {
         beancfg.addToProperties(cfg, props, "the", "a");
 
         assertFalse(props.contains("noAnnotation"));
-        assertEquals(STRING_VALUE, props.getProperty("a.value"));
+        assertEquals(STRING_VALUE, props.getProperty(A_VALUE));
         assertFalse(props.contains("a.null.value"));
         assertEquals("some other value", props.getProperty("some.other.prefix"));
     }
@@ -1232,8 +1237,8 @@ public class BeanConfiguratorTest {
         beancfg.addToProperties(cfg, props, "", "");
 
         assertEquals("true", props.getProperty("plain.bool"));
-        assertEquals("false", props.getProperty("prim.bool"));
-        assertEquals("false", props.getProperty("plain.bool.get"));
+        assertEquals(FALSE_STRING, props.getProperty("prim.bool"));
+        assertEquals(FALSE_STRING, props.getProperty("plain.bool.get"));
         assertEquals("true", props.getProperty("prim.bool.get"));
         assertEquals("1100", props.getProperty("int"));
         assertEquals(STRING_VALUE, props.getProperty("string"));
@@ -1301,8 +1306,8 @@ public class BeanConfiguratorTest {
 
         beancfg = new BeanConfigurator() {
             @Override
-            protected Method getGetter(Field field, String methodName) throws SecurityException {
-                throw new SecurityException("expected exception");
+            protected Method getGetter(Field field, String methodName) {
+                throw new SecurityException(EXPECTED_EXCEPTION);
             }
         };
 
@@ -1319,7 +1324,7 @@ public class BeanConfiguratorTest {
 
             @SuppressWarnings("unused")
             public String getValue() {
-                throw new RuntimeException("expected exception");
+                throw new RuntimeException(EXPECTED_EXCEPTION);
             }
         }
 
@@ -1411,7 +1416,7 @@ public class BeanConfiguratorTest {
         private String value;
 
         public static void setValue(String value) {
-
+            // do nothing
         }
     }
 
index e5a79bc..4b2b007 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
+ *  Modifications 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.
@@ -48,11 +49,12 @@ public class ResourceUtilsTest {
     private String jarDirResource = null;
     private String jarFileResource = null;
 
-    private final String pathDirResource = "testdir";
-    private final String pathFileResource = "testdir/testfile.xml";
+    private static final String RESOURCES_PATH = "src/test/resources/";
+    private static final String PATH_DIR_RESOURCE = "testdir";
+    private static final String PATH_FILE_RESOURCE = "testdir/testfile.xml";
 
-    private final String nonExistantResource = "somewhere/over/the/rainbow";
-    private final String invalidResource = "@%%%\\\\_:::DESD";
+    private static final String NON_EXISTENT_RESOURCE = "somewhere/over/the/rainbow";
+    private static final String INVALID_RESOURCE = "@%%%\\\\_:::DESD";
 
     /**
      * Setup resource utils test.
@@ -68,9 +70,9 @@ public class ResourceUtilsTest {
         jarDirResource = "META-INF";
         jarFileResource = "META-INF/MANIFEST.MF";
 
-        final FileWriter fileWriter = new FileWriter(tmpUsedFile);
-        fileWriter.write("Bluebirds fly over the rainbow");
-        fileWriter.close();
+        try (final FileWriter fileWriter = new FileWriter(tmpUsedFile)) {
+            fileWriter.write("Bluebirds fly over the rainbow");
+        }
     }
 
     /**
@@ -93,25 +95,25 @@ public class ResourceUtilsTest {
         theUrl = ResourceUtils.getUrlResource(jarFileResource);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrlResource(pathDirResource);
+        theUrl = ResourceUtils.getUrlResource(PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrlResource(pathFileResource);
+        theUrl = ResourceUtils.getUrlResource(PATH_FILE_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrlResource("file:///" + pathDirResource);
+        theUrl = ResourceUtils.getUrlResource("file:///" + PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile("src/test/resources/" + pathDirResource);
+        theUrl = ResourceUtils.getLocalFile(RESOURCES_PATH + PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile("src/test/resources/" + pathFileResource);
+        theUrl = ResourceUtils.getLocalFile(RESOURCES_PATH + PATH_FILE_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrlResource(nonExistantResource);
+        theUrl = ResourceUtils.getUrlResource(NON_EXISTENT_RESOURCE);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getUrlResource(invalidResource);
+        theUrl = ResourceUtils.getUrlResource(INVALID_RESOURCE);
         assertNull(theUrl);
 
         theUrl = ResourceUtils.getUrlResource(null);
@@ -138,22 +140,22 @@ public class ResourceUtilsTest {
         theUrl = ResourceUtils.getLocalFile(jarFileResource);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile(pathDirResource);
+        theUrl = ResourceUtils.getLocalFile(PATH_DIR_RESOURCE);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile(pathFileResource);
+        theUrl = ResourceUtils.getLocalFile(PATH_FILE_RESOURCE);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile("src/test/resources/" + pathDirResource);
+        theUrl = ResourceUtils.getLocalFile(RESOURCES_PATH + PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile("src/test/resources/" + pathFileResource);
+        theUrl = ResourceUtils.getLocalFile(RESOURCES_PATH + PATH_FILE_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile(nonExistantResource);
+        theUrl = ResourceUtils.getLocalFile(NON_EXISTENT_RESOURCE);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getLocalFile(invalidResource);
+        theUrl = ResourceUtils.getLocalFile(INVALID_RESOURCE);
         assertNull(theUrl);
 
         theUrl = ResourceUtils.getLocalFile("file:///");
@@ -186,29 +188,29 @@ public class ResourceUtilsTest {
         theStream = ResourceUtils.getResourceAsStream(jarFileResource);
         assertNotNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream(pathDirResource);
+        theStream = ResourceUtils.getResourceAsStream(PATH_DIR_RESOURCE);
         assertNotNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream(pathFileResource);
+        theStream = ResourceUtils.getResourceAsStream(PATH_FILE_RESOURCE);
         assertNotNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream("src/test/resources/" + pathDirResource);
+        theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_DIR_RESOURCE);
         assertNotNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream("src/test/resources/" + pathFileResource);
+        theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_FILE_RESOURCE);
         assertNotNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream(nonExistantResource);
+        theStream = ResourceUtils.getResourceAsStream(NON_EXISTENT_RESOURCE);
         assertNull(theStream);
 
-        theStream = ResourceUtils.getResourceAsStream(invalidResource);
+        theStream = ResourceUtils.getResourceAsStream(INVALID_RESOURCE);
         assertNull(theStream);
 
         theStream = ResourceUtils.getResourceAsStream(null);
-        assertNull(null);
+        assertNull(theStream);
 
         theStream = ResourceUtils.getResourceAsStream("");
-        assertNull(null);
+        assertNotNull(theStream);
     }
 
     /**
@@ -228,22 +230,22 @@ public class ResourceUtilsTest {
         theString = ResourceUtils.getResourceAsString(jarFileResource);
         assertNotNull(theString);
 
-        theString = ResourceUtils.getResourceAsString(pathDirResource);
+        theString = ResourceUtils.getResourceAsString(PATH_DIR_RESOURCE);
         assertNotNull(theString);
 
-        theString = ResourceUtils.getResourceAsString(pathFileResource);
+        theString = ResourceUtils.getResourceAsString(PATH_FILE_RESOURCE);
         assertNotNull(theString);
 
-        theString = ResourceUtils.getResourceAsString("src/test/resources/" + pathDirResource);
+        theString = ResourceUtils.getResourceAsString(RESOURCES_PATH + PATH_DIR_RESOURCE);
         assertNotNull(theString);
 
-        theString = ResourceUtils.getResourceAsString("src/test/resources/" + pathFileResource);
+        theString = ResourceUtils.getResourceAsString(RESOURCES_PATH + PATH_FILE_RESOURCE);
         assertNotNull(theString);
 
-        theString = ResourceUtils.getResourceAsString(nonExistantResource);
+        theString = ResourceUtils.getResourceAsString(NON_EXISTENT_RESOURCE);
         assertNull(theString);
 
-        theString = ResourceUtils.getResourceAsString(invalidResource);
+        theString = ResourceUtils.getResourceAsString(INVALID_RESOURCE);
         assertNull(theString);
 
         theString = ResourceUtils.getResourceAsString(null);
@@ -272,22 +274,22 @@ public class ResourceUtilsTest {
         theUrl = ResourceUtils.getUrl4Resource(jarFileResource);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource(pathDirResource);
+        theUrl = ResourceUtils.getUrl4Resource(PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource(pathFileResource);
+        theUrl = ResourceUtils.getUrl4Resource(PATH_FILE_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource("src/test/resources/" + pathDirResource);
+        theUrl = ResourceUtils.getUrl4Resource(RESOURCES_PATH + PATH_DIR_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource("src/test/resources/" + pathFileResource);
+        theUrl = ResourceUtils.getUrl4Resource(RESOURCES_PATH + PATH_FILE_RESOURCE);
         assertNotNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource(nonExistantResource);
+        theUrl = ResourceUtils.getUrl4Resource(NON_EXISTENT_RESOURCE);
         assertNull(theUrl);
 
-        theUrl = ResourceUtils.getUrl4Resource(invalidResource);
+        theUrl = ResourceUtils.getUrl4Resource(INVALID_RESOURCE);
         assertNull(theUrl);
     }
 
index fd3daee..9a88918 100644 (file)
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 
 import java.security.GeneralSecurityException;
-
 import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,86 +34,88 @@ import org.slf4j.LoggerFactory;
 
 public class CryptoUtilsTest {
     private static Logger logger = LoggerFactory.getLogger(CryptoUtilsTest.class);
-    private final String pass = "HelloWorld";
-    private final String secretKey = "12345678901234567890123456789012";
-    private final String encryptedPass = "enc:8XxseP5W5ODxzPrReNKd9JBYLv0iiAzy9BHnMKau5yg=";
+    private static final String PASS = "HelloWorld";
+    private static final String SECRET_KEY = "MTIzNDU2Nzg5MDEyMzQ1Ng==";
+    private static final String ENCRYPTED_PASS = "enc:hcI2XVX+cxPz/6rlbebkWpCFF6WPbBtT7iJRr2VHUkA=";
+    private static final String DECRYPTED_MSG = "encrypted value: {}  decrypted value : {}";
+    private static final String ENCRYPTED_MSG = "original value : {}  encrypted value: {}";
 
     @Test
     public void testEncrypt() throws GeneralSecurityException {
         logger.info("testEncrypt:");
-        CryptoUtils cryptoUtils = new CryptoUtils(secretKey);
-        String encryptedValue = cryptoUtils.encrypt(pass);
-        logger.info("original value : " + pass + "  encrypted value: " + encryptedValue);
+        CryptoUtils cryptoUtils = new CryptoUtils(SECRET_KEY);
+        String encryptedValue = cryptoUtils.encrypt(PASS);
+        logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
 
         String decryptedValue = cryptoUtils.decrypt(encryptedValue);
-        logger.info("encrypted value: " + encryptedValue + "  decrypted value : " + decryptedValue);
-        assertEquals(pass, decryptedValue);
+        logger.info(DECRYPTED_MSG, encryptedValue, decryptedValue);
+        assertEquals(PASS, decryptedValue);
     }
 
     @Test
     public void testDecrypt() throws GeneralSecurityException {
         logger.info("testDecrypt:");
-        CryptoUtils cryptoUtils = new CryptoUtils(secretKey);
-        String decryptedValue = cryptoUtils.decrypt(encryptedPass);
-        logger.info("encrypted value: " + encryptedPass + "  decrypted value : " + decryptedValue);
-        assertEquals(pass, decryptedValue);
+        CryptoUtils cryptoUtils = new CryptoUtils(SECRET_KEY);
+        String decryptedValue = cryptoUtils.decrypt(ENCRYPTED_PASS);
+        logger.info(DECRYPTED_MSG, ENCRYPTED_PASS, decryptedValue);
+        assertEquals(PASS, decryptedValue);
     }
 
     @Test
     public void testStaticEncrypt() {
         logger.info("testStaticEncrypt:");
-        String encryptedValue = CryptoUtils.encrypt(pass, secretKey);
-        logger.info("original value : " + pass + "  encrypted value: " + encryptedValue);
+        String encryptedValue = CryptoUtils.encrypt(PASS, SECRET_KEY);
+        logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
 
-        String decryptedValue = CryptoUtils.decrypt(encryptedValue, secretKey);
-        logger.info("encrypted value: " + encryptedValue + "  decrypted value : " + decryptedValue);
-        assertEquals(pass, decryptedValue);
+        String decryptedValue = CryptoUtils.decrypt(encryptedValue, SECRET_KEY);
+        logger.info(DECRYPTED_MSG, encryptedValue, decryptedValue);
+        assertEquals(PASS, decryptedValue);
     }
 
     @Test
     public void testStaticDecrypt() {
         logger.info("testStaticDecrypt:");
-        String decryptedValue = CryptoUtils.decrypt(encryptedPass, secretKey);
-        logger.info("encrypted value: " + encryptedPass + "  decrypted value : " + decryptedValue);
-        assertEquals(pass, decryptedValue);
+        String decryptedValue = CryptoUtils.decrypt(ENCRYPTED_PASS, SECRET_KEY);
+        logger.info(DECRYPTED_MSG, ENCRYPTED_PASS, decryptedValue);
+        assertEquals(PASS, decryptedValue);
     }
 
     @Test
     public void testBadInputs() {
-        String badKey = CryptoUtils.encrypt(pass, "test");
-        assertEquals(pass, badKey);
+        String badKey = CryptoUtils.encrypt(PASS, "test");
+        assertEquals(PASS, badKey);
 
-        String badDecrypt = CryptoUtils.decrypt(encryptedPass, "");
-        assertEquals(encryptedPass, badDecrypt);
+        String badDecrypt = CryptoUtils.decrypt(ENCRYPTED_PASS, "");
+        assertEquals(ENCRYPTED_PASS, badDecrypt);
 
-        String emptyValue = CryptoUtils.encrypt(new String(), secretKey);
+        String emptyValue = CryptoUtils.encrypt("", SECRET_KEY);
         assertEquals("", emptyValue);
 
-        String emptyDecrypt = CryptoUtils.decrypt(new String(), secretKey);
+        String emptyDecrypt = CryptoUtils.decrypt("", SECRET_KEY);
         assertEquals("", emptyDecrypt);
 
-        String nullValue = CryptoUtils.encrypt(null, secretKey);
+        String nullValue = CryptoUtils.encrypt(null, SECRET_KEY);
         assertNull(nullValue);
 
-        String nullDecrypt = CryptoUtils.decrypt(null, secretKey);
+        String nullDecrypt = CryptoUtils.decrypt(null, SECRET_KEY);
         assertNull(nullDecrypt);
     }
 
     @Test
     public void testAll() {
         logger.info("testAll:");
-        String encryptedValue = CryptoUtils.encrypt(pass, secretKey);
-        logger.info("original value : " + pass + "  encrypted value: " + encryptedValue);
+        String encryptedValue = CryptoUtils.encrypt(PASS, SECRET_KEY);
+        logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
 
-        String encryptedAgain = CryptoUtils.encrypt(encryptedValue, secretKey);
+        String encryptedAgain = CryptoUtils.encrypt(encryptedValue, SECRET_KEY);
 
         assertEquals(encryptedValue, encryptedAgain);
 
-        String decryptedValue = CryptoUtils.decrypt(encryptedAgain, secretKey);
-        logger.info("encrypted value: " + encryptedAgain + "  decrypted value : " + decryptedValue);
-        assertEquals(pass, decryptedValue);
+        String decryptedValue = CryptoUtils.decrypt(encryptedAgain, SECRET_KEY);
+        logger.info(DECRYPTED_MSG, encryptedAgain, decryptedValue);
+        assertEquals(PASS, decryptedValue);
 
-        String decryptedAgain = CryptoUtils.decrypt(decryptedValue, secretKey);
+        String decryptedAgain = CryptoUtils.decrypt(decryptedValue, SECRET_KEY);
         assertEquals(decryptedValue, decryptedAgain);
     }
 }
\ No newline at end of file
index b7774a5..83b2629 100644 (file)
@@ -90,7 +90,7 @@ public class ServiceManagerTest {
     }
 
     @Test
-    public void testAddStartable() throws Exception {
+    public void testAddStartable() {
         Startable start1 = mock(Startable.class);
         svcmgr.addService("first startable", start1);
 
@@ -115,7 +115,7 @@ public class ServiceManagerTest {
     }
 
     @Test
-    public void testStart() throws Exception {
+    public void testStart() {
         Startable start1 = mock(Startable.class);
         svcmgr.addService("test start", start1);
 
@@ -201,7 +201,7 @@ public class ServiceManagerTest {
     }
 
     @Test
-    public void testStop() throws Exception {
+    public void testStop() {
         Startable start1 = mock(Startable.class);
         svcmgr.addService("first stop", start1);
 
@@ -245,7 +245,7 @@ public class ServiceManagerTest {
     }
 
     @Test
-    public void testShutdown() throws Exception {
+    public void testShutdown() {
         Startable start1 = mock(Startable.class);
         svcmgr.addService("first stop", start1);
 
@@ -265,7 +265,7 @@ public class ServiceManagerTest {
     }
 
     @Test
-    public void testRewind() throws Exception {
+    public void testRewind() {
         RunnableWithEx starter = mock(RunnableWithEx.class);
         LinkedList<String> lst = new LinkedList<>();
 
index e39058b..05d4c5c 100644 (file)
@@ -2,6 +2,7 @@
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
  *  Modifications Copyright (C) 2019 Nordix Foundation.
+ *  Modifications 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.
@@ -21,6 +22,7 @@
 
 package org.onap.policy.common.utils.validation;
 
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 
@@ -32,67 +34,62 @@ import org.junit.Test;
  * @author Liam Fallon (liam.fallon@ericsson.com)
  */
 public class AssertionsTest {
+    private static final String HELLO = "Hello";
+    private static final String IT_IS_OK = "it is OK";
+    private static final String IT_IS_NULL = "it is null";
+    private static final String IT_IS_TRUE = "it is true";
+    private static final String IT_IS_FALSE = "it is false";
+
     @Test
     public void testAssertions() {
-        Assertions.argumentNotFalse(true, "it is true");
+        Assertions.argumentNotFalse(true, IT_IS_TRUE);
+
+        assertThatIllegalArgumentException().isThrownBy(() -> Assertions.argumentNotFalse(false, IT_IS_FALSE))
+                        .withMessage(IT_IS_FALSE);
+
+
+        Assertions.argumentOfClassNotFalse(true, ArithmeticException.class, IT_IS_TRUE);
 
-        try {
-            Assertions.argumentNotFalse(false, "it is false");
-        } catch (IllegalArgumentException e) {
-            assertEquals("it is false", e.getMessage());
-        }
+        assertThatIllegalArgumentException().isThrownBy(
+            () -> Assertions.argumentOfClassNotFalse(false, ArithmeticException.class, IT_IS_FALSE))
+            .withMessage(IT_IS_FALSE);
 
-        Assertions.argumentOfClassNotFalse(true, ArithmeticException.class, "it is true");
 
-        try {
-            Assertions.argumentOfClassNotFalse(false, ArithmeticException.class, "it is false");
-        } catch (Exception e) {
-            assertEquals("it is false", e.getMessage());
-        }
+        Assertions.argumentNotNull(HELLO, IT_IS_OK);
 
-        Assertions.argumentNotNull("Hello", "it is OK");
+        assertThatIllegalArgumentException().isThrownBy(() -> Assertions.argumentNotNull(null, IT_IS_NULL))
+                        .withMessage(IT_IS_NULL);
 
-        try {
-            Assertions.argumentNotNull(null, "it is null");
-        } catch (IllegalArgumentException e) {
-            assertEquals("it is null", e.getMessage());
-        }
 
-        Assertions.argumentOfClassNotNull(true, ArithmeticException.class, "it is OK");
+        Assertions.argumentOfClassNotNull(true, ArithmeticException.class, IT_IS_OK);
+
+        assertThatIllegalArgumentException().isThrownBy(
+            () -> Assertions.argumentOfClassNotNull(null, ArithmeticException.class, IT_IS_NULL))
+            .withMessage(IT_IS_NULL);
 
-        try {
-            Assertions.argumentOfClassNotNull(null, ArithmeticException.class, "it is null");
-        } catch (Exception e) {
-            assertEquals("it is null", e.getMessage());
-        }
 
         Assertions.assignableFrom(java.util.TreeMap.class, java.util.Map.class);
 
-        try {
-            Assertions.assignableFrom(java.util.Map.class, java.util.TreeMap.class);
-        } catch (IllegalArgumentException e) {
-            assertEquals("java.util.Map is not an instance of java.util.TreeMap", e.getMessage());
-        }
+        assertThatIllegalArgumentException()
+                        .isThrownBy(() -> Assertions.assignableFrom(java.util.Map.class, java.util.TreeMap.class))
+                        .withMessage("java.util.Map is not an instance of java.util.TreeMap");
+
 
-        Assertions.instanceOf("Hello", String.class);
+        Assertions.instanceOf(HELLO, String.class);
+
+        assertThatIllegalArgumentException().isThrownBy(() -> Assertions.instanceOf(100, String.class))
+                        .withMessage("java.lang.Integer is not an instance of java.lang.String");
 
-        try {
-            Assertions.instanceOf(100, String.class);
-        } catch (IllegalArgumentException e) {
-            assertEquals("java.lang.Integer is not an instance of java.lang.String", e.getMessage());
-        }
 
         Assertions.validateStringParameter("name", "MyName", "^M.*e$");
 
-        try {
-            Assertions.validateStringParameter("name", "MyName", "^M.*f$");
-        } catch (IllegalArgumentException e) {
-            assertEquals("parameter \"name\": value \"MyName\", does not match regular expression \"^M.*f$\"",
-                    e.getMessage());
-        }
+        assertThatIllegalArgumentException()
+            .isThrownBy(() -> Assertions.validateStringParameter("name", "MyName", "^M.*f$"))
+            .withMessage("parameter \"name\": value \"MyName\", does not match regular expression \"^M.*f$\"");
+
 
-        assertNull(Assertions.getStringParameterValidationMessage("Greeting", "Hello", "^H.*o$"));
+        assertNull(Assertions.getStringParameterValidationMessage("Greeting", HELLO, "^H.*o$"));
         assertEquals("parameter Greeting with value Hello does not match regular expression Goodbye",
-                Assertions.getStringParameterValidationMessage("Greeting", "Hello", "Goodbye"));
+                        Assertions.getStringParameterValidationMessage("Greeting", HELLO, "Goodbye"));
     }
 }