diff --git a/Jenkinsfile b/Jenkinsfile index 3b19af3..efd463b 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -109,7 +109,7 @@ def getSha1() { def mvn(args) { withMaven( - maven: 'maven-3.6.1', + maven: 'maven-3.9.4', globalMavenSettingsConfig: 'locusworks-settings' ) { @@ -183,4 +183,4 @@ def SetVersion( v ) { } } -return this \ No newline at end of file +return this diff --git a/pom.xml b/pom.xml index 5f563f8..6faff9a 100644 --- a/pom.xml +++ b/pom.xml @@ -18,11 +18,11 @@ - 2.14.1 - 1.7.32 - 2.12.5 - 1.8 - 1.8 + 2.20.0 + 2.0.9 + 2.15.2 + 17 + 17 https://nexus.locusworks.net @@ -31,28 +31,27 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M5 - - always - + 3.1.2 org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.11.0 ${maven.compiler.source} ${maven.compiler.target} true - - -Xlint:all - + + -Xlint:all + --add-exports + java.base/sun.security.jca=ALL-UNNAMED + org.owasp dependency-check-maven - 6.3.1 + 8.4.0 @@ -61,20 +60,77 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.10 + + + + prepare-agent + + + + report + prepare-package + + report + + + + jacoco-check + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + 1.00 + + + BRANCH + COVEREDRATIO + 1.00 + + + + + + + + - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter-api + 5.10.0 test + + org.junit.jupiter + junit-jupiter-params + 5.10.0 + test + + + org.mockito + mockito-core + 5.5.0 + test + + org.flywaydb flyway-core - 7.15.0 + 9.22.1 org.apache.logging.log4j @@ -103,14 +159,14 @@ - org.apache.httpcomponents - httpclient - 4.5.13 + org.apache.httpcomponents.client5 + httpclient5 + 5.2.1 org.apache.httpcomponents httpmime - 4.5.13 + 4.5.14 @@ -133,7 +189,7 @@ com.google.code.gson gson - 2.8.8 + 2.10.1 @@ -176,4 +232,4 @@ - \ No newline at end of file + diff --git a/src/main/java/net/locusworks/common/configuration/PropertiesManager.java b/src/main/java/net/locusworks/common/configuration/PropertiesManager.java index c99a16d..a9b8a0b 100644 --- a/src/main/java/net/locusworks/common/configuration/PropertiesManager.java +++ b/src/main/java/net/locusworks/common/configuration/PropertiesManager.java @@ -15,11 +15,13 @@ import java.util.Properties; import java.util.stream.Collectors; import net.locusworks.common.immutables.Pair; +import net.locusworks.common.immutables.Unit; + /** * Properties manager class to help load and read properties * @author Isaac Parenteau - * @version 1.0.0 - * @date 02/15/2018 + * @version 2.0.0 + * @date 09/17/2023 */ public class PropertiesManager { /** @@ -88,7 +90,8 @@ public class PropertiesManager { * @return a map containing the results of the values added */ public static Map addConfiguration(Properties to, Properties from) { - Map results = from.entrySet() + + return from.entrySet() .stream() .filter(entry -> !to.containsKey(entry.getKey())) .map(entry -> { @@ -97,9 +100,7 @@ public class PropertiesManager { to.put(key, value); return new Pair(key, value); }) - .collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2())); - - return results; + .collect(Collectors.toMap(Unit::getValue1, Pair::getValue2)); } /** @@ -109,19 +110,17 @@ public class PropertiesManager { * @return a map containing the results of the values removed */ public static Map removeConfiguration(Properties from, Properties comparedTo) { - Map results = from.keySet() + + return from.keySet() .stream() .filter(key -> !comparedTo.containsKey(key)) //only get the items that are not in the comparedTo properties .map(key -> new Pair(String.valueOf(key), String.valueOf(from.get(key)))) - .collect(Collectors.toList()) //Create a list of paired items (key value) of the items that were filtered + .toList() //Create a list of paired items (key value) of the items that were filtered .stream() - .map(pair -> { //remove those pairs from the from properties + .peek(pair -> { //remove those pairs from the from properties from.remove(pair.getValue1()); - return pair; }) - .collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2())); //create a map of what was removed - - return results; + .collect(Collectors.toMap(Unit::getValue1, Pair::getValue2)); } /** diff --git a/src/main/java/net/locusworks/common/crypto/AES.java b/src/main/java/net/locusworks/common/crypto/AES.java index 9c67983..b44355a 100644 --- a/src/main/java/net/locusworks/common/crypto/AES.java +++ b/src/main/java/net/locusworks/common/crypto/AES.java @@ -7,10 +7,7 @@ import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; +import java.security.*; import java.util.Base64; import net.locusworks.common.utils.RandomString; @@ -21,7 +18,7 @@ import static net.locusworks.common.Charsets.UTF_8; /** * AES encryption/decryption class * This class will encrypt/decrypt data. The encryption key is never known. - * Instead it is is generated by the provided seed. As long as the seed stays the same + * Instead, it is generated by the provided seed. As long as the seed stays the same * the key will remain the same and the encryption/decryption will work. This * provides and added security. * @author Isaac Parenteau @@ -62,7 +59,6 @@ public class AES { * @param seed Seed to initialize SecureRandom with * @return SecureRandom object * @throws NoSuchAlgorithmException thrown when algorithm can't be used - * @throws NoSuchProviderException thrown when the provider cant be found */ private static SecureRandom getSecureRandom(String seed) throws NoSuchAlgorithmException { SecureRandom sr = SecureRandom.getInstance(ALGORITHM); @@ -73,7 +69,7 @@ public class AES { /** * Initialize the aes engine * @param key secret key to use - * @param sr + * @param sr the secure random class */ private void init(final byte[] key, SecureRandom sr) { try { @@ -81,8 +77,7 @@ public class AES { this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE); this.ivParamSpec = new IvParameterSpec(RandomString.getBytes(16, sr)); } catch (Exception ex) { - System.err.println(ex); - throw new IllegalArgumentException("Unable to initalize encryption:", ex); + throw new IllegalArgumentException("Unable to initialize encryption:", ex); } } @@ -122,7 +117,7 @@ public class AES { } } - public AES setSeed(String seed) { + public AES withSeed(String seed) { if (this.seed == null || !this.seed.equals(seed)) { initSecureKey(seed); } @@ -144,9 +139,7 @@ public class AES { } public static AES createInstance(String seed) { - AES aes = new AES(); - aes.setSeed(seed); - return aes; + return new AES().withSeed(seed); } public static void main(String[] args) throws NoSuchAlgorithmException { diff --git a/src/main/java/net/locusworks/common/crypto/AESKey.java b/src/main/java/net/locusworks/common/crypto/AESKey.java index b64d6b8..3bec359 100644 --- a/src/main/java/net/locusworks/common/crypto/AESKey.java +++ b/src/main/java/net/locusworks/common/crypto/AESKey.java @@ -1,13 +1,14 @@ package net.locusworks.common.crypto; +import java.io.Serial; import java.security.PrivateKey; import net.locusworks.common.Charsets; public class AESKey implements PrivateKey { - private static final long serialVersionUID = -8452357427706386362L; - private String seed; + @Serial private static final long serialVersionUID = -8452357427706386362L; + private final String seed; public AESKey(String seed) { this.seed = seed; diff --git a/src/main/java/net/locusworks/common/crypto/KeyFile.java b/src/main/java/net/locusworks/common/crypto/KeyFile.java index 9b71ce3..0ebffec 100644 --- a/src/main/java/net/locusworks/common/crypto/KeyFile.java +++ b/src/main/java/net/locusworks/common/crypto/KeyFile.java @@ -114,7 +114,7 @@ public class KeyFile implements AutoCloseable { dosh.writeInt(item.length); dosh.write(item); })); - data = String.format("ssh-rsa", dosh.base64Encoded(), this.description); + data = String.format("ssh-rsa %s %s", dosh.base64Encoded(), this.description); IOUtils.writeStringToFile(fileName, data); } break; @@ -186,9 +186,9 @@ public class KeyFile implements AutoCloseable { } private static class KeySpecHelper { - private KeySpec keySpec; - private boolean isPrivate; - private EncryptionType encryptionType; + private final KeySpec keySpec; + private final boolean isPrivate; + private final EncryptionType encryptionType; public KeySpecHelper(KeySpec keySpec, boolean isPrivate, EncryptionType encryptionType) { super(); diff --git a/src/main/java/net/locusworks/common/crypto/SSHEncodedKeySpec.java b/src/main/java/net/locusworks/common/crypto/SSHEncodedKeySpec.java index 0572364..94a33a2 100644 --- a/src/main/java/net/locusworks/common/crypto/SSHEncodedKeySpec.java +++ b/src/main/java/net/locusworks/common/crypto/SSHEncodedKeySpec.java @@ -37,8 +37,7 @@ public class SSHEncodedKeySpec extends EncodedKeySpec { checkArguments(SSH_MARKER.equals(marker), "Looking for marker %s but received %s", SSH_MARKER, marker); BigInteger publicExponent = new BigInteger(readLengthFirst(stream)); BigInteger modulus = new BigInteger(readLengthFirst(stream)); - RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent); - return keySpec; + return new RSAPublicKeySpec(modulus, publicExponent); } catch (Exception ex) { throw new InvalidKeySpecException(ex); } diff --git a/src/main/java/net/locusworks/common/exceptions/ApplicationException.java b/src/main/java/net/locusworks/common/exceptions/ApplicationException.java index 0ade43a..40cb230 100644 --- a/src/main/java/net/locusworks/common/exceptions/ApplicationException.java +++ b/src/main/java/net/locusworks/common/exceptions/ApplicationException.java @@ -1,5 +1,7 @@ package net.locusworks.common.exceptions; +import java.io.Serial; + /*** * Custom exception class for the patch repository * @author Isaac Parenteau @@ -8,7 +10,7 @@ package net.locusworks.common.exceptions; public class ApplicationException extends Exception { private final Integer code; boolean success = false; - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public static ApplicationException egregiousServer() { return new ApplicationException(9001, "Something went wrong. Please see logs for details"); diff --git a/src/main/java/net/locusworks/common/immutables/Triplet.java b/src/main/java/net/locusworks/common/immutables/Triplet.java index 5ff5c83..065b7e2 100644 --- a/src/main/java/net/locusworks/common/immutables/Triplet.java +++ b/src/main/java/net/locusworks/common/immutables/Triplet.java @@ -48,10 +48,8 @@ public class Triplet extends Pair { @Override public boolean equals(Object other) { - if (!(other instanceof Triplet)) return false; - - Triplet otherTriplet = (Triplet)other; - + if (!(other instanceof Triplet otherTriplet)) return false; + return super.equals(otherTriplet) && this.getValue3().equals(otherTriplet.getValue3()); } -} \ No newline at end of file +} diff --git a/src/main/java/net/locusworks/common/interfaces/AutoCloseableIterator.java b/src/main/java/net/locusworks/common/interfaces/AutoCloseableIterator.java index d494fcb..bc02ab1 100644 --- a/src/main/java/net/locusworks/common/interfaces/AutoCloseableIterator.java +++ b/src/main/java/net/locusworks/common/interfaces/AutoCloseableIterator.java @@ -5,6 +5,6 @@ import java.util.Iterator; public interface AutoCloseableIterator extends Iterator, AutoCloseable { @Override - public void close(); + void close(); } diff --git a/src/main/java/net/locusworks/common/io/IOUtils.java b/src/main/java/net/locusworks/common/io/IOUtils.java index 7ce89f1..71c3bf4 100644 --- a/src/main/java/net/locusworks/common/io/IOUtils.java +++ b/src/main/java/net/locusworks/common/io/IOUtils.java @@ -172,7 +172,7 @@ public class IOUtils { */ public static void copy(final InputStream input, final Writer output, final Charset inputEncoding) throws IOException { - final InputStreamReader in = new InputStreamReader(input, inputEncoding.toString()); + final InputStreamReader in = new InputStreamReader(input, inputEncoding); copy(in, output); } diff --git a/src/main/java/net/locusworks/common/objectmapper/ObjectMapperHelper.java b/src/main/java/net/locusworks/common/objectmapper/ObjectMapperHelper.java index 9ce2050..0fa5993 100644 --- a/src/main/java/net/locusworks/common/objectmapper/ObjectMapperHelper.java +++ b/src/main/java/net/locusworks/common/objectmapper/ObjectMapperHelper.java @@ -20,7 +20,7 @@ import com.google.gson.GsonBuilder; */ public class ObjectMapperHelper { - private static ObjectMapper mapper; + private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); @@ -145,4 +145,4 @@ public class ObjectMapperHelper { return new ObjectMapperListResults<>(ex); } } -} \ No newline at end of file +} diff --git a/src/main/java/net/locusworks/common/properties/ImmutableProperties.java b/src/main/java/net/locusworks/common/properties/ImmutableProperties.java index 0884479..05a1eef 100644 --- a/src/main/java/net/locusworks/common/properties/ImmutableProperties.java +++ b/src/main/java/net/locusworks/common/properties/ImmutableProperties.java @@ -1,10 +1,11 @@ package net.locusworks.common.properties; +import java.io.Serial; import java.util.Properties; public class ImmutableProperties extends Properties { - private static final long serialVersionUID = 65942088008978137L; + @Serial private static final long serialVersionUID = 65942088008978137L; public ImmutableProperties() { super(); @@ -13,8 +14,8 @@ public class ImmutableProperties extends Properties { public ImmutableProperties(Properties props) { super(); if (props == null || props.isEmpty()) return; - - props.entrySet().forEach(item -> this.put(item.getKey(), item.getValue())); + + this.putAll(props); } @Override diff --git a/src/main/java/net/locusworks/common/properties/OrderedProperties.java b/src/main/java/net/locusworks/common/properties/OrderedProperties.java index dcefa70..410d7c9 100644 --- a/src/main/java/net/locusworks/common/properties/OrderedProperties.java +++ b/src/main/java/net/locusworks/common/properties/OrderedProperties.java @@ -24,15 +24,7 @@ package net.locusworks.common.properties; * * */ -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.io.OutputStreamWriter; -import java.io.BufferedWriter; +import java.io.*; import java.util.Collections; import java.util.Date; import java.util.Enumeration; @@ -123,7 +115,7 @@ public class OrderedProperties extends LinkedHashMap { /** * use serialVersionUID from JDK 1.1.X for interoperability */ - private static final long serialVersionUID = 4112578634023874840L; + @Serial private static final long serialVersionUID = 4112578634023874840L; /** * A property list that contains default values for any keys not diff --git a/src/main/java/net/locusworks/common/utils/DataOutputStreamHelper.java b/src/main/java/net/locusworks/common/utils/DataOutputStreamHelper.java index 238c203..e45612f 100644 --- a/src/main/java/net/locusworks/common/utils/DataOutputStreamHelper.java +++ b/src/main/java/net/locusworks/common/utils/DataOutputStreamHelper.java @@ -8,7 +8,7 @@ import java.util.Base64; import net.locusworks.common.Charsets; -public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable{ +public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable { public DataOutputStreamHelper() { this(new ByteArrayOutputStream()); @@ -43,7 +43,7 @@ public class DataOutputStreamHelper extends DataOutputStream implements AutoClos try { super.out.close(); super.out = null; - } catch (Exception ex) {} + } catch (Exception ignored) {} } } diff --git a/src/main/java/net/locusworks/common/utils/DateTimeStampSerializer.java b/src/main/java/net/locusworks/common/utils/DateTimeStampSerializer.java index 2d13be6..88bef4e 100644 --- a/src/main/java/net/locusworks/common/utils/DateTimeStampSerializer.java +++ b/src/main/java/net/locusworks/common/utils/DateTimeStampSerializer.java @@ -1,6 +1,7 @@ package net.locusworks.common.utils; import java.io.IOException; +import java.io.Serial; import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; @@ -29,7 +30,7 @@ public class DateTimeStampSerializer extends StdSerializer { /** * */ - private static final long serialVersionUID = -4753139740916300831L; + @Serial private static final long serialVersionUID = -4753139740916300831L; public DateTimeStampSerializer() { this(null); diff --git a/src/main/java/net/locusworks/common/utils/Splitter.java b/src/main/java/net/locusworks/common/utils/Splitter.java index a29e914..d1af387 100644 --- a/src/main/java/net/locusworks/common/utils/Splitter.java +++ b/src/main/java/net/locusworks/common/utils/Splitter.java @@ -9,51 +9,51 @@ import static net.locusworks.common.utils.Checks.checkArguments; import static net.locusworks.common.utils.Checks.checkNotNull; public class Splitter { - + private String splitSeq; private boolean omitEmptyStrings = false; private int partition; private int limit; - + private static Splitter splitter; - + private Splitter(String seq) { this.splitSeq = seq; } - + private Splitter(int partition) { this.partition = partition; } - + public Splitter omitEmptyStrings() { this.omitEmptyStrings = true; return this; } - + public Splitter withLimit(int limit) { this.limit = limit; return this; } - + public MapSplitter withKeyValueSeparator(String separator) { checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null"); return new MapSplitter(this, separator); } - + public String[] splitToArray(String sentence) { List list = split(sentence); - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } - + public List split(String sentence) { checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty"); List list = new ArrayList<>(); - + if (!Utils.isEmptyString(splitSeq)) populateForTrimmer(sentence, list); - else + else populateForFixedWidth(sentence, list); - + return limit > 0 ? list.subList(0, limit) : list; } @@ -66,64 +66,67 @@ public class Splitter { private void populateForTrimmer(String sentence, List list) { for (String s : sentence.split(splitSeq)) { - if (s == null || (omitEmptyStrings && s.trim().isEmpty())) continue; + if (s == null || (omitEmptyStrings && s.trim().isEmpty())) + continue; list.add(s.trim()); } } - + public static Splitter fixedLengthSplit(int partition) { checkArguments(partition > 0, "Partition has to be greater than 0"); splitter = new Splitter(partition); return splitter; } - + public static Splitter on(String split) { checkNotNull(split, "Split value provided was null"); splitter = new Splitter(split); return splitter; } - + public static Splitter onNewLine() { return on("\\r?\\n"); } - + public static Splitter onSpace() { return on(" "); } - + public static class MapSplitter { - - private Splitter splitter; + + private final Splitter splitter; private String separator; private boolean skipInvalid = false; - + private MapSplitter(Splitter splitter, String separator) { checkNotNull(splitter, "Splitter cannot be null"); - checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null"); + checkArguments(!Utils.isEmptyString(separator), + "Key value separator cannot be empty or null"); this.splitter = splitter; this.separator = separator; } - + public MapSplitter skipInvalidKeyValues() { this.skipInvalid = true; return this; } - + public Map split(String sentence) { checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty"); Map map = new LinkedHashMap<>(); - + for (String s : splitter.split(sentence)) { String[] keyValue = s.split(separator); try { checkArguments(keyValue.length == 2, "invalid length found for key value mapping"); } catch (IllegalArgumentException ex) { - if (!skipInvalid) throw ex; + if (!skipInvalid) + throw ex; continue; } map.put(keyValue[0], keyValue[1]); } - + return map; } } diff --git a/src/main/java/net/locusworks/common/utils/Utils.java b/src/main/java/net/locusworks/common/utils/Utils.java index 9cc887e..2257988 100644 --- a/src/main/java/net/locusworks/common/utils/Utils.java +++ b/src/main/java/net/locusworks/common/utils/Utils.java @@ -2,6 +2,7 @@ package net.locusworks.common.utils; import java.lang.reflect.Array; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; @@ -47,7 +48,7 @@ public class Utils { } E firstVal = values[0]; - boolean equal = true; + boolean equal = !or; for (int i = 1; i < values.length; i++) { if (or) @@ -100,7 +101,7 @@ public class Utils { * * @param the type parameter * @param the type parameter - * @param mapClass The map class to map to i.e HashMap, TreeMap etc + * @param mapClass The map class to map to i.e. HashMap, TreeMap etc * @param mapKey the map key * @param mapValue the map value * @param data The data to place in the map @@ -109,9 +110,9 @@ public class Utils { */ @SuppressWarnings("unchecked") public static Map buildMap(Class mapClass, Class mapKey, Class mapValue, Object... data) { - Map results = new LinkedHashMap(); + Map results; try { - results = (Map) mapClass.newInstance(); + results = (Map) mapClass.getDeclaredConstructor().newInstance(); } catch (Exception ex) { throw new IllegalArgumentException("Unable to create instance of " + mapClass.getSimpleName()); } @@ -121,7 +122,7 @@ public class Utils { } Object key = null; - Integer step = -1; + int step = -1; for (Object value : data) { switch(++step % 2) { @@ -131,7 +132,7 @@ public class Utils { } if (value instanceof Class) { try { - value = ((Class)value).newInstance(); + value = ((Class)value).getDeclaredConstructor().newInstance(); } catch (Exception ex) { throw new IllegalArgumentException("Unable to create new instance of " + value); } @@ -150,7 +151,7 @@ public class Utils { results.put((K) key, (V) value); break; default: - throw new IllegalAccessError("Caculation for step was not a multiple of two. This shouldn't have happened"); + throw new IllegalAccessError("Calculation for step was not a multiple of two. This shouldn't have happened"); } } return results; @@ -166,10 +167,10 @@ public class Utils { */ @SuppressWarnings("unchecked") public static Set buildSet(Class setClass, Class setValue, Object... data) { - Set results = null; + Set results; try { - results = (Set) setClass.newInstance(); + results = (Set) setClass.getDeclaredConstructor().newInstance(); } catch (Exception ex) { throw new IllegalArgumentException("Unable to create instance of " + setClass.getSimpleName()); } @@ -192,21 +193,22 @@ public class Utils { * @return - Returns a HashMap using the data. */ public static HashMap buildStringHashMap(String... data) { - return new HashMap(buildMap(HashMap.class, String.class, String.class, (Object[]) data)); + return new HashMap<>(buildMap(HashMap.class, String.class, String.class, (Object[]) data)); } /** - * Clone list list. + * Clone list. * * @param the type parameter * @param list the list * * @return the list * @throws IllegalAccessException throw when an object in the list cannot be accessed through reflection - * @throws InstantiationException thrown when an boject in the list cannot be instantiated through reflection + * @throws InstantiationException thrown when an object in the list cannot be instantiated through reflection */ @SuppressWarnings("unchecked") - public static List cloneList(List list) throws InstantiationException, IllegalAccessException { + public static List cloneList(List list) + throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List clone = new ArrayList<>(); for (E item : list) { clone.add((E) cloneObject(item)); @@ -221,8 +223,9 @@ public class Utils { * @throws IllegalAccessException thrown when the filed cannot be access * @throws InstantiationException Thrown when the object cannot be instantiated */ - public static Object cloneObject(Object obj) throws InstantiationException, IllegalAccessException { - Object clone = obj.getClass().newInstance(); + public static Object cloneObject(Object obj) + throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + Object clone = obj.getClass().getDeclaredConstructor().newInstance(); for (Field field : obj.getClass().getDeclaredFields()) { try { field.setAccessible(true); @@ -241,9 +244,7 @@ public class Utils { field.set(clone, cloneObject(field.get(obj))); } } - } catch (NullPointerException ex) { - continue; - } + } catch (NullPointerException ignored) { } } return clone; } @@ -329,7 +330,7 @@ public class Utils { @SuppressWarnings("unchecked") public static Set extractFieldToSet(String fieldName, Iterable list) { Set newSet = new LinkedHashSet<>(); - Field field = null; + Field field; for (K item : Utils.safeList(list)) { try { field = getField(item.getClass(), fieldName); @@ -358,9 +359,9 @@ public class Utils { */ @SuppressWarnings("unchecked") public static List filterList(String fieldName, Object filter, Iterable list) { - List newList = new ArrayList(); + List newList = new ArrayList<>(); - Field field = null; + Field field; for (E item : safeList(list)) { try { @@ -384,7 +385,6 @@ public class Utils { /** * Find a value within the list. - * * Public method of type E called "findValue". * The method takes a parameter of type E called "itemToFind" and a String parameter called "fieldName" and a parameter of type List called "list". * The method loops through each item in the list and tries to get the class name and return it as an item. @@ -394,7 +394,7 @@ public class Utils { * @param list - The list to search * @param - The expected class of item to be found * @param - The expected class of the Iterable list - * @return - Returns returns the value of the specified field or null if there is no value. + * @return - Returns the value of the specified field or null if there is no value. * */ @SuppressWarnings({ "unchecked", "unlikely-arg-type" }) @@ -422,11 +422,10 @@ public class Utils { /** * Find values list. - * * Public method of type List called "findValues". - * The method takes a E type parameter called "valueToFind" and a String parameter called "fieldName" and a List parameter called "list". + * The method takes an E type parameter called "valueToFind" and a String parameter called "fieldName" and a List parameter called "list". * The method creates a new array list called "tmpList". - * The method then iterates through the list and gets all of the classes as items. + * The method then iterates through the list and gets all the classes as items. * If it can't find the fields, it will throw an illegal argument exception. * @param valueToFind - The value to find * @param fieldName - The field name @@ -461,7 +460,7 @@ public class Utils { } /** - * A replacement for String.format. Allows for to many parameters or to few + * A replacement for String.format. Allows for to many parameters or too few * Replaces {} in the string in order. * * @param message the message @@ -506,8 +505,8 @@ public class Utils { /** * Use reflection to get the field values - * @param clazz - * @param fieldName + * @param clazz the class to find the field + * @param fieldName the field name * @return field */ private static Field getField(Class clazz, String fieldName) { @@ -551,7 +550,7 @@ public class Utils { * @return map value */ public static T getMapValue(Map map, K key, T defaultValue) { - return map.containsKey(key) ? map.get(key) : defaultValue; + return map.getOrDefault(key, defaultValue); } /** @@ -574,7 +573,7 @@ public class Utils { * For collections checks to see if they are null or empty * for all others just checks if they are null * @param the expected class type of the object - * @param value The value to check + * @param values The value to check * @return true if the value is not valid, false otherwise */ @SafeVarargs @@ -588,7 +587,7 @@ public class Utils { * For collections checks to see if they are not null and not empty * for all others just checks if they are not null * @param the expected class type of the object - * @param value The value to check + * @param values The value to check * @return true if the value is valid, false otherwise */ @SafeVarargs @@ -635,7 +634,7 @@ public class Utils { } /** - * List to set set. + * List to set. * * @param the type parameter * @param valueSet the value set @@ -648,13 +647,12 @@ public class Utils { /** * Creates an array from a collection - * * Public method of type array called "makeArray". * The method takes a Collection object parameter called "collection" and a Class object parameter called "clazz". * The method first checks to see if the Collection object is null. If so, it returns null. * The method then creates an array called "results" and populates it with a new instance of "clazz" and the size of the collection. - * The method then creates a Int variable called "index" and sets the value to zero. - * The method then iterates through the collection and adds all of the items to the results array. + * The method then creates an Int variable called "index" and sets the value to zero. + * The method then iterates through the collection and adds all the items to the results array. * The method then returns the results array. * @param - The type parameter * @param collection - The collection @@ -683,7 +681,7 @@ public class Utils { * The method takes a Collection object parameter called "collection". * The method checks to see if the Collection Object is null. If so, it returns null. * Otherwise, it creates an ArrayList object called "list". - * It then iterates through the Collection Object and adds all of the collection items to that list. + * It then iterates through the Collection Object and adds all the collection items to that list. * The method then returns the list. * @param - The type parameter * @param collection - The collection @@ -693,11 +691,7 @@ public class Utils { if (collection == null) { return null; } - List list = new ArrayList<>(); - for (E item : collection) { - list.add(item); - } - return list; + return new ArrayList<>(collection); } /** @@ -716,13 +710,7 @@ public class Utils { return null; } - List newList = new ArrayList<>(); - - for (E item : array) { - newList.add(item); - } - - return newList; + return List.of(array); } /** @@ -752,11 +740,11 @@ public class Utils { * Public method of type Set called "makeSet". * The method takes an Iterable object parameter called "collection". * The method first creates a new HashSet called "set". - * The method then iterates through the collection and adds all of the items from it to the HashSet. + * The method then iterates through the collection and adds all the items from it to the HashSet. * The method then returns the HashSet. * @param - The type parameter * @param collection - The iterable object name. - * @return - Returns the HashSet with all of the items of the collection inside of it. + * @return - Returns the HashSet with all the items of the collection inside of it. */ public static Set makeSet(Iterable collection) { Set set = new HashSet<>(); @@ -767,7 +755,7 @@ public class Utils { } /** - * Map to list list. + * Map to list. * * @param the type parameter * @param the type parameter @@ -776,17 +764,12 @@ public class Utils { * @return the list */ public static List mapToList(Map map) { - List list = new ArrayList<>(); - for (V key : map.values()) { - list.add(key); - } - - return list; + return new ArrayList<>(map.values()); } /** - * Map to set set. + * Map to set. * * @param the type parameter * @param the type parameter @@ -795,13 +778,8 @@ public class Utils { * @return the set */ public static Set mapToSet(Map map) { - Set list = new HashSet<>(); - for (V key : map.values()) { - list.add(key); - } - - return list; + return new HashSet<>(map.values()); } /** @@ -833,7 +811,7 @@ public class Utils { */ public static Collection safeList(Collection list) { if (!validateValue(list)) { - return new ArrayList(); + return new ArrayList<>(); } return list; } @@ -864,7 +842,7 @@ public class Utils { */ public static Iterable safeList(Iterable list) { if (!validateValue(list)) { - return new ArrayList(); + return new ArrayList<>(); } return list; } @@ -879,7 +857,7 @@ public class Utils { */ public static List safeList(List list) { if (!validateValue(list)) { - return new ArrayList(); + return new ArrayList<>(); } return list; } @@ -892,17 +870,17 @@ public class Utils { */ public static Set safeSet(Set set) { if (set == null) { - return new HashSet(); + return new HashSet<>(); } return set; } /** * Checks to see if a string is not blank or null. - * if its not blank it will return the string + * if it's not blank it will return the string * otherwise it will return an empty string * @param string The string to check - * @return the passed in string if its not null either empty string + * @return the passed in string if it's not null either empty string */ public static String safeString(String string) { return isEmptyString(string) ? "" : string; @@ -917,18 +895,14 @@ public class Utils { * @return the to list */ public static List setToList(Set valueSet) { - List list = new ArrayList<>(); - for (E value : valueSet) { - list.add(value); - } - return list; + return new ArrayList<>(valueSet); } /** * Converts a String into an integer without exception * @param value The string value to convert * @param defaultValue The default value to return if the string cant be converted - * @return the integer representation of the passed in string or the default value if an exception occured + * @return the integer representation of the passed in string or the default value if an exception occurred */ public static Integer toInteger(String value, Integer defaultValue) { try { @@ -952,7 +926,7 @@ public class Utils { } public static List toList(Iterable iterable) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (E item : iterable) { list.add(item); } @@ -969,17 +943,13 @@ public class Utils { */ @SafeVarargs public static Set toSet(E... values) { - Set set = new LinkedHashSet<>(); - for (E value : values) { - set.add(value); - } - return set; + return new LinkedHashSet<>(Arrays.asList(values)); } public static List toByteList(byte[] bytes) { return IntStream.range(0, bytes.length) - .mapToObj(index -> new Byte(bytes[index])) + .mapToObj(index -> bytes[index]) .collect(Collectors.toList()); } @@ -1008,7 +978,7 @@ public class Utils { Optional test = StreamUtils.asStream(iterable) .filter(item -> count.getAndIncrement() == index) .findFirst(); - return test.isPresent() ? test.get() : null; + return test.orElse(null); } public static Consumer handleExceptionWrapper(ThrowingConsumer consumer) { @@ -1026,13 +996,13 @@ public class Utils { * The method takes an Object parameter called "value". * The method loops through and checks to see if value is empty. * If so, it will return that the value is not null and that it is not empty. - * Otherwise it will check to see the value is an instance of Map. + * Otherwise, it will check to see the value is an instance of Map. * If so, it will return that the value is not null and that it is not empty. - * Otherwise it will check to see if value is an instance of a String. + * Otherwise, it will check to see if value is an instance of a String. * If so, it will return that the value is not null and that it is not empty. - * Otherwise it will check to see if value is an instance of a Collection Object. - * If so, it will return that the value is not null and if the value.size is greater than zero. - * Otherwise it will just return that the value is not null and not empty. + * Otherwise, it will check to see if value is an instance of a Collection Object. + * If so, it will return that the value is not null and if the value size is greater than zero. + * Otherwise, it will just return that the value is not null and not empty. * @param - The type parameter * @param value - Value to validate * @return - Returns true if it is valid; false otherwise @@ -1047,25 +1017,21 @@ public class Utils { } else if (value instanceof Map){ return !((Map)value).isEmpty(); } else if (value instanceof Boolean) { - return ((Boolean)value) == true; + return ((Boolean) value); } - else if (!(value instanceof String)) { - return value != null; - } return !value.toString().trim().isEmpty(); } /** * Validates all given values. - * * Public method of type Boolean called "validateValues". * The method takes multiple V type objects called "objectToValidate". * The method creates a boolean type variable called "valid" and sets it to true. * The method then loops through all the objects and validates each value in the object. * The method sets valid equal to the result of true and false. * If the method cannot validate the object values, it will throw an exception. If so, it returns false. - * Otherwise, the method will return the variable called "valid'. + * Otherwise, the method will return the variable called "valid". * @param - The type parameter * @param objectsToValidate - Objects to validate * @return - Returns true if all objects are valid false otherwise. @@ -1084,7 +1050,7 @@ public class Utils { */ @SafeVarargs public static boolean validateValues(boolean or, V... objectsToValidate) { - boolean valid = true; + boolean valid = !or; try { for (Object obj : objectsToValidate) { if (or && validateValue(obj)) { @@ -1103,14 +1069,14 @@ public class Utils { public static boolean isJUnitRunning() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); Optional junit = StreamUtils.asStream(stackTrace) - .map(element -> element.getClassName()) + .map(StackTraceElement::getClassName) .filter(className -> className.startsWith("org.junit.")) .findFirst(); return junit.isPresent(); } private static Set> getWrapperTypes() { - Set> ret = new HashSet>(); + Set> ret = new HashSet<>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); @@ -1122,4 +1088,4 @@ public class Utils { ret.add(String.class); return ret; } -} \ No newline at end of file +} diff --git a/src/test/java/net/locusworks/test/AESEncryptionTest.java b/src/test/java/net/locusworks/test/AESEncryptionTest.java index 794a91d..7854265 100644 --- a/src/test/java/net/locusworks/test/AESEncryptionTest.java +++ b/src/test/java/net/locusworks/test/AESEncryptionTest.java @@ -1,10 +1,10 @@ package net.locusworks.test; -import org.junit.Assert; -import org.junit.Test; - import net.locusworks.common.crypto.AES; import net.locusworks.common.utils.Utils; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class AESEncryptionTest { @@ -12,10 +12,10 @@ public class AESEncryptionTest { public void testEncryption() { try { String encrypted = AES.createInstance().encrypt("hello world"); - Assert.assertTrue(String.format("Encrypted String is not blank? :%s", encrypted), !Utils.isEmptyString(encrypted)); + assertFalse(Utils.isEmptyString(encrypted), String.format("Encrypted String is not blank? :%s", encrypted)); } catch (Exception ex) { ex.printStackTrace(System.err); - Assert.fail(); + fail(); } } @@ -25,16 +25,16 @@ public class AESEncryptionTest { try { AES aes = AES.createInstance(); String encrypted = aes.encrypt(testString); - Assert.assertTrue(String.format("Encrypted String is not blank? :%s", encrypted), !Utils.isEmptyString(encrypted)); + assertFalse(Utils.isEmptyString(encrypted), String.format("Encrypted String is not blank? :%s", encrypted)); String decrypted = aes.decrypt(encrypted); - Assert.assertTrue(String.format("Decrypted String is not blank? :%s", decrypted), !Utils.isEmptyString(encrypted)); - - Assert.assertTrue("Test String and Original String the same? :%s", testString.equals(decrypted)); + assertFalse(Utils.isEmptyString(encrypted), String.format("Decrypted String is not blank? :%s", decrypted)); + + assertEquals(testString, decrypted, "Test String and Original String the same? :%s"); } catch (Exception ex) { ex.printStackTrace(System.err); - Assert.fail(); + fail(); } } diff --git a/src/test/java/net/locusworks/test/AllTests.java b/src/test/java/net/locusworks/test/AllTests.java index 7d9e8e9..0407b5a 100644 --- a/src/test/java/net/locusworks/test/AllTests.java +++ b/src/test/java/net/locusworks/test/AllTests.java @@ -1,11 +1,7 @@ package net.locusworks.test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; +import org.junit.jupiter.api.extension.ExtendWith; -@RunWith(Suite.class) -@SuiteClasses({ AESEncryptionTest.class, FileReaderTest.class, HashSaltTest.class, RandomStringTest.class }) public class AllTests { } diff --git a/src/test/java/net/locusworks/test/FileReaderTest.java b/src/test/java/net/locusworks/test/FileReaderTest.java index 9296da6..b35f4da 100644 --- a/src/test/java/net/locusworks/test/FileReaderTest.java +++ b/src/test/java/net/locusworks/test/FileReaderTest.java @@ -1,6 +1,12 @@ package net.locusworks.test; -import static org.junit.Assert.*; +import net.locusworks.common.interfaces.AutoCloseableIterator; +import net.locusworks.common.utils.FileReader; +import net.locusworks.common.utils.FileReader.LineInfo; +import net.locusworks.common.utils.RandomString; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileOutputStream; @@ -10,26 +16,19 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import net.locusworks.common.interfaces.AutoCloseableIterator; -import net.locusworks.common.utils.FileReader; -import net.locusworks.common.utils.FileReader.LineInfo; -import net.locusworks.common.utils.RandomString; +import static org.junit.jupiter.api.Assertions.assertEquals; public class FileReaderTest { private static final String TEST_FILE = "test_file.txt"; - private static Map numLines = new LinkedHashMap<>(); + private static final Map numLines = new LinkedHashMap<>(); - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { File testFile = new File(TEST_FILE); FileOutputStream fos = new FileOutputStream(testFile); - Integer count = ThreadLocalRandom.current().nextInt(100); + int count = ThreadLocalRandom.current().nextInt(100); for (int i = 1; i <= count; i++) { String randomString = RandomString.getString(ThreadLocalRandom.current().nextInt(5, 100)) + "\n"; @@ -40,7 +39,7 @@ public class FileReaderTest { fos.close(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { File file = new File(TEST_FILE); file.delete(); @@ -48,48 +47,50 @@ public class FileReaderTest { @Test public void testForLoop() { - Integer lineCount = 0; + int lineCount = 0; try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) { for (LineInfo s : fr) { lineCount++; Integer lineNumber = s.getLineNumber(); - Integer lineLength = s.getLine().length(); + int lineLength = s.getLine().length(); Integer mapLineLength = numLines.get(lineNumber); - assertTrue(lineLength == (mapLineLength-1)); + assertEquals(lineLength, (mapLineLength - 1)); } } - assertTrue(lineCount == numLines.size()); + assertEquals(lineCount, numLines.size()); } @Test public void testIterator() { - Integer lineCount = 0; + int lineCount = 0; try(AutoCloseableIterator iter = new FileReader(Paths.get(TEST_FILE))) { while(iter.hasNext()) { lineCount++; LineInfo s = iter.next(); Integer lineNumber = s.getLineNumber(); - Integer lineLength = s.getLine().length(); + int lineLength = s.getLine().length(); Integer mapLineLength = numLines.get(lineNumber); - assertTrue(lineLength == (mapLineLength-1)); + assertEquals(lineLength, (mapLineLength - 1)); } } - assertTrue(lineCount == numLines.size()); + assertEquals(lineCount, numLines.size()); } @Test public void testForIterator() { - Integer lineCount = 0; - for(Iterator iter = new FileReader(Paths.get(TEST_FILE)); iter.hasNext();) { - lineCount++; - LineInfo s = iter.next(); - Integer lineNumber = s.getLineNumber(); - Integer lineLength = s.getLine().length(); - Integer mapLineLength = numLines.get(lineNumber); - assertTrue(lineLength == (mapLineLength-1)); + int lineCount = 0; + try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) { + while (((Iterator) fr).hasNext()) { + lineCount++; + LineInfo s = ((Iterator) fr).next(); + Integer lineNumber = s.getLineNumber(); + int lineLength = s.getLine().length(); + Integer mapLineLength = numLines.get(lineNumber); + assertEquals(lineLength, (mapLineLength - 1)); + } + assertEquals(lineCount, numLines.size()); } - assertTrue(lineCount == numLines.size()); } } diff --git a/src/test/java/net/locusworks/test/HashSaltTest.java b/src/test/java/net/locusworks/test/HashSaltTest.java index 8851ac5..b42681f 100644 --- a/src/test/java/net/locusworks/test/HashSaltTest.java +++ b/src/test/java/net/locusworks/test/HashSaltTest.java @@ -1,22 +1,22 @@ package net.locusworks.test; -import org.junit.Assert; -import org.junit.Test; - import net.locusworks.common.crypto.HashSalt; import net.locusworks.common.utils.Utils; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class HashSaltTest { - private static String samplePassword="Hello World"; + private static final String samplePassword="Hello World"; @Test public void testEncryption() { try { String hashSalt = HashSalt.createHash(samplePassword); - Assert.assertTrue(String.format("Encrypted String is not blank? :%s", hashSalt), !Utils.isEmptyString(hashSalt)); + assertFalse(Utils.isEmptyString(hashSalt), String.format("Encrypted String is not blank? :%s", hashSalt)); } catch(Exception ex) { - Assert.fail(); + fail(); } } @@ -25,9 +25,9 @@ public class HashSaltTest { try { String hashSalt = HashSalt.createHash(samplePassword); boolean decrypted = HashSalt.validatePassword(samplePassword, hashSalt); - Assert.assertTrue("Test String and Original String the same? :%s", decrypted); + assertTrue(decrypted, "Test String and Original String the same? :%s"); } catch(Exception ex) { - Assert.fail(); + fail(); } } diff --git a/src/test/java/net/locusworks/test/HashUtilsTest.java b/src/test/java/net/locusworks/test/HashUtilsTest.java index 1eaad9b..063a4f6 100644 --- a/src/test/java/net/locusworks/test/HashUtilsTest.java +++ b/src/test/java/net/locusworks/test/HashUtilsTest.java @@ -1,11 +1,10 @@ package net.locusworks.test; -import static org.junit.Assert.*; - -import org.apache.commons.codec.digest.DigestUtils; -import org.junit.Test; - import net.locusworks.common.utils.HashUtils; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class HashUtilsTest { @@ -15,24 +14,24 @@ public class HashUtilsTest { public void testMD5() throws Exception { String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes()); String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING); - - assertTrue(digestUtilsMD5.equals(hashUtilsMD5)); + + assertEquals(digestUtilsMD5, hashUtilsMD5); } @Test public void testSHA1() throws Exception { String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes()); String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING); - - assertTrue(digestUtilsMD5.equals(hashUtilsMD5)); + + assertEquals(digestUtilsMD5, hashUtilsMD5); } @Test public void testSHA512() throws Exception { String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes()); String hashUtilsMD5 = HashUtils.hash("SHA-512", TEST_STRING); - - assertTrue(digestUtilsMD5.equals(hashUtilsMD5)); + + assertEquals(digestUtilsMD5, hashUtilsMD5); } } diff --git a/src/test/java/net/locusworks/test/ImmutablesTest.java b/src/test/java/net/locusworks/test/ImmutablesTest.java index d8992a6..4269faa 100644 --- a/src/test/java/net/locusworks/test/ImmutablesTest.java +++ b/src/test/java/net/locusworks/test/ImmutablesTest.java @@ -1,12 +1,12 @@ package net.locusworks.test; -import static org.junit.Assert.*; - -import org.junit.Test; - import net.locusworks.common.immutables.Pair; import net.locusworks.common.immutables.Triplet; import net.locusworks.common.immutables.Unit; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ImmutablesTest { @@ -14,32 +14,32 @@ public class ImmutablesTest { @Test public void testUnit() { Unit unit = new Unit<>("Hello World"); - assertTrue(unit.getValue1().equals("Hello World")); + assertEquals("Hello World", unit.getValue1()); Unit unit2 = new Unit<>(2); - assertTrue(unit2.getValue1().equals(2)); + assertEquals(2, (int) unit2.getValue1()); } @Test public void testPair() { Pair pair1 = new Pair<>("Hello", "World"); - assertTrue(pair1.getValue1().equals("Hello")); - assertTrue(pair1.getValue2().equals("World")); + assertEquals("Hello", pair1.getValue1()); + assertEquals("World", pair1.getValue2()); Pair pair2 = new Pair<>("Foo", 25); - assertTrue(pair2.getValue1().equals("Foo")); - assertTrue(pair2.getValue2().equals(25)); + assertEquals("Foo", pair2.getValue1()); + assertEquals(25, (int) pair2.getValue2()); Pair pair3 = new Pair<>(1, 23); - assertTrue(pair3.getValue1().equals(1)); - assertTrue(pair3.getValue2().equals(23)); + assertEquals(1, (int) pair3.getValue1()); + assertEquals(23, (int) pair3.getValue2()); } @Test public void testTriplet() { Triplet triplet1 = new Triplet<>("Hello", 24, "World"); - assertTrue(triplet1.getValue1().equals("Hello")); - assertTrue(triplet1.getValue2().equals(24)); - assertTrue(triplet1.getValue3().equals("World")); + assertEquals("Hello", triplet1.getValue1()); + assertEquals(24, (int) triplet1.getValue2()); + assertEquals("World", triplet1.getValue3()); } } diff --git a/src/test/java/net/locusworks/test/ObjectMapperHelperTest.java b/src/test/java/net/locusworks/test/ObjectMapperHelperTest.java index e27b861..5c0af39 100644 --- a/src/test/java/net/locusworks/test/ObjectMapperHelperTest.java +++ b/src/test/java/net/locusworks/test/ObjectMapperHelperTest.java @@ -3,20 +3,18 @@ */ package net.locusworks.test; -import static org.junit.Assert.*; - import java.util.List; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - import net.locusworks.common.immutables.Triplet; import net.locusworks.common.objectmapper.ObjectMapperHelper; import net.locusworks.common.utils.Utils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import static net.locusworks.common.utils.Constants.JUNIT_TEST_CHECK; import static net.locusworks.common.utils.Constants.LOG4J_CONFIG_PROPERTY; +import static org.junit.jupiter.api.Assertions.*; /** * Test cases to test ObjectMapperHelper.class @@ -31,14 +29,14 @@ public class ObjectMapperHelperTest { /** * @throws java.lang.Exception exception */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { System.setProperty(LOG4J_CONFIG_PROPERTY, "log4j2-test.xml"); System.setProperty(JUNIT_TEST_CHECK, "true"); test = new Triplet("Hello", 24, "World"); } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { System.clearProperty(LOG4J_CONFIG_PROPERTY); System.clearProperty(JUNIT_TEST_CHECK); @@ -56,8 +54,8 @@ public class ObjectMapperHelperTest { assertTrue(value != null && !value.trim().isEmpty()); Triplet tmp = ObjectMapperHelper.readValue(value, Triplet.class).getResults(); - assertTrue(tmp != null); - assertTrue(tmp.equals(test)); + assertNotNull(tmp); + assertEquals(tmp, test); } @SuppressWarnings("rawtypes") @@ -67,7 +65,7 @@ public class ObjectMapperHelperTest { String value = ObjectMapperHelper.writeValue(htrList).getResults(); assertTrue(value != null && !value.trim().isEmpty()); List tmpList = ObjectMapperHelper.readListValue(value, Triplet.class).getResults(); - assertTrue(tmpList != null && tmpList.size() > 0); + assertTrue(tmpList != null && !tmpList.isEmpty()); } } diff --git a/src/test/java/net/locusworks/test/PropertiesManagerTest.java b/src/test/java/net/locusworks/test/PropertiesManagerTest.java index 0c9f166..698e8ee 100644 --- a/src/test/java/net/locusworks/test/PropertiesManagerTest.java +++ b/src/test/java/net/locusworks/test/PropertiesManagerTest.java @@ -1,17 +1,16 @@ package net.locusworks.test; -import static org.junit.Assert.*; - import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; -import org.junit.AfterClass; -import org.junit.Test; - import net.locusworks.common.configuration.PropertiesManager; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * Test cases for the properties manager class @@ -31,7 +30,7 @@ public class PropertiesManagerTest { USER_EXPIRATION_DAYS("userExpirationDays"), LOG_LEVEL("logLevel"); - private String value; + private final String value; private Configuration(String value) { this.value = value; @@ -51,7 +50,7 @@ public class PropertiesManagerTest { } } - @AfterClass + @AfterAll public static void removeSavedProps() { File tmp = new File(TMP_PROPS); if (tmp.exists()) { @@ -63,7 +62,7 @@ public class PropertiesManagerTest { public void testPropertiesLoad() { try { Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); - assertTrue(props != null); + assertNotNull(props); assertTrue(props.containsKey(Configuration.USER_EXPIRATION_DAYS.toString())); assertTrue(props.containsKey(Configuration.DB_HOST.toString())); assertTrue(props.containsKey(Configuration.DB_PORT.toString())); @@ -78,9 +77,9 @@ public class PropertiesManagerTest { try { Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); Properties tmp = new Properties(); - assertTrue(tmp.keySet().size() == 0); + assertEquals(0, tmp.keySet().size()); PropertiesManager.addConfiguration(tmp, props); - assertTrue(tmp.keySet().size() == ENTRY_SIZE); + assertEquals(ENTRY_SIZE, tmp.keySet().size()); assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString())); assertTrue(tmp.containsKey(Configuration.DB_HOST.toString())); assertTrue(tmp.containsKey(Configuration.DB_PORT.toString())); @@ -95,11 +94,12 @@ public class PropertiesManagerTest { try { Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); Properties tmp = new Properties(); - assertTrue(props.keySet().size() == ENTRY_SIZE); - assertTrue(tmp.keySet().size() == 0); + assert props != null; + assertEquals(ENTRY_SIZE, props.keySet().size()); + assertEquals(0, tmp.keySet().size()); PropertiesManager.removeConfiguration(props, tmp); - assertTrue(props.keySet().size() == 0); - assertTrue(tmp.keySet().size() == 0); + assertEquals(0, props.keySet().size()); + assertEquals(0, tmp.keySet().size()); } catch (IOException e) { fail(e.getMessage()); } @@ -112,7 +112,7 @@ public class PropertiesManagerTest { Path tmpFile = Paths.get(TMP_PROPS); PropertiesManager.saveConfiguration(props, tmpFile, "test propertis"); Properties tmp = PropertiesManager.loadConfiguration(tmpFile); - assertTrue(tmp.keySet().size() == ENTRY_SIZE); + assertEquals(ENTRY_SIZE, tmp.keySet().size()); assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString())); assertTrue(tmp.containsKey(Configuration.DB_HOST.toString())); assertTrue(tmp.containsKey(Configuration.DB_PORT.toString())); diff --git a/src/test/java/net/locusworks/test/RandomStringTest.java b/src/test/java/net/locusworks/test/RandomStringTest.java index 8e411b0..50a32e1 100644 --- a/src/test/java/net/locusworks/test/RandomStringTest.java +++ b/src/test/java/net/locusworks/test/RandomStringTest.java @@ -1,17 +1,16 @@ package net.locusworks.test; -import static org.junit.Assert.*; - -import org.junit.Test; - import net.locusworks.common.utils.RandomString; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class RandomStringTest { @Test public void testStaticBytes() { for (Integer length = 3; length < 50; length++) { - assertTrue(RandomString.getBytes(length).length == length); + assertEquals(RandomString.getBytes(length).length, (int) length); } } @@ -19,7 +18,7 @@ public class RandomStringTest { public void testStaticString() { for (Integer length = 3; length < 50; length++) { String random = RandomString.getString(length); - assertTrue(random.length() == length); + assertEquals(random.length(), (int) length); } } diff --git a/src/test/java/net/locusworks/test/UtilsTest.java b/src/test/java/net/locusworks/test/UtilsTest.java index e16587d..389e0dd 100644 --- a/src/test/java/net/locusworks/test/UtilsTest.java +++ b/src/test/java/net/locusworks/test/UtilsTest.java @@ -1,10 +1,18 @@ package net.locusworks.test; -import static org.junit.Assert.*; - -import org.junit.Test; - import net.locusworks.common.utils.Utils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.ParameterizedTest; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; /** * Test cases for the Utils class @@ -20,6 +28,30 @@ public class UtilsTest { assertTrue(Utils.safeString(null).isEmpty()); assertFalse(Utils.safeString("hello world").isEmpty()); } + + + @Test + public void testAreEqual() { + String val1 = "H"; + String val2 = "H"; + assertTrue(Utils.areEqual(val1, val2)); + + assertThrows(IllegalArgumentException.class, () -> Utils.areEqual("1")); + } + @ParameterizedTest + @MethodSource("areEqualParams") + public void testAreEqualWithParams(List objectList, boolean or, boolean equal) { + assertEquals(equal, Utils.areEqual(or, objectList.toArray())); + } + + static Stream areEqualParams() { + return Stream.of( + Arguments.of(List.of("Hello", "Hello"), false, true), + Arguments.of(List.of("Hello", "World"), false, false), + Arguments.of(List.of("Hello", "World", "Hello"), true, true), + Arguments.of(List.of("Hello", "World", "Fair"), true, false) + ); + } @Test public void testEmptyString() { @@ -32,8 +64,55 @@ public class UtilsTest { @Test public void testToInteger() { - assertTrue(Utils.toInteger("Hello word", 2) == 2); - assertTrue(Utils.toInteger("23", 5023) == 23); + assertEquals(2, (int) Utils.toInteger("Hello word", 2)); + assertEquals(23, (int) Utils.toInteger("23", 5023)); + } + + @ParameterizedTest + @MethodSource("validateValueParams") + public void testValidateValue(V value, boolean valid) { + assertEquals(valid, Utils.validateValue(value)); + } + + static Stream validateValueParams() { + return Stream.of( + Arguments.of(null, false), + Arguments.of(Collections.emptyList(), false), + Arguments.of(Map.of(), false), + Arguments.of(false, false), + Arguments.of("", false), + Arguments.of("Hello", true), + Arguments.of(List.of("Hello"), true), + Arguments.of(Map.of("Hello", "World"), true), + Arguments.of(true, true) + ); + } + + @ParameterizedTest + @MethodSource("areValidParams") + public void testValidateValues(List objects, boolean or, boolean valid) { + assertEquals(valid, Utils.areValid(objects.toArray())); + assertEquals(!valid, Utils.areNotValid(objects.toArray())); + } + + static Stream areValidParams() { + return Stream.of( + Arguments.of(List.of("Hello", List.of("Hello"), Map.of("Hello", "World"), true), false, true), + Arguments.of(List.of(Collections.emptyList(), Map.of(), false), false, false) + ); + } + + @Test + public void testBuildMap() { + Map mymap = Utils.buildMap(TreeMap.class, String.class, String.class, "Hello", "World"); + assertNotNull(mymap); + assertEquals(1, mymap.size()); + assertEquals("World", mymap.get("Hello")); + } + + @Test + public void testIsJunitRunning() { + assertTrue(Utils.isJUnitRunning()); } }