diff options
author | Jim Hahn <jrh3@att.com> | 2019-06-12 14:32:25 -0400 |
---|---|---|
committer | Jim Hahn <jrh3@att.com> | 2019-06-12 17:36:59 -0400 |
commit | ea262e6da52fd4da0733f02998f87aebaf502ddb (patch) | |
tree | a7cded567521f0141f31d9f8c185eccdaf2a8979 | |
parent | e671e9fa5d09ec696cb24aeefaf10ddbc7c705d7 (diff) |
Apply simple sonar fixes
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, 753 insertions, 801 deletions
diff --git a/common-parameters/pom.xml b/common-parameters/pom.xml index 0f1e9dfc..fc47b402 100644 --- a/common-parameters/pom.xml +++ b/common-parameters/pom.xml @@ -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. @@ -39,6 +40,11 @@ <artifactId>lombok</artifactId> </dependency> <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java index b65db953..b874db69 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java @@ -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()); } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java index 30e2c0da..12cd80cb 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java @@ -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()); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java index ae4dbd2c..abef5528 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java @@ -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()); diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java index 2dad4283..fda37816 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java @@ -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. @@ -20,99 +21,73 @@ 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"); } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java index eb673222..9e7121cd 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java @@ -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"); diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java index 2c1e2f18..b02022d7 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java @@ -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\""); } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java index f7451051..46360ef9 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java @@ -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"); } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java index e24f1c8e..66656844 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java @@ -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()); diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java index 748eb902..ea5ae853 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java @@ -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()); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java index 8ad682ff..2fba9ba2 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java @@ -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()); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java index 2fc04180..44ec7139 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java @@ -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"); } diff --git a/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java b/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java index 65baaee4..c7b3bc98 100644 --- a/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java +++ b/gson/src/main/java/org/onap/policy/common/gson/internal/Adapter.java @@ -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. diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java index 4b5473c5..3ce16964 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonExclusionStrategyTest.java @@ -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 { diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java index 9d4b4388..bbeb1e26 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonFieldAdapterFactoryTest.java @@ -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; diff --git a/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java b/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java index 47cf4b3b..6377420d 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/JacksonMethodAdapterFactoryTest.java @@ -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; diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java index 04f37164..33160007 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/AdapterTest.java @@ -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))); } /** diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/AnyGetterSerializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/AnyGetterSerializerTest.java index 75128420..f68e3e3e 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/AnyGetterSerializerTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/AnyGetterSerializerTest.java @@ -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"); diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/AnySetterDeserializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/AnySetterDeserializerTest.java index b180605e..c03e3695 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/AnySetterDeserializerTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/AnySetterDeserializerTest.java @@ -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 { diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/ClassWalkerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/ClassWalkerTest.java index 1a15be09..6af4ae4f 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/ClassWalkerTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/ClassWalkerTest.java @@ -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; } diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java index 62bab231..509ddb79 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldDeserializerTest.java @@ -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"; diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java index 18167fc0..cc5ef928 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java @@ -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"; diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java index a75fe17e..6be4e590 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/JacksonTypeAdapterTest.java @@ -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 { diff --git a/gson/src/test/java/org/onap/policy/common/gson/internal/LifterTest.java b/gson/src/test/java/org/onap/policy/common/gson/internal/LifterTest.java index 55a3b674..e0b9eb30 100644 --- a/gson/src/test/java/org/onap/policy/common/gson/internal/LifterTest.java +++ b/gson/src/test/java/org/onap/policy/common/gson/internal/LifterTest.java @@ -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 { diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java index ef002f52..73c61651 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpoint.java @@ -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); diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSink.java index d3745940..c52a30be 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSink.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSink.java @@ -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); diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSource.java index 95ed0fe6..a5b9349e 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSource.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSource.java @@ -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); diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java index e20fb598..abf793d6 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumer.java @@ -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 { diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java index 1c2d6eeb..1c85fa97 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java @@ -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) { diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java index b7bafe0d..0aaf1ccb 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java @@ -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"); } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java index 919397d9..b5c9e614 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java @@ -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())); } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java index b4c7fff8..6c9dfcbd 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java @@ -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(); } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java index ec6fcfcc..d6187420 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java @@ -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(); } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java index c9064d45..ae07798d 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java @@ -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 diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java index 9c1e4af4..283d44da 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java @@ -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; diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java index 5628a239..01028045 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java @@ -39,6 +39,7 @@ public class BusTopicBaseTest extends TopicTestBase { * Initializes the object to be tested. */ @Before + @Override public void setUp() { super.setUp(); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java index 8d1c6343..54531c56 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java @@ -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 diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java index cb6eb107..2356746e 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java @@ -47,6 +47,7 @@ public class InlineBusTopicSinkTest extends TopicTestBase { * Creates the object to be tested. */ @Before + @Override public void setUp() { super.setUp(); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java index aaab402c..d9bc990b 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java @@ -37,6 +37,7 @@ public class InlineDmaapTopicSinkTest extends TopicTestBase { * Creates the object to be tested. */ @Before + @Override public void setUp() { super.setUp(); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java index 2516406f..a45504f2 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java @@ -37,6 +37,7 @@ public class InlineUebTopicSinkTest extends TopicTestBase { * Creates the object to be tested. */ @Before + @Override public void setUp() { super.setUp(); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java index 1f1f117e..4f7a5a9f 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java @@ -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()); } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java index 972fc666..3ae39ebd 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java @@ -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(); } } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java index d3354e49..f37f32a1 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java @@ -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; } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java index 3e4244dd..466041e3 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java @@ -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 diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java index ee66195c..95abd4db 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java @@ -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); } /** diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java index 710926d3..8a60a5d2 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java @@ -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)); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java index 4d289c6a..3cb53d81 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java @@ -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); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java index e01ed417..cd6edf76 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java @@ -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(); diff --git a/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java b/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java index ebe0483f..579eed9f 100644 --- a/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java +++ b/utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java @@ -20,16 +20,13 @@ 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"); diff --git a/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java b/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java index 13fb3389..c3eabe8e 100644 --- a/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java +++ b/utils/src/main/java/org/onap/policy/common/utils/services/Registry.java @@ -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. diff --git a/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java b/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java index e2e462da..f15d936b 100644 --- a/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java +++ b/utils/src/main/java/org/onap/policy/common/utils/validation/ParameterValidationUtils.java @@ -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); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java index e791e084..589d0924 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java @@ -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); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java index 8f2c0159..ca2b7220 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java @@ -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); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java index 9a499e49..d764e9d0 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java @@ -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); diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java index beca88f0..07e0795f 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java @@ -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 } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java index e5a79bc3..4b2b007b 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java @@ -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); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java index fd3daee8..9a88918d 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java @@ -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 diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java index b7774a5e..83b2629c 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java @@ -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<>(); diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java b/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java index e39058bd..05d4c5c3 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java @@ -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")); } } |