diff options
Diffstat (limited to 'utils-test/src')
25 files changed, 626 insertions, 226 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 f37f32a1..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-2019 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,28 +28,28 @@ 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 javax.script.Bindings; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; +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.MapContext; import org.slf4j.Logger; 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); @@ -61,11 +62,12 @@ public class GsonTestUtils { /** * Engine used to interpolate strings before they're compared. */ - private static ScriptEngine engineInstance = null; + private static JexlEngine engineInstance = null; /** * Used to encode and decode an object via gson. */ + @Getter private Gson gson; /** @@ -78,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 @@ -109,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")); @@ -122,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())); } @@ -168,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 } /** @@ -178,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()); } @@ -192,42 +183,37 @@ 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; } // bind the object to the variable, "obj" - ScriptEngine eng = getEngine(); - Bindings bindings = eng.createBindings(); - bindings.put("obj", object); + JexlEngine eng = getEngine(); + JexlContext context = new MapContext(); + 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.eval(script, bindings); - bldr.append(result == null ? "null" : result.toString()); - - } catch (ScriptException 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 @@ -241,10 +227,10 @@ public class GsonTestUtils { * * @return the script engine */ - private static ScriptEngine getEngine() { + private static JexlEngine getEngine() { if (engineInstance == null) { // race condition here, but it's ok to overwrite with a new engine - engineInstance = new ScriptEngineManager().getEngineByName("javascript"); + engineInstance = new JexlBuilder().create(); } return engineInstance; @@ -270,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(); @@ -296,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. diff --git a/utils-test/src/main/resources/keystore_san.txt b/utils-test/src/main/resources/keystore_san.txt new file mode 100644 index 00000000..38428ea0 --- /dev/null +++ b/utils-test/src/main/resources/keystore_san.txt @@ -0,0 +1,15 @@ +DNS:policy +DNS:drools +DNS:drools.onap +DNS:policy-apex-pdp +DNS:policy-apex-pdp.onap +DNS:policy-api +DNS:policy-api.onap +DNS:policy-distribution +DNS:policy-distribution.onap +DNS:policy-pap +DNS:policy-pap.onap +DNS:policy-xacml-pdp +DNS:policy-xacml-pdp.onap +DNS:policy.api.simpledemo.onap.org +DNS:policy-sim diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java index 35fea577..51522ec0 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-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. @@ -34,7 +35,9 @@ import com.google.gson.JsonParseException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import javax.script.ScriptException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; import org.junit.Before; import org.junit.Test; @@ -76,10 +79,11 @@ public class GsonTestUtilsTest { utils.compareGson(data, GsonTestUtilsTest.class); // file not found - assertThatThrownBy(() -> utils.compareGson(data, - new File(GsonTestUtilsTest.class.getSimpleName() + "-NotFound.json"))) - .isInstanceOf(JsonParseException.class) - .hasCauseInstanceOf(FileNotFoundException.class); + File file = new File(GsonTestUtilsTest.class.getSimpleName() + "-NotFound.json"); + + assertThatThrownBy(() -> utils.compareGson(data, file)) + .isInstanceOf(JsonParseException.class) + .hasCauseInstanceOf(FileNotFoundException.class); // force I/O error while reading file GsonTestUtils utils2 = new GsonTestUtils() { @@ -136,11 +140,7 @@ public class GsonTestUtilsTest { data.setText(null); result = utils.applyScripts("use ${obj.text} this", data); assertEquals("use null this", result); - - assertThatThrownBy(() -> utils.applyScripts("use ${obj.text} this", null)) - .isInstanceOf(JsonParseException.class) - .hasCauseInstanceOf(ScriptException.class) - .hasMessage("cannot expand element: ${obj.text}"); + assertEquals("use null this", utils.applyScripts("use ${obj.text} this", null)); } @Test @@ -224,29 +224,12 @@ public class GsonTestUtilsTest { assertEquals("[300,{'objE':true,'objEStr':'obj-e-string'},false]".replace('\'', '"'), jsonEl.toString()); } + @Setter + @Getter + @ToString public static class Data { private int id; private String text; - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - @Override - public String toString() { - return "Data [id=" + id + ", text=" + text + "]"; - } } } 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 95abd4db..203c78ec 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 @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Modificaitons Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +42,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.utils.io.Serializer.Factory; -import org.powermock.reflect.Whitebox; +import org.springframework.test.util.ReflectionTestUtils; public class SerializerTest { private static final String FACTORY = "factory"; @@ -53,12 +54,12 @@ public class SerializerTest { @BeforeClass public static void setUpBeforeClass() { - saveFactory = Whitebox.getInternalState(Serializer.class, FACTORY); + saveFactory = (Factory) ReflectionTestUtils.getField(Serializer.class, FACTORY); } @AfterClass public static void tearDownAfterClass() { - Whitebox.setInternalState(Serializer.class, FACTORY, saveFactory); + ReflectionTestUtils.setField(Serializer.class, FACTORY, saveFactory); } @Before @@ -80,7 +81,7 @@ public class SerializerTest { byte[] data2 = Serializer.serialize(obj1); assertEquals(Arrays.toString(data), Arrays.toString(data2)); - MyObject obj2 = Serializer.deserialize(MyObject.class, data); + MyObject obj2 = Serializer.roundTrip(obj1); assertEquals(obj1.value, obj2.value); } @@ -210,16 +211,14 @@ public class SerializerTest { } }); - assertThatThrownBy(() -> Serializer.serialize(new MyObject(130))).isEqualTo(ex2); + assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(130))).isEqualTo(ex2); } @Test public void testDeserialize() throws Exception { MyObject obj1 = new MyObject(3); - byte[] data = Serializer.serialize(obj1); - - MyObject obj2 = Serializer.deserialize(MyObject.class, data); + MyObject obj2 = Serializer.roundTrip(obj1); assertEquals(obj1.value, obj2.value); } @@ -249,8 +248,7 @@ public class SerializerTest { } }); - byte[] data = Serializer.serialize(new MyObject(300)); - assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex); + assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(300))).isEqualTo(ex); } @Test @@ -267,8 +265,7 @@ public class SerializerTest { } }); - byte[] data = Serializer.serialize(new MyObject(310)); - assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex); + assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(310))).isEqualTo(ex); } @Test @@ -287,9 +284,20 @@ public class SerializerTest { */ text = text.replace("MyObject", "AnObject"); - byte[] data = text.getBytes(binary); + byte[] data2 = text.getBytes(binary); + + /* + * Use a factory that returns a byte array for "data2" instead of the real "data". + */ + setFactory(new Factory() { + @Override + public ByteArrayInputStream makeByteArrayInputStream(byte[] data) { + // read from "data2" instead of "data" + return super.makeByteArrayInputStream(data2); + } + }); - assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isInstanceOf(IOException.class) + assertThatThrownBy(() -> Serializer.roundTrip(obj1)).isInstanceOf(IOException.class) .hasCauseInstanceOf(ClassNotFoundException.class); } @@ -313,8 +321,7 @@ public class SerializerTest { } }); - byte[] data = Serializer.serialize(new MyObject(320)); - assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex); + assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(320))).isEqualTo(ex); } @Test @@ -348,8 +355,7 @@ public class SerializerTest { } }); - byte[] data = Serializer.serialize(new MyObject(330)); - assertThatThrownBy(() -> Serializer.deserialize(MyObject.class, data)).isEqualTo(ex2); + assertThatThrownBy(() -> Serializer.roundTrip(new MyObject(330))).isEqualTo(ex2); } @Test @@ -371,7 +377,7 @@ public class SerializerTest { * @param factory new factory to be set */ private void setFactory(Factory factory) { - Whitebox.setInternalState(Serializer.class, FACTORY, factory); + ReflectionTestUtils.setField(Serializer.class, FACTORY, factory); } /** diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java new file mode 100644 index 00000000..27bceacf --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java @@ -0,0 +1,151 @@ +/*- + * ============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 static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SelfSignedKeyStoreTest { + private static final String USER_DIR_PROP = "user.dir"; + + private static String saveUserDir; + private static String defaultName; + private static File defaultKeystore; + + + /** + * Saves the user.dir property and initializes static fields. + */ + @BeforeClass + public static void setUpBeforeClass() { + saveUserDir = System.getProperty(USER_DIR_PROP); + defaultName = saveUserDir + "/" + SelfSignedKeyStore.RELATIVE_PATH; + defaultKeystore = new File(defaultName); + } + + @Before + public void setUp() { + System.setProperty(USER_DIR_PROP, saveUserDir); + delete(defaultKeystore); + } + + @Test + public void testSelfSignedKeyStore() throws Exception { + SelfSignedKeyStore ks = new SelfSignedKeyStore(); + + assertThat(ks.getKeystoreName()).isEqualTo(defaultName); + assertThat(defaultKeystore).exists(); + } + + @Test + public void testSelfSignedKeyStoreString() throws IOException, InterruptedException { + String relName = "target/my-keystore"; + String altName = saveUserDir + "/" + relName; + File altFile = new File(altName); + + delete(altFile); + + SelfSignedKeyStore ks = new SelfSignedKeyStore(relName); + + assertThat(ks.getKeystoreName()).isEqualTo(altName); + assertThat(altFile).exists(); + } + + /** + * Tests the constructor, when the keystore already exists. + */ + @Test + public void testSelfSignedKeyStoreStringExists() throws Exception { + new SelfSignedKeyStore(); + assertThat(defaultKeystore).exists(); + + // change the timestamp on the keystore so it's a little old, but not too old + defaultKeystore.setLastModified( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES)); + long tcurrent = defaultKeystore.lastModified(); + + // this should not recreate the keystore, thus the timestamp should be unchanged + new SelfSignedKeyStore(); + assertThat(defaultKeystore.lastModified()).isEqualTo(tcurrent); + + // change the timestamp on the keystore so it's too old + defaultKeystore.setLastModified( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1000, TimeUnit.HOURS)); + tcurrent = defaultKeystore.lastModified(); + + // this should recreate the keystore + new SelfSignedKeyStore(); + assertThat(defaultKeystore.lastModified()).isGreaterThan(tcurrent); + } + + /** + * Tests the constructor, when the SAN file is not found. + */ + @Test + public void testSelfSignedKeyStoreStringNoSanFile() throws Exception { + assertThatThrownBy(() -> new SelfSignedKeyStore() { + @Override + protected String getKeystoreSanName() { + return "unknown/san/file.txt"; + } + }).isInstanceOf(FileNotFoundException.class).hasMessageContaining("file.txt"); + } + + /** + * Tests the constructor, when write fails. + */ + @Test + public void testSelfSignedKeyStoreStringWriteFailure() throws Exception { + assertThatThrownBy(() -> new SelfSignedKeyStore("target/unknown/path/to/keystore")) + .isInstanceOf(IOException.class); + } + + @Test + public void testGetKeystoreName() throws Exception { + String relpath = SelfSignedKeyStore.RELATIVE_PATH; + + // append the first part of the relative path to user.dir + System.setProperty(USER_DIR_PROP, saveUserDir + "/" + relpath.substring(0, relpath.indexOf('/'))); + + // create a keystore using the remaining components of the relative path + SelfSignedKeyStore ks = new SelfSignedKeyStore(relpath.substring(relpath.indexOf('/') + 1)); + + assertThat(ks.getKeystoreName()).isEqualTo(defaultName); + assertThat(defaultKeystore).exists(); + + // try again using the original relative path - should fail, as it's now deeper + assertThatThrownBy(() -> new SelfSignedKeyStore(relpath)).isInstanceOf(IOException.class); + } + + private static void delete(File file) { + if (file.exists()) { + assertThat(file.delete()).isTrue(); + } + } +} 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 cd6edf76..4c2237fc 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Common Utils-Test * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,13 +26,11 @@ import static org.junit.Assert.assertFalse; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; - import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -376,21 +374,6 @@ public class ExtractAppenderTest { // create some threads to get extractions addThread(tend, err, xtxt -> app.getExtracted()); - // create some threads to clear extractions - addThread(tend, err, xtxt -> { - app.clearExtractions(); - - // don't want to clear the list too frequently - // so sleep a bit in between - try { - Thread.sleep(10L + Integer.valueOf(xtxt)); - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw e; - } - }); - /* * Finally ready to start. */ diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java new file mode 100644 index 00000000..0046f791 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.utils.time; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class PseudoExecutorTest { + private int invoked; + private PseudoExecutor executor; + + @Before + public void setUp() { + invoked = 0; + executor = new PseudoExecutor(); + } + + @Test + public void test() { + assertEquals(0, executor.getQueueLength()); + assertEquals(0, executor.getTasks().size()); + assertTrue(executor.runAll(0)); + + executor.execute(() -> invoked++); + executor.execute(() -> invoked++); + executor.execute(() -> invoked++); + assertEquals(3, executor.getTasks().size()); + assertEquals(3, executor.getQueueLength()); + + assertFalse(executor.runAll(2)); + assertEquals(2, invoked); + assertEquals(1, executor.getQueueLength()); + + assertTrue(executor.runAll(2)); + assertEquals(3, invoked); + assertEquals(0, executor.getQueueLength()); + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java index 70820c44..745e989f 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java @@ -2,7 +2,7 @@ * ============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. @@ -27,6 +27,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Collections; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; @@ -37,6 +38,7 @@ import org.junit.Test; public class PseudoScheduledExecutorServiceTest { private static final long DELAY_MS = 100L; private static final long PERIOD_MS = 200L; + private static final List<Callable<Object>> EMPTY_CALLABLES = Collections.emptyList(); private int ran; private int called; @@ -135,25 +137,25 @@ public class PseudoScheduledExecutorServiceTest { @Test public void testInvokeAllCollectionOfQextendsCallableOfT() { - assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList())) + assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES)) .isInstanceOf(UnsupportedOperationException.class); } @Test public void testInvokeAllCollectionOfQextendsCallableOfTLongTimeUnit() { - assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList(), 1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS)) .isInstanceOf(UnsupportedOperationException.class); } @Test public void testInvokeAnyCollectionOfQextendsCallableOfT() { - assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList())) + assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES)) .isInstanceOf(UnsupportedOperationException.class); } @Test public void testInvokeAnyCollectionOfQextendsCallableOfTLongTimeUnit() { - assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList(), 1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS)) .isInstanceOf(UnsupportedOperationException.class); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java index e23bbd29..248edf61 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.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,9 +31,11 @@ import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +@RunWith(MockitoJUnitRunner.class) public class PseudoScheduledFutureTest { private static final long DELAY_MS = 1000L; @@ -49,8 +51,6 @@ public class PseudoScheduledFutureTest { */ @Before public void setUp() { - MockitoAnnotations.initMocks(this); - when(work.getDelay()).thenReturn(DELAY_MS); count = 0; diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java index 49710538..d7316c1f 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java @@ -2,7 +2,7 @@ * ============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. @@ -83,8 +83,9 @@ public class PseudoTimerTest { @Test public void testScheduleTimerTaskDate() { - assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date())) - .isInstanceOf(UnsupportedOperationException.class); + MyTask task = new MyTask(); + Date curdate = new Date(); + assertThatThrownBy(() -> timer.schedule(task, curdate)).isInstanceOf(UnsupportedOperationException.class); } @Test @@ -105,8 +106,9 @@ public class PseudoTimerTest { @Test public void testScheduleTimerTaskDateLong() { - assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date(), 1L)) - .isInstanceOf(UnsupportedOperationException.class); + MyTask task = new MyTask(); + Date curdate = new Date(); + assertThatThrownBy(() -> timer.schedule(task, curdate, 1L)).isInstanceOf(UnsupportedOperationException.class); } @Test @@ -127,7 +129,9 @@ public class PseudoTimerTest { @Test public void testScheduleAtFixedRateTimerTaskDateLong() { - assertThatThrownBy(() -> timer.scheduleAtFixedRate(new MyTask(), new Date(), 1L)) + MyTask task = new MyTask(); + Date curdate = new Date(); + assertThatThrownBy(() -> timer.scheduleAtFixedRate(task, curdate, 1L)) .isInstanceOf(UnsupportedOperationException.class); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java index 4e6f92b5..d2fc8d58 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java @@ -2,7 +2,7 @@ * ============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,6 +20,7 @@ package org.onap.policy.common.utils.time; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -88,7 +89,7 @@ public class WorkItemTest { @Test public void testFire() { // ensure no exception is thrown - item.fire(); + assertThatCode(() -> item.fire()).doesNotThrowAnyException(); } @Test |