Upgrading to use jdk 17

This commit is contained in:
2023-09-17 22:15:12 -05:00
parent 09f3bbbc74
commit 587f8bbaf6
28 changed files with 414 additions and 331 deletions

4
Jenkinsfile vendored
View File

@ -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
return this

104
pom.xml
View File

@ -18,11 +18,11 @@
</scm>
<properties>
<log4j.version>2.14.1</log4j.version>
<slf4j.version>1.7.32</slf4j.version>
<jackson.version>2.12.5</jackson.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<log4j.version>2.20.0</log4j.version>
<slf4j.version>2.0.9</slf4j.version>
<jackson.version>2.15.2</jackson.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<nexus.repo>https://nexus.locusworks.net</nexus.repo>
</properties>
@ -31,28 +31,27 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<forkMode>always</forkMode>
</configuration>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.11.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<failOnError>true</failOnError>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>--add-exports</arg>
<arg>java.base/sun.security.jca=ALL-UNNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>6.3.1</version>
<version>8.4.0</version>
<executions>
<execution>
<goals>
@ -61,20 +60,77 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.10</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>1.00</minimum>
</limit>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>1.00</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>7.15.0</version>
<version>9.22.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
@ -103,14 +159,14 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
<version>4.5.14</version>
</dependency>
<!-- Jackson -->
@ -133,7 +189,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
<version>2.10.1</version>
</dependency>
</dependencies>
@ -176,4 +232,4 @@
</pluginRepository>
</pluginRepositories>
</project>
</project>

View File

@ -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<String, String> addConfiguration(Properties to, Properties from) {
Map<String, String> 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<String, String>(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<String, String> removeConfiguration(Properties from, Properties comparedTo) {
Map<String, String> 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, String>(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));
}
/**

View File

@ -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 {

View File

@ -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;

View File

@ -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();

View File

@ -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);
}

View File

@ -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");

View File

@ -48,10 +48,8 @@ public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
@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());
}
}
}

View File

@ -5,6 +5,6 @@ import java.util.Iterator;
public interface AutoCloseableIterator<T> extends Iterator<T>, AutoCloseable {
@Override
public void close();
void close();
}

View File

@ -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);
}

View File

@ -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);
}
}
}
}

View File

@ -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

View File

@ -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<Object,Object> {
/**
* 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

View File

@ -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) {}
}
}

View File

@ -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<Date> {
/**
*
*/
private static final long serialVersionUID = -4753139740916300831L;
@Serial private static final long serialVersionUID = -4753139740916300831L;
public DateTimeStampSerializer() {
this(null);

View File

@ -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<String> list = split(sentence);
return list.toArray(new String[list.size()]);
return list.toArray(new String[0]);
}
public List<String> split(String sentence) {
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
List<String> 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<String> 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<String, String> split(String sentence) {
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
Map<String, String> 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;
}
}

View File

@ -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 <K> the type parameter
* @param <V> 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 <K, V> Map<K, V> buildMap(Class<?> mapClass, Class<K> mapKey, Class<V> mapValue, Object... data) {
Map<K, V> results = new LinkedHashMap<K, V>();
Map<K, V> results;
try {
results = (Map<K, V>) mapClass.newInstance();
results = (Map<K, V>) 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 <V> Set<V> buildSet(Class<?> setClass, Class<V> setValue, Object... data) {
Set<V> results = null;
Set<V> results;
try {
results = (Set<V>) setClass.newInstance();
results = (Set<V>) 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<String, String> buildStringHashMap(String... data) {
return new HashMap<String, String>(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 <E> 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 <E> List<E> cloneList(List<E> list) throws InstantiationException, IllegalAccessException {
public static <E> List<E> cloneList(List<E> list)
throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
List<E> 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 <E, K> Set<E> extractFieldToSet(String fieldName, Iterable<K> list) {
Set<E> 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 <E> List<E> filterList(String fieldName, Object filter, Iterable<E> list) {
List<E> newList = new ArrayList<E>();
List<E> 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 <E> - The expected class of item to be found
* @param <K> - 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, K> T getMapValue(Map<K, T> 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 <V> 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 <V> 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 <E> 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 <E> - 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 <E> - The type parameter
* @param collection - The collection
@ -693,11 +691,7 @@ public class Utils {
if (collection == null) {
return null;
}
List<E> 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<E> 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 <E> - 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 <E> Set<E> makeSet(Iterable<E> collection) {
Set<E> set = new HashSet<>();
@ -767,7 +755,7 @@ public class Utils {
}
/**
* Map to list list.
* Map to list.
*
* @param <K> the type parameter
* @param <V> the type parameter
@ -776,17 +764,12 @@ public class Utils {
* @return the list
*/
public static <K, V> List<V> mapToList(Map<K, V> map) {
List<V> 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 <K> the type parameter
* @param <V> the type parameter
@ -795,13 +778,8 @@ public class Utils {
* @return the set
*/
public static <K, V> Set<V> mapToSet(Map<K, V> map) {
Set<V> 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 <E> Collection<E> safeList(Collection<E> list) {
if (!validateValue(list)) {
return new ArrayList<E>();
return new ArrayList<>();
}
return list;
}
@ -864,7 +842,7 @@ public class Utils {
*/
public static <E> Iterable<E> safeList(Iterable<E> list) {
if (!validateValue(list)) {
return new ArrayList<E>();
return new ArrayList<>();
}
return list;
}
@ -879,7 +857,7 @@ public class Utils {
*/
public static <E> List<E> safeList(List<E> list) {
if (!validateValue(list)) {
return new ArrayList<E>();
return new ArrayList<>();
}
return list;
}
@ -892,17 +870,17 @@ public class Utils {
*/
public static <E> Set<E> safeSet(Set<E> set) {
if (set == null) {
return new HashSet<E>();
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 <E> List<E> setToList(Set<E> valueSet) {
List<E> 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 <E> List<E> toList(Iterable<E> iterable) {
List<E> list = new ArrayList<E>();
List<E> list = new ArrayList<>();
for (E item : iterable) {
list.add(item);
}
@ -969,17 +943,13 @@ public class Utils {
*/
@SafeVarargs
public static <E> Set<E> toSet(E... values) {
Set<E> set = new LinkedHashSet<>();
for (E value : values) {
set.add(value);
}
return set;
return new LinkedHashSet<>(Arrays.asList(values));
}
public static List<Byte> 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<E> test = StreamUtils.asStream(iterable)
.filter(item -> count.getAndIncrement() == index)
.findFirst();
return test.isPresent() ? test.get() : null;
return test.orElse(null);
}
public static <T, E extends Exception> Consumer<T> handleExceptionWrapper(ThrowingConsumer<T, E> 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 <V> - 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 <V> - 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 <V> 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<String> junit = StreamUtils.asStream(stackTrace)
.map(element -> element.getClassName())
.map(StackTraceElement::getClassName)
.filter(className -> className.startsWith("org.junit."))
.findFirst();
return junit.isPresent();
}
private static Set<Class<?>> getWrapperTypes() {
Set<Class<?>> ret = new HashSet<Class<?>>();
Set<Class<?>> 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;
}
}
}

View File

@ -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();
}
}

View File

@ -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 {
}

View File

@ -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<Integer, Integer> numLines = new LinkedHashMap<>();
private static final Map<Integer, Integer> 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<LineInfo> 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<LineInfo> 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<LineInfo>) fr).hasNext()) {
lineCount++;
LineInfo s = ((Iterator<LineInfo>) 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());
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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<String> unit = new Unit<>("Hello World");
assertTrue(unit.getValue1().equals("Hello World"));
assertEquals("Hello World", unit.getValue1());
Unit<Integer> unit2 = new Unit<>(2);
assertTrue(unit2.getValue1().equals(2));
assertEquals(2, (int) unit2.getValue1());
}
@Test
public void testPair() {
Pair<String, String> pair1 = new Pair<>("Hello", "World");
assertTrue(pair1.getValue1().equals("Hello"));
assertTrue(pair1.getValue2().equals("World"));
assertEquals("Hello", pair1.getValue1());
assertEquals("World", pair1.getValue2());
Pair<String, Integer> 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<Integer, Integer> 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<String, Integer, String> 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());
}
}

View File

@ -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<String, Integer, String>("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<Triplet> tmpList = ObjectMapperHelper.readListValue(value, Triplet.class).getResults();
assertTrue(tmpList != null && tmpList.size() > 0);
assertTrue(tmpList != null && !tmpList.isEmpty());
}
}

View File

@ -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()));

View File

@ -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);
}
}

View File

@ -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<Object> objectList, boolean or, boolean equal) {
assertEquals(equal, Utils.areEqual(or, objectList.toArray()));
}
static Stream<Arguments> 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 <V> void testValidateValue(V value, boolean valid) {
assertEquals(valid, Utils.validateValue(value));
}
static Stream<Arguments> 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<Object> objects, boolean or, boolean valid) {
assertEquals(valid, Utils.areValid(objects.toArray()));
assertEquals(!valid, Utils.areNotValid(objects.toArray()));
}
static Stream<Arguments> 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<String, String> 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());
}
}