diff options
Diffstat (limited to 'utils-test/src/main/java/org/onap/policy/common/utils')
15 files changed, 325 insertions, 131 deletions
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 6ae42faf..8276ea4c 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,8 @@ * ============LICENSE_START======================================================= * policy-management * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,22 +28,20 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import com.google.re2j.Pattern; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.URL; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.apache.commons.jexl3.JexlBuilder; import org.apache.commons.jexl3.JexlContext; import org.apache.commons.jexl3.JexlEngine; -import org.apache.commons.jexl3.JexlException; import org.apache.commons.jexl3.MapContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,6 +49,7 @@ import org.slf4j.LoggerFactory; /** * Utilities used to test encoding and decoding of Policy objects. */ +@AllArgsConstructor(access = AccessLevel.PROTECTED) public class GsonTestUtils { private static final Logger logger = LoggerFactory.getLogger(GsonTestUtils.class); @@ -67,6 +67,7 @@ public class GsonTestUtils { /** * Used to encode and decode an object via gson. */ + @Getter private Gson gson; /** @@ -79,19 +80,6 @@ public class GsonTestUtils { } /** - * Constructs the object. - * - * @param gson used to encode via gson - */ - protected GsonTestUtils(Gson gson) { - this.gson = gson; - } - - public Gson getGson() { - return gson; - } - - /** * Serializes and then deserializes an object using gson. * * @param object the object to be serialized @@ -110,7 +98,6 @@ public class GsonTestUtils { * * @param object the object to be encoded * @param expected the expected value - * @throws Exception if the file cannot be read */ public void compareGson(Object object, Class<?> expected) { compareGson(object, new File(expected.getSimpleName() + ".json")); @@ -123,11 +110,10 @@ public class GsonTestUtils { * * @param object the object to be encoded * @param expected the expected value - * @throws Exception if the file cannot be read */ public void compareGson(Object object, File expected) { // file is not required to have a full path - find it via getResource() - URL url = object.getClass().getResource(expected.getName()); + var url = object.getClass().getResource(expected.getName()); if (url == null) { throw new JsonParseException(new FileNotFoundException(expected.getName())); } @@ -169,7 +155,11 @@ public class GsonTestUtils { JsonElement gsonjo = reorder(gson.fromJson(sgson, JsonElement.class)); JsonElement expjo = reorder(expected); - assertEquals(expjo.toString(), gsonjo.toString()); + /* + * As this method is only used within junit tests, it is OK to use assert calls, + * thus sonar is disabled. + */ + assertEquals(expjo.toString(), gsonjo.toString()); // NOSONAR } /** @@ -179,7 +169,7 @@ public class GsonTestUtils { * @throws IOException if an error occurs */ protected String readFile(File file) throws IOException { - return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + return Files.readString(file.toPath()); } @@ -193,7 +183,7 @@ public class GsonTestUtils { * @return the text, after interpolating the script elements */ public String applyScripts(String text, Object object) { - Matcher mat = SCRIPT_PAT.matcher(text); + var mat = SCRIPT_PAT.matcher(text); if (!mat.find()) { // contains no script elements - just return it as is return text; @@ -205,30 +195,25 @@ public class GsonTestUtils { context.set("obj", object); // work our way through the text, interpolating script elements as we go - StringBuilder bldr = new StringBuilder(); - int ilast = 0; + var bldr = new StringBuilder(); + var ilast = 0; mat.reset(); while (mat.find(ilast)) { // append segment that appears between last match and this int inext = mat.start(); - bldr.append(text.substring(ilast, inext)); + bldr.append(text, ilast, inext); // next match begins after the current match ilast = mat.end(); // interpolate the script String script = mat.group(1); - try { - /* - * Note: must use "eng" instead of "engineInstance" to ensure that we use - * the same engine that's associated with the bindings. - */ - Object result = eng.createExpression(script).evaluate(context); - bldr.append(result == null ? "null" : result.toString()); - - } catch (JexlException e) { - throw new JsonParseException("cannot expand element: " + mat.group(), e); - } + /* + * Note: must use "eng" instead of "engineInstance" to ensure that we use + * the same engine that's associated with the bindings. + */ + Object result = eng.createExpression(script).evaluate(context); + bldr.append(result == null ? "null" : result.toString()); } // append final segment @@ -271,11 +256,11 @@ public class GsonTestUtils { * @return a new object, without the null items */ public JsonObject reorder(JsonObject jsonObj) { - JsonObject newjo = new JsonObject(); + var newjo = new JsonObject(); // sort the keys before copying to the new object List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet()); - Collections.sort(sortedSet, (left, right) -> left.getKey().compareTo(right.getKey())); + sortedSet.sort(Entry.comparingByKey()); for (Entry<String, JsonElement> ent : sortedSet) { JsonElement val = ent.getValue(); @@ -297,7 +282,7 @@ public class GsonTestUtils { * @return a new array, with null items removed from all elements */ public JsonArray reorder(JsonArray jsonArray) { - JsonArray newarr = new JsonArray(); + var newarr = new JsonArray(); for (JsonElement ent : jsonArray) { newarr.add(reorder(ent)); } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java index 9ab26d32..f3e1418a 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2021 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. @@ -25,10 +25,13 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; /** * Utilities for testing serialization and de-serialization of objects. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class Serializer { /** @@ -37,13 +40,6 @@ public class Serializer { private static Factory factory = new Factory(); /** - * The constructor. - */ - private Serializer() { - - } - - /** * Serializes an object into a byte array. * * @param object the object to be serialized @@ -51,8 +47,8 @@ public class Serializer { * @throws IOException if an error occurs */ public static <T> byte[] serialize(T object) throws IOException { - try (ByteArrayOutputStream out = factory.makeByteArrayOutputStream()) { - try (ObjectOutputStream oos = factory.makeObjectOutputStream(out)) { + try (var out = factory.makeByteArrayOutputStream()) { + try (var oos = factory.makeObjectOutputStream(out)) { /* * writeObject() is final and mockito can't mock final methods. In * addition, powermock seemed to be having difficulty with the junit test @@ -73,10 +69,10 @@ public class Serializer { * @return the object that was de-serialized from the byte array * @throws IOException if an error occurs */ - public static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException { + private static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException { - try (ByteArrayInputStream in = factory.makeByteArrayInputStream(data); - ObjectInputStream ois = factory.makeObjectInputStream(in)) { + try (var in = factory.makeByteArrayInputStream(data); + var ois = factory.makeObjectInputStream(in)) { /* * readObject() is final and mockito can't mock final methods. In addition, * powermock seemed to be having difficulty with the junit test class as well, @@ -133,7 +129,11 @@ public class Serializer { */ public Object readObject(ObjectInputStream ois) throws IOException { try { - return ois.readObject(); + /* + * This class is only used by junit tests. In addition, it is only used by + * deserialize(), which has been made "private", thus disabling sonar. + */ + return ois.readObject(); // NOSONAR } catch (ClassNotFoundException e) { throw new IOException(e); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java new file mode 100644 index 00000000..0787872c --- /dev/null +++ b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.utils.security; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.Arrays; +import java.util.Date; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import lombok.Getter; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * Keystore, containing a self-signed certificate, valid for one day (see the argument to + * the "-valid" flag below). For use in junit tests. + */ +@Getter +public class SelfSignedKeyStore { + public static final String KEYSTORE_PASSWORD = "Pol1cy_0nap"; + public static final String PRIVATE_KEY_PASSWORD = KEYSTORE_PASSWORD; + public static final String RELATIVE_PATH = "target/test-classes/policy-keystore"; + + /** + * File containing subject-alternative names (i.e., list of servers that may use this + * keystore). + */ + private static final String KEYSTORE_SAN = "keystore_san.txt"; + + private final String keystoreName; + + + /** + * Generates the keystore, if it does not exist or if it's more than a few hours old. + * + * @throws IOException if an I/O error occurs + * @throws InterruptedException if an interrupt occurs + */ + public SelfSignedKeyStore() throws IOException, InterruptedException { + this(RELATIVE_PATH); + } + + /** + * Generates the keystore, if it does not exist or if it's more than a few hours old. + * + * @param relativePath path to the keystore, relative to the "user.dir" system + * property + * @throws IOException if an I/O error occurs + * @throws InterruptedException if an interrupt occurs + */ + public SelfSignedKeyStore(String relativePath) throws IOException, InterruptedException { + keystoreName = System.getProperty("user.dir") + "/" + relativePath; + + // use existing file if it isn't too old + var keystoreFile = new File(keystoreName); + if (keystoreFile.exists()) { + if (System.currentTimeMillis() < keystoreFile.lastModified() + + TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS)) { + return; + } + + Files.delete(keystoreFile.toPath()); + } + + /* + * Read the list of subject-alternative names, joining the lines with commas, and + * dropping the trailing comma. + */ + String sanFileName = getKeystoreSanName(); + var sanString = ResourceUtils.getResourceAsString(sanFileName); + if (sanString == null) { + throw new FileNotFoundException(sanFileName); + } + + var sanArray = sanString.replace("DNS:", "").replace("\r", "").split("\n"); + GeneralName[] nameArray = Arrays.stream(sanArray).map(name -> new GeneralName(GeneralName.dNSName, name)) + .toList().toArray(new GeneralName[0]); + final var names = new GeneralNames(nameArray); + + try (var ostr = new FileOutputStream(keystoreFile)) { + var keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + final var keyPair = keyPairGenerator.generateKeyPair(); + + final long tcur = System.currentTimeMillis(); + + final var dn = new X500Name("C=US, O=ONAP, OU=OSAAF, OU=policy@policy.onap.org:DEV, CN=policy"); + final var serial = BigInteger.valueOf(new SecureRandom().nextInt()); + final var notBefore = new Date(tcur); + final var notAfter = new Date(tcur + TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS)); + final var pubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); + + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA") + .setProvider(new BouncyCastleFipsProvider()).build(keyPair.getPrivate()); + + X509CertificateHolder holder = new X509v3CertificateBuilder(dn, serial, notBefore, notAfter, dn, pubKeyInfo) + .addExtension(Extension.subjectAlternativeName, false, names).build(signer); + + var cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleFipsProvider()) + .getCertificate(holder); + final Certificate[] chain = {cert}; + + var keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, null); + keystore.setKeyEntry("policy@policy.onap.org", keyPair.getPrivate(), PRIVATE_KEY_PASSWORD.toCharArray(), + chain); + + keystore.store(ostr, KEYSTORE_PASSWORD.toCharArray()); + + } catch (NoSuchAlgorithmException | OperatorCreationException | CertificateException | KeyStoreException e) { + throw new IOException("cannot create certificate", e); + } + } + + // may be overridden by junit tests + + protected String getKeystoreSanName() { + return KEYSTORE_SAN; + } +} diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java index f457dd21..1ab1f285 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java @@ -2,7 +2,7 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 2021 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. @@ -70,7 +70,7 @@ public class ExceptionsTester extends ThrowablesTester { * if the constructed objects fail to pass various tests */ public <T extends Exception> int testAllException(final Class<T> claz) { - int ncons = 0; + var ncons = 0; ncons += testAllThrowable(claz); ncons += testException(claz); @@ -111,8 +111,8 @@ public class ExceptionsTester extends ThrowablesTester { return 0; } - Exception cause = new Exception(EXPECTED_EXCEPTION_MSG); - T ex = newInstance(cons, cause); + var cause = new Exception(EXPECTED_EXCEPTION_MSG); + var ex = newInstance(cons, cause); assertNotNull(ex.toString()); assertEquals(ex.getMessage(), ex.getMessage()); @@ -151,8 +151,8 @@ public class ExceptionsTester extends ThrowablesTester { return 0; } - Exception cause = new Exception(EXPECTED_EXCEPTION_MSG); - T ex = newInstance(cons, "world", cause); + var cause = new Exception(EXPECTED_EXCEPTION_MSG); + var ex = newInstance(cons, "world", cause); assertNotNull(ex.toString()); assertEquals("world", ex.getMessage()); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java index 0fba944e..06ca8046 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java @@ -2,7 +2,7 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 2020-2021 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,7 +27,6 @@ import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +39,7 @@ public class ThrowablesTester { private static Logger logger = LoggerFactory.getLogger(ThrowablesTester.class); - public static final String EXPECTED_EXCEPTION_MSG = + public static final String EXPECTED_EXCEPTION_MSG = "expected exception"; private static final String EXPECTED_SUPPRESSED_EXCEPTION_MSG = "expected suppressed exception"; @@ -74,7 +73,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> int testAllThrowable( final Class<T> claz) { - int ncons = 0; + var ncons = 0; ncons += testDefault(claz); ncons += testString(claz); @@ -113,7 +112,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons); + var ex = newInstance(cons); assertNotNull(ex.toString()); assertNull(ex.getMessage()); @@ -152,7 +151,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, "hello"); + var ex = newInstance(cons, "hello"); assertNotNull(ex.toString()); assertEquals("hello", ex.getMessage()); @@ -192,7 +191,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, CAUSE); + var ex = newInstance(cons, CAUSE); assertEquals(ex.getMessage(), ex.getMessage()); assertNotNull(ex.toString()); @@ -232,7 +231,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, "world", CAUSE); + var ex = newInstance(cons, "world", CAUSE); assertNotNull(ex.toString()); assertEquals("world", ex.getMessage()); @@ -383,7 +382,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testSuppressStack( final Constructor<T> cons) { - T ex = newInstance(cons, "yes,yes", CAUSE, true, true); + var ex = newInstance(cons, "yes,yes", CAUSE, true, true); ex.addSuppressed(SUPPRESSED); @@ -421,7 +420,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testSuppressNoStack( final Constructor<T> cons) { - T ex = newInstance(cons, "yes,no", CAUSE, true, false); + var ex = newInstance(cons, "yes,no", CAUSE, true, false); ex.addSuppressed(SUPPRESSED); @@ -459,7 +458,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testNoSuppressStack( final Constructor<T> cons) { - T ex = newInstance(cons, "no,yes", CAUSE, false, true); + var ex = newInstance(cons, "no,yes", CAUSE, false, true); ex.addSuppressed(SUPPRESSED); @@ -495,7 +494,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testNoSuppressNoStack( final Constructor<T> cons) { - T ex = newInstance(cons, "no,no", CAUSE, false, false); + var ex = newInstance(cons, "no,no", CAUSE, false, false); ex.addSuppressed(SUPPRESSED); @@ -530,8 +529,7 @@ public class ThrowablesTester { } catch (NoSuchMethodException | SecurityException e) { // this constructor is not defined so nothing to test - logger.debug("skipped test, no constructor for: " - + claz + " due to: " + e); + logger.debug("skipped test, no constructor for: {}", claz, e); return null; } } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java index f9ae39ac..ab09291c 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,7 +29,7 @@ import com.openpojo.reflection.PojoClass; import com.openpojo.validation.affirm.Affirm; import com.openpojo.validation.test.Tester; import com.openpojo.validation.utils.ValidationHelper; - +import lombok.AllArgsConstructor; import org.hamcrest.Matcher; @@ -38,23 +38,19 @@ import org.hamcrest.Matcher; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@SuppressWarnings("rawtypes") +@AllArgsConstructor public class ToStringTester implements Tester { - private final Matcher matcher; + private final Matcher<?> matcher; public ToStringTester() { matcher = anything(); } - public ToStringTester(final Matcher matcher) { - this.matcher = matcher; - } - @SuppressWarnings("unchecked") @Override public void run(final PojoClass pojoClass) { - final Class clazz = pojoClass.getClazz(); + final Class<?> clazz = pojoClass.getClazz(); if (anyOf(matcher).matches(clazz)) { final Object classInstance = ValidationHelper.getBasicInstance(pojoClass); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java index 19c50968..27d9fcc6 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java @@ -2,7 +2,7 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019, 2021 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 +22,13 @@ package org.onap.policy.common.utils.test.log.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import com.google.re2j.Matcher; +import com.google.re2j.Pattern; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Queue; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * This is an appender that is intended for use by JUnit tests that wish to @@ -110,7 +110,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> { } for (Pattern p : patterns.values()) { - Matcher matcher = p.matcher(msg); + var matcher = p.matcher(msg); if (matcher.find()) { addGroupMatch(matcher); @@ -129,7 +129,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> { private void addGroupMatch(final Matcher mat) { int ngroups = mat.groupCount(); - for (int x = 1; x <= ngroups; ++x) { + for (var x = 1; x <= ngroups; ++x) { String txt = mat.group(x); if (txt != null) { diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java index 79d2f226..04a9b3f6 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PeriodicItem.java @@ -1,8 +1,8 @@ -/* +/*-- * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,6 @@ package org.onap.policy.common.utils.time; -import org.onap.policy.common.utils.time.TestTime; - /** * Work item that runs periodically. */ diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java new file mode 100644 index 00000000..b29f7421 --- /dev/null +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.utils.time; + +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.Executor; +import lombok.Getter; + +/** + * Executor that will run tasks until the queue is empty or a maximum number of tasks have + * been executed. Doesn't actually run anything until {@link #runAll()} is invoked. + */ +public class PseudoExecutor implements Executor { + + /** + * Tasks to be run. + */ + @Getter + private final Queue<Runnable> tasks = new LinkedList<>(); + + + /** + * Gets the queue length. + * + * @return the queue length + */ + public int getQueueLength() { + return tasks.size(); + } + + @Override + public void execute(Runnable command) { + tasks.add(command); + } + + /** + * Runs all tasks until the queue is empty or the maximum number of tasks have been + * reached. + * + * @param maxTasks maximum number of tasks to run + * @return {@code true} if the queue is empty, {@code false} if the maximum number of + * tasks have been reached before the queue was emptied + */ + public boolean runAll(int maxTasks) { + for (var count = 0; count < maxTasks && !tasks.isEmpty(); ++count) { + tasks.remove().run(); + } + + return tasks.isEmpty(); + } +} diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java index 4f9b32c9..71a24528 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 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. @@ -31,6 +31,7 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; +import lombok.Getter; /** * Scheduled executor service that uses {@link TestTimeMulti} to execute its tasks. Note: @@ -48,6 +49,7 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService * {@code True} if {@link #shutdown()} or {@link #shutdownNow()} has been called, * {@code false} otherwise. */ + @Getter private boolean shutdown = false; /** @@ -80,13 +82,8 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService } @Override - public boolean isShutdown() { - return shutdown; - } - - @Override public boolean isTerminated() { - return shutdown; + return isShutdown(); } @Override diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java index 6ce7bc04..34c756bb 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 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 +39,7 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule /** * {@code True} if this task is periodic, {@code false} otherwise. */ + @Getter private final boolean periodic; /** @@ -82,11 +83,6 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule } @Override - public boolean isPeriodic() { - return periodic; - } - - @Override public void run() { if (isPeriodic()) { super.runAndReset(); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java index 54560316..67371bb9 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/RunnableItem.java @@ -1,8 +1,8 @@ -/* +/*- * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ package org.onap.policy.common.utils.time; import java.util.concurrent.Future; import lombok.AccessLevel; import lombok.Getter; -import org.onap.policy.common.utils.time.TestTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,7 +79,7 @@ class RunnableItem extends WorkItem { try { action.run(); } catch (RuntimeException e) { - logger.warn("work item {} threw an exception {}", this, e); + logger.warn("work item {} threw an exception", this, e); } } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java index 420021f3..ace19160 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Common Utils-Test * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019, 2021 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,12 +22,14 @@ package org.onap.policy.common.utils.time; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; +import lombok.NoArgsConstructor; /** * "Current" time, when running junit tests. This is intended to be injected into classes * under test, to replace their {@link CurrentTime} objects. When {@link #sleep(long)} is * invoked, it simply advances the notion of "current" time and returns immediately. */ +@NoArgsConstructor public class TestTime extends CurrentTime { /** @@ -35,14 +37,6 @@ public class TestTime extends CurrentTime { */ private AtomicLong tcur = new AtomicLong(System.currentTimeMillis()); - /** - * Constructor. - * - */ - public TestTime() { - super(); - } - @Override public long getMillis() { return tcur.get(); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java index f52105ed..9e61eaa3 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2021 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. @@ -29,7 +29,6 @@ import java.util.PriorityQueue; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import lombok.Getter; -import org.onap.policy.common.utils.time.TestTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -180,7 +179,7 @@ public class TestTimeMulti extends TestTime { long realEnd = System.currentTimeMillis() + maxWaitMs; while (System.currentTimeMillis() < realEnd) { - if (condition.call()) { + if (Boolean.TRUE.equals(condition.call())) { return; } @@ -190,11 +189,13 @@ public class TestTimeMulti extends TestTime { } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("interrupted while waiting for condition", e); - fail("interrupted while waiting for condition: " + e.getMessage()); + // disabling sonar, as this is only used by junit tests + fail("interrupted while waiting for condition: " + e.getMessage()); // NOSONAR } catch (Exception e) { logger.error("condition evaluator threw an exception", e); - fail("condition evaluator threw an exception: " + e.getMessage()); + // disabling sonar, as this is only used by junit tests + fail("condition evaluator threw an exception: " + e.getMessage()); // NOSONAR } fail(NEVER_SATISFIED); @@ -281,7 +282,7 @@ public class TestTimeMulti extends TestTime { return; } - SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread()); + var item = new SleepItem(this, sleepMs, Thread.currentThread()); enqueue(item); // wait for the item to fire @@ -299,7 +300,7 @@ public class TestTimeMulti extends TestTime { logger.info("enqueue work item {}", item); synchronized (updateLock) { queue.add(item); - updateLock.notify(); + updateLock.notifyAll(); } } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java index af3d5d7e..cd690602 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/WorkItem.java @@ -1,8 +1,8 @@ -/* +/*-- * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ package org.onap.policy.common.utils.time; import lombok.AccessLevel; import lombok.Getter; -import org.onap.policy.common.utils.time.TestTime; /** * Work item to be executed at some time. |