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) { def mvn(args) {
withMaven( withMaven(
maven: 'maven-3.6.1', maven: 'maven-3.9.4',
globalMavenSettingsConfig: 'locusworks-settings' globalMavenSettingsConfig: 'locusworks-settings'
) { ) {
@ -183,4 +183,4 @@ def SetVersion( v ) {
} }
} }
return this return this

104
pom.xml
View File

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

View File

@ -15,11 +15,13 @@ import java.util.Properties;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.locusworks.common.immutables.Pair; import net.locusworks.common.immutables.Pair;
import net.locusworks.common.immutables.Unit;
/** /**
* Properties manager class to help load and read properties * Properties manager class to help load and read properties
* @author Isaac Parenteau * @author Isaac Parenteau
* @version 1.0.0 * @version 2.0.0
* @date 02/15/2018 * @date 09/17/2023
*/ */
public class PropertiesManager { public class PropertiesManager {
/** /**
@ -88,7 +90,8 @@ public class PropertiesManager {
* @return a map containing the results of the values added * @return a map containing the results of the values added
*/ */
public static Map<String, String> addConfiguration(Properties to, Properties from) { public static Map<String, String> addConfiguration(Properties to, Properties from) {
Map<String, String> results = from.entrySet()
return from.entrySet()
.stream() .stream()
.filter(entry -> !to.containsKey(entry.getKey())) .filter(entry -> !to.containsKey(entry.getKey()))
.map(entry -> { .map(entry -> {
@ -97,9 +100,7 @@ public class PropertiesManager {
to.put(key, value); to.put(key, value);
return new Pair<String, String>(key, value); return new Pair<String, String>(key, value);
}) })
.collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2())); .collect(Collectors.toMap(Unit::getValue1, Pair::getValue2));
return results;
} }
/** /**
@ -109,19 +110,17 @@ public class PropertiesManager {
* @return a map containing the results of the values removed * @return a map containing the results of the values removed
*/ */
public static Map<String, String> removeConfiguration(Properties from, Properties comparedTo) { public static Map<String, String> removeConfiguration(Properties from, Properties comparedTo) {
Map<String, String> results = from.keySet()
return from.keySet()
.stream() .stream()
.filter(key -> !comparedTo.containsKey(key)) //only get the items that are not in the comparedTo properties .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)))) .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() .stream()
.map(pair -> { //remove those pairs from the from properties .peek(pair -> { //remove those pairs from the from properties
from.remove(pair.getValue1()); from.remove(pair.getValue1());
return pair;
}) })
.collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2())); //create a map of what was removed .collect(Collectors.toMap(Unit::getValue1, Pair::getValue2));
return results;
} }
/** /**

View File

@ -7,10 +7,7 @@ import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException; import java.security.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64; import java.util.Base64;
import net.locusworks.common.utils.RandomString; import net.locusworks.common.utils.RandomString;
@ -21,7 +18,7 @@ import static net.locusworks.common.Charsets.UTF_8;
/** /**
* AES encryption/decryption class * AES encryption/decryption class
* This class will encrypt/decrypt data. The encryption key is never known. * 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 * the key will remain the same and the encryption/decryption will work. This
* provides and added security. * provides and added security.
* @author Isaac Parenteau * @author Isaac Parenteau
@ -62,7 +59,6 @@ public class AES {
* @param seed Seed to initialize SecureRandom with * @param seed Seed to initialize SecureRandom with
* @return SecureRandom object * @return SecureRandom object
* @throws NoSuchAlgorithmException thrown when algorithm can't be used * @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 { private static SecureRandom getSecureRandom(String seed) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance(ALGORITHM); SecureRandom sr = SecureRandom.getInstance(ALGORITHM);
@ -73,7 +69,7 @@ public class AES {
/** /**
* Initialize the aes engine * Initialize the aes engine
* @param key secret key to use * @param key secret key to use
* @param sr * @param sr the secure random class
*/ */
private void init(final byte[] key, SecureRandom sr) { private void init(final byte[] key, SecureRandom sr) {
try { try {
@ -81,8 +77,7 @@ public class AES {
this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE); this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE);
this.ivParamSpec = new IvParameterSpec(RandomString.getBytes(16, sr)); this.ivParamSpec = new IvParameterSpec(RandomString.getBytes(16, sr));
} catch (Exception ex) { } catch (Exception ex) {
System.err.println(ex); throw new IllegalArgumentException("Unable to initialize encryption:", ex);
throw new IllegalArgumentException("Unable to initalize 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)) { if (this.seed == null || !this.seed.equals(seed)) {
initSecureKey(seed); initSecureKey(seed);
} }
@ -144,9 +139,7 @@ public class AES {
} }
public static AES createInstance(String seed) { public static AES createInstance(String seed) {
AES aes = new AES(); return new AES().withSeed(seed);
aes.setSeed(seed);
return aes;
} }
public static void main(String[] args) throws NoSuchAlgorithmException { public static void main(String[] args) throws NoSuchAlgorithmException {

View File

@ -1,13 +1,14 @@
package net.locusworks.common.crypto; package net.locusworks.common.crypto;
import java.io.Serial;
import java.security.PrivateKey; import java.security.PrivateKey;
import net.locusworks.common.Charsets; import net.locusworks.common.Charsets;
public class AESKey implements PrivateKey { public class AESKey implements PrivateKey {
private static final long serialVersionUID = -8452357427706386362L; @Serial private static final long serialVersionUID = -8452357427706386362L;
private String seed; private final String seed;
public AESKey(String seed) { public AESKey(String seed) {
this.seed = seed; this.seed = seed;

View File

@ -114,7 +114,7 @@ public class KeyFile implements AutoCloseable {
dosh.writeInt(item.length); dosh.writeInt(item.length);
dosh.write(item); 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); IOUtils.writeStringToFile(fileName, data);
} }
break; break;
@ -186,9 +186,9 @@ public class KeyFile implements AutoCloseable {
} }
private static class KeySpecHelper { private static class KeySpecHelper {
private KeySpec keySpec; private final KeySpec keySpec;
private boolean isPrivate; private final boolean isPrivate;
private EncryptionType encryptionType; private final EncryptionType encryptionType;
public KeySpecHelper(KeySpec keySpec, boolean isPrivate, EncryptionType encryptionType) { public KeySpecHelper(KeySpec keySpec, boolean isPrivate, EncryptionType encryptionType) {
super(); 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); checkArguments(SSH_MARKER.equals(marker), "Looking for marker %s but received %s", SSH_MARKER, marker);
BigInteger publicExponent = new BigInteger(readLengthFirst(stream)); BigInteger publicExponent = new BigInteger(readLengthFirst(stream));
BigInteger modulus = new BigInteger(readLengthFirst(stream)); BigInteger modulus = new BigInteger(readLengthFirst(stream));
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent); return new RSAPublicKeySpec(modulus, publicExponent);
return keySpec;
} catch (Exception ex) { } catch (Exception ex) {
throw new InvalidKeySpecException(ex); throw new InvalidKeySpecException(ex);
} }

View File

@ -1,5 +1,7 @@
package net.locusworks.common.exceptions; package net.locusworks.common.exceptions;
import java.io.Serial;
/*** /***
* Custom exception class for the patch repository * Custom exception class for the patch repository
* @author Isaac Parenteau * @author Isaac Parenteau
@ -8,7 +10,7 @@ package net.locusworks.common.exceptions;
public class ApplicationException extends Exception { public class ApplicationException extends Exception {
private final Integer code; private final Integer code;
boolean success = false; boolean success = false;
private static final long serialVersionUID = 1L; @Serial private static final long serialVersionUID = 1L;
public static ApplicationException egregiousServer() { public static ApplicationException egregiousServer() {
return new ApplicationException(9001, "Something went wrong. Please see logs for details"); 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 @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (!(other instanceof Triplet)) return false; if (!(other instanceof Triplet<?, ?, ?> otherTriplet)) return false;
Triplet<?, ?, ?> otherTriplet = (Triplet<?, ?, ?>)other;
return super.equals(otherTriplet) && this.getValue3().equals(otherTriplet.getValue3()); 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 { public interface AutoCloseableIterator<T> extends Iterator<T>, AutoCloseable {
@Override @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) public static void copy(final InputStream input, final Writer output, final Charset inputEncoding)
throws IOException { throws IOException {
final InputStreamReader in = new InputStreamReader(input, inputEncoding.toString()); final InputStreamReader in = new InputStreamReader(input, inputEncoding);
copy(in, output); copy(in, output);
} }

View File

@ -20,7 +20,7 @@ import com.google.gson.GsonBuilder;
*/ */
public class ObjectMapperHelper { public class ObjectMapperHelper {
private static ObjectMapper mapper; private static final ObjectMapper mapper;
static { static {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL); mapper.setSerializationInclusion(Include.NON_NULL);
@ -145,4 +145,4 @@ public class ObjectMapperHelper {
return new ObjectMapperListResults<>(ex); return new ObjectMapperListResults<>(ex);
} }
} }
} }

View File

@ -1,10 +1,11 @@
package net.locusworks.common.properties; package net.locusworks.common.properties;
import java.io.Serial;
import java.util.Properties; import java.util.Properties;
public class ImmutableProperties extends Properties { public class ImmutableProperties extends Properties {
private static final long serialVersionUID = 65942088008978137L; @Serial private static final long serialVersionUID = 65942088008978137L;
public ImmutableProperties() { public ImmutableProperties() {
super(); super();
@ -13,8 +14,8 @@ public class ImmutableProperties extends Properties {
public ImmutableProperties(Properties props) { public ImmutableProperties(Properties props) {
super(); super();
if (props == null || props.isEmpty()) return; if (props == null || props.isEmpty()) return;
props.entrySet().forEach(item -> this.put(item.getKey(), item.getValue())); this.putAll(props);
} }
@Override @Override

View File

@ -24,15 +24,7 @@ package net.locusworks.common.properties;
* *
* *
*/ */
import java.io.IOException; import java.io.*;
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.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
@ -123,7 +115,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
/** /**
* use serialVersionUID from JDK 1.1.X for interoperability * 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 * 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; import net.locusworks.common.Charsets;
public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable{ public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable {
public DataOutputStreamHelper() { public DataOutputStreamHelper() {
this(new ByteArrayOutputStream()); this(new ByteArrayOutputStream());
@ -43,7 +43,7 @@ public class DataOutputStreamHelper extends DataOutputStream implements AutoClos
try { try {
super.out.close(); super.out.close();
super.out = null; super.out = null;
} catch (Exception ex) {} } catch (Exception ignored) {}
} }
} }

View File

@ -1,6 +1,7 @@
package net.locusworks.common.utils; package net.locusworks.common.utils;
import java.io.IOException; import java.io.IOException;
import java.io.Serial;
import java.util.Date; import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator; 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() { public DateTimeStampSerializer() {
this(null); this(null);

View File

@ -9,51 +9,51 @@ import static net.locusworks.common.utils.Checks.checkArguments;
import static net.locusworks.common.utils.Checks.checkNotNull; import static net.locusworks.common.utils.Checks.checkNotNull;
public class Splitter { public class Splitter {
private String splitSeq; private String splitSeq;
private boolean omitEmptyStrings = false; private boolean omitEmptyStrings = false;
private int partition; private int partition;
private int limit; private int limit;
private static Splitter splitter; private static Splitter splitter;
private Splitter(String seq) { private Splitter(String seq) {
this.splitSeq = seq; this.splitSeq = seq;
} }
private Splitter(int partition) { private Splitter(int partition) {
this.partition = partition; this.partition = partition;
} }
public Splitter omitEmptyStrings() { public Splitter omitEmptyStrings() {
this.omitEmptyStrings = true; this.omitEmptyStrings = true;
return this; return this;
} }
public Splitter withLimit(int limit) { public Splitter withLimit(int limit) {
this.limit = limit; this.limit = limit;
return this; return this;
} }
public MapSplitter withKeyValueSeparator(String separator) { public MapSplitter withKeyValueSeparator(String separator) {
checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null"); checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null");
return new MapSplitter(this, separator); return new MapSplitter(this, separator);
} }
public String[] splitToArray(String sentence) { public String[] splitToArray(String sentence) {
List<String> list = split(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) { public List<String> split(String sentence) {
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty"); checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
if (!Utils.isEmptyString(splitSeq)) if (!Utils.isEmptyString(splitSeq))
populateForTrimmer(sentence, list); populateForTrimmer(sentence, list);
else else
populateForFixedWidth(sentence, list); populateForFixedWidth(sentence, list);
return limit > 0 ? list.subList(0, limit) : list; return limit > 0 ? list.subList(0, limit) : list;
} }
@ -66,64 +66,67 @@ public class Splitter {
private void populateForTrimmer(String sentence, List<String> list) { private void populateForTrimmer(String sentence, List<String> list) {
for (String s : sentence.split(splitSeq)) { 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()); list.add(s.trim());
} }
} }
public static Splitter fixedLengthSplit(int partition) { public static Splitter fixedLengthSplit(int partition) {
checkArguments(partition > 0, "Partition has to be greater than 0"); checkArguments(partition > 0, "Partition has to be greater than 0");
splitter = new Splitter(partition); splitter = new Splitter(partition);
return splitter; return splitter;
} }
public static Splitter on(String split) { public static Splitter on(String split) {
checkNotNull(split, "Split value provided was null"); checkNotNull(split, "Split value provided was null");
splitter = new Splitter(split); splitter = new Splitter(split);
return splitter; return splitter;
} }
public static Splitter onNewLine() { public static Splitter onNewLine() {
return on("\\r?\\n"); return on("\\r?\\n");
} }
public static Splitter onSpace() { public static Splitter onSpace() {
return on(" "); return on(" ");
} }
public static class MapSplitter { public static class MapSplitter {
private Splitter splitter; private final Splitter splitter;
private String separator; private String separator;
private boolean skipInvalid = false; private boolean skipInvalid = false;
private MapSplitter(Splitter splitter, String separator) { private MapSplitter(Splitter splitter, String separator) {
checkNotNull(splitter, "Splitter cannot be null"); 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.splitter = splitter;
this.separator = separator; this.separator = separator;
} }
public MapSplitter skipInvalidKeyValues() { public MapSplitter skipInvalidKeyValues() {
this.skipInvalid = true; this.skipInvalid = true;
return this; return this;
} }
public Map<String, String> split(String sentence) { public Map<String, String> split(String sentence) {
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty"); checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
for (String s : splitter.split(sentence)) { for (String s : splitter.split(sentence)) {
String[] keyValue = s.split(separator); String[] keyValue = s.split(separator);
try { try {
checkArguments(keyValue.length == 2, "invalid length found for key value mapping"); checkArguments(keyValue.length == 2, "invalid length found for key value mapping");
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
if (!skipInvalid) throw ex; if (!skipInvalid)
throw ex;
continue; continue;
} }
map.put(keyValue[0], keyValue[1]); map.put(keyValue[0], keyValue[1]);
} }
return map; return map;
} }
} }

View File

@ -2,6 +2,7 @@ package net.locusworks.common.utils;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -47,7 +48,7 @@ public class Utils {
} }
E firstVal = values[0]; E firstVal = values[0];
boolean equal = true; boolean equal = !or;
for (int i = 1; i < values.length; i++) { for (int i = 1; i < values.length; i++) {
if (or) if (or)
@ -100,7 +101,7 @@ public class Utils {
* *
* @param <K> the type parameter * @param <K> the type parameter
* @param <V> 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 mapKey the map key
* @param mapValue the map value * @param mapValue the map value
* @param data The data to place in the map * @param data The data to place in the map
@ -109,9 +110,9 @@ public class Utils {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <K, V> Map<K, V> buildMap(Class<?> mapClass, Class<K> mapKey, Class<V> mapValue, Object... data) { 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 { try {
results = (Map<K, V>) mapClass.newInstance(); results = (Map<K, V>) mapClass.getDeclaredConstructor().newInstance();
} catch (Exception ex) { } catch (Exception ex) {
throw new IllegalArgumentException("Unable to create instance of " + mapClass.getSimpleName()); throw new IllegalArgumentException("Unable to create instance of " + mapClass.getSimpleName());
} }
@ -121,7 +122,7 @@ public class Utils {
} }
Object key = null; Object key = null;
Integer step = -1; int step = -1;
for (Object value : data) { for (Object value : data) {
switch(++step % 2) { switch(++step % 2) {
@ -131,7 +132,7 @@ public class Utils {
} }
if (value instanceof Class) { if (value instanceof Class) {
try { try {
value = ((Class<?>)value).newInstance(); value = ((Class<?>)value).getDeclaredConstructor().newInstance();
} catch (Exception ex) { } catch (Exception ex) {
throw new IllegalArgumentException("Unable to create new instance of " + value); throw new IllegalArgumentException("Unable to create new instance of " + value);
} }
@ -150,7 +151,7 @@ public class Utils {
results.put((K) key, (V) value); results.put((K) key, (V) value);
break; break;
default: 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; return results;
@ -166,10 +167,10 @@ public class Utils {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <V> Set<V> buildSet(Class<?> setClass, Class<V> setValue, Object... data) { public static <V> Set<V> buildSet(Class<?> setClass, Class<V> setValue, Object... data) {
Set<V> results = null; Set<V> results;
try { try {
results = (Set<V>) setClass.newInstance(); results = (Set<V>) setClass.getDeclaredConstructor().newInstance();
} catch (Exception ex) { } catch (Exception ex) {
throw new IllegalArgumentException("Unable to create instance of " + setClass.getSimpleName()); throw new IllegalArgumentException("Unable to create instance of " + setClass.getSimpleName());
} }
@ -192,21 +193,22 @@ public class Utils {
* @return - Returns a HashMap using the data. * @return - Returns a HashMap using the data.
*/ */
public static HashMap<String, String> buildStringHashMap(String... 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 <E> the type parameter
* @param list the list * @param list the list
* *
* @return the list * @return the list
* @throws IllegalAccessException throw when an object in the list cannot be accessed through reflection * @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") @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<>(); List<E> clone = new ArrayList<>();
for (E item : list) { for (E item : list) {
clone.add((E) cloneObject(item)); clone.add((E) cloneObject(item));
@ -221,8 +223,9 @@ public class Utils {
* @throws IllegalAccessException thrown when the filed cannot be access * @throws IllegalAccessException thrown when the filed cannot be access
* @throws InstantiationException Thrown when the object cannot be instantiated * @throws InstantiationException Thrown when the object cannot be instantiated
*/ */
public static Object cloneObject(Object obj) throws InstantiationException, IllegalAccessException { public static Object cloneObject(Object obj)
Object clone = obj.getClass().newInstance(); throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Object clone = obj.getClass().getDeclaredConstructor().newInstance();
for (Field field : obj.getClass().getDeclaredFields()) { for (Field field : obj.getClass().getDeclaredFields()) {
try { try {
field.setAccessible(true); field.setAccessible(true);
@ -241,9 +244,7 @@ public class Utils {
field.set(clone, cloneObject(field.get(obj))); field.set(clone, cloneObject(field.get(obj)));
} }
} }
} catch (NullPointerException ex) { } catch (NullPointerException ignored) { }
continue;
}
} }
return clone; return clone;
} }
@ -329,7 +330,7 @@ public class Utils {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E, K> Set<E> extractFieldToSet(String fieldName, Iterable<K> list) { public static <E, K> Set<E> extractFieldToSet(String fieldName, Iterable<K> list) {
Set<E> newSet = new LinkedHashSet<>(); Set<E> newSet = new LinkedHashSet<>();
Field field = null; Field field;
for (K item : Utils.safeList(list)) { for (K item : Utils.safeList(list)) {
try { try {
field = getField(item.getClass(), fieldName); field = getField(item.getClass(), fieldName);
@ -358,9 +359,9 @@ public class Utils {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> List<E> filterList(String fieldName, Object filter, Iterable<E> list) { 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)) { for (E item : safeList(list)) {
try { try {
@ -384,7 +385,6 @@ public class Utils {
/** /**
* Find a value within the list. * Find a value within the list.
*
* Public method of type E called "findValue". * 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 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. * 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 list - The list to search
* @param <E> - The expected class of item to be found * @param <E> - The expected class of item to be found
* @param <K> - The expected class of the Iterable list * @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" }) @SuppressWarnings({ "unchecked", "unlikely-arg-type" })
@ -422,11 +422,10 @@ public class Utils {
/** /**
* Find values list. * Find values list.
*
* Public method of type List called "findValues". * 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 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. * If it can't find the fields, it will throw an illegal argument exception.
* @param valueToFind - The value to find * @param valueToFind - The value to find
* @param fieldName - The field name * @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. * Replaces {} in the string in order.
* *
* @param message the message * @param message the message
@ -506,8 +505,8 @@ public class Utils {
/** /**
* Use reflection to get the field values * Use reflection to get the field values
* @param clazz * @param clazz the class to find the field
* @param fieldName * @param fieldName the field name
* @return field * @return field
*/ */
private static Field getField(Class<?> clazz, String fieldName) { private static Field getField(Class<?> clazz, String fieldName) {
@ -551,7 +550,7 @@ public class Utils {
* @return map value * @return map value
*/ */
public static <T, K> T getMapValue(Map<K, T> map, K key, T defaultValue) { 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 collections checks to see if they are null or empty
* for all others just checks if they are null * for all others just checks if they are null
* @param <V> the expected class type of the object * @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 * @return true if the value is not valid, false otherwise
*/ */
@SafeVarargs @SafeVarargs
@ -588,7 +587,7 @@ public class Utils {
* For collections checks to see if they are not null and not empty * For collections checks to see if they are not null and not empty
* for all others just checks if they are not null * for all others just checks if they are not null
* @param <V> the expected class type of the object * @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 * @return true if the value is valid, false otherwise
*/ */
@SafeVarargs @SafeVarargs
@ -635,7 +634,7 @@ public class Utils {
} }
/** /**
* List to set set. * List to set.
* *
* @param <E> the type parameter * @param <E> the type parameter
* @param valueSet the value set * @param valueSet the value set
@ -648,13 +647,12 @@ public class Utils {
/** /**
* Creates an array from a collection * Creates an array from a collection
*
* Public method of type array called "makeArray". * 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 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 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 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 creates an 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 iterates through the collection and adds all the items to the results array.
* The method then returns the results array. * The method then returns the results array.
* @param <E> - The type parameter * @param <E> - The type parameter
* @param collection - The collection * @param collection - The collection
@ -683,7 +681,7 @@ public class Utils {
* The method takes a Collection object parameter called "collection". * 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. * The method checks to see if the Collection Object is null. If so, it returns null.
* Otherwise, it creates an ArrayList object called "list". * 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. * The method then returns the list.
* @param <E> - The type parameter * @param <E> - The type parameter
* @param collection - The collection * @param collection - The collection
@ -693,11 +691,7 @@ public class Utils {
if (collection == null) { if (collection == null) {
return null; return null;
} }
List<E> list = new ArrayList<>(); return new ArrayList<>(collection);
for (E item : collection) {
list.add(item);
}
return list;
} }
/** /**
@ -716,13 +710,7 @@ public class Utils {
return null; return null;
} }
List<E> newList = new ArrayList<>(); return List.of(array);
for (E item : array) {
newList.add(item);
}
return newList;
} }
/** /**
@ -752,11 +740,11 @@ public class Utils {
* Public method of type Set called "makeSet". * Public method of type Set called "makeSet".
* The method takes an Iterable object parameter called "collection". * The method takes an Iterable object parameter called "collection".
* The method first creates a new HashSet called "set". * 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. * The method then returns the HashSet.
* @param <E> - The type parameter * @param <E> - The type parameter
* @param collection - The iterable object name. * @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) { public static <E> Set<E> makeSet(Iterable<E> collection) {
Set<E> set = new HashSet<>(); 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 <K> the type parameter
* @param <V> the type parameter * @param <V> the type parameter
@ -776,17 +764,12 @@ public class Utils {
* @return the list * @return the list
*/ */
public static <K, V> List<V> mapToList(Map<K, V> map) { public static <K, V> List<V> mapToList(Map<K, V> map) {
List<V> list = new ArrayList<>();
for (V key : map.values()) { return new ArrayList<>(map.values());
list.add(key);
}
return list;
} }
/** /**
* Map to set set. * Map to set.
* *
* @param <K> the type parameter * @param <K> the type parameter
* @param <V> the type parameter * @param <V> the type parameter
@ -795,13 +778,8 @@ public class Utils {
* @return the set * @return the set
*/ */
public static <K, V> Set<V> mapToSet(Map<K, V> map) { public static <K, V> Set<V> mapToSet(Map<K, V> map) {
Set<V> list = new HashSet<>();
for (V key : map.values()) { return new HashSet<>(map.values());
list.add(key);
}
return list;
} }
/** /**
@ -833,7 +811,7 @@ public class Utils {
*/ */
public static <E> Collection<E> safeList(Collection<E> list) { public static <E> Collection<E> safeList(Collection<E> list) {
if (!validateValue(list)) { if (!validateValue(list)) {
return new ArrayList<E>(); return new ArrayList<>();
} }
return list; return list;
} }
@ -864,7 +842,7 @@ public class Utils {
*/ */
public static <E> Iterable<E> safeList(Iterable<E> list) { public static <E> Iterable<E> safeList(Iterable<E> list) {
if (!validateValue(list)) { if (!validateValue(list)) {
return new ArrayList<E>(); return new ArrayList<>();
} }
return list; return list;
} }
@ -879,7 +857,7 @@ public class Utils {
*/ */
public static <E> List<E> safeList(List<E> list) { public static <E> List<E> safeList(List<E> list) {
if (!validateValue(list)) { if (!validateValue(list)) {
return new ArrayList<E>(); return new ArrayList<>();
} }
return list; return list;
} }
@ -892,17 +870,17 @@ public class Utils {
*/ */
public static <E> Set<E> safeSet(Set<E> set) { public static <E> Set<E> safeSet(Set<E> set) {
if (set == null) { if (set == null) {
return new HashSet<E>(); return new HashSet<>();
} }
return set; return set;
} }
/** /**
* Checks to see if a string is not blank or null. * 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 * otherwise it will return an empty string
* @param string The string to check * @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) { public static String safeString(String string) {
return isEmptyString(string) ? "" : string; return isEmptyString(string) ? "" : string;
@ -917,18 +895,14 @@ public class Utils {
* @return the to list * @return the to list
*/ */
public static <E> List<E> setToList(Set<E> valueSet) { public static <E> List<E> setToList(Set<E> valueSet) {
List<E> list = new ArrayList<>(); return new ArrayList<>(valueSet);
for (E value : valueSet) {
list.add(value);
}
return list;
} }
/** /**
* Converts a String into an integer without exception * Converts a String into an integer without exception
* @param value The string value to convert * @param value The string value to convert
* @param defaultValue The default value to return if the string cant be converted * @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) { public static Integer toInteger(String value, Integer defaultValue) {
try { try {
@ -952,7 +926,7 @@ public class Utils {
} }
public static <E> List<E> toList(Iterable<E> iterable) { public static <E> List<E> toList(Iterable<E> iterable) {
List<E> list = new ArrayList<E>(); List<E> list = new ArrayList<>();
for (E item : iterable) { for (E item : iterable) {
list.add(item); list.add(item);
} }
@ -969,17 +943,13 @@ public class Utils {
*/ */
@SafeVarargs @SafeVarargs
public static <E> Set<E> toSet(E... values) { 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) { public static List<Byte> toByteList(byte[] bytes) {
return IntStream.range(0, bytes.length) return IntStream.range(0, bytes.length)
.mapToObj(index -> new Byte(bytes[index])) .mapToObj(index -> bytes[index])
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@ -1008,7 +978,7 @@ public class Utils {
Optional<E> test = StreamUtils.asStream(iterable) Optional<E> test = StreamUtils.asStream(iterable)
.filter(item -> count.getAndIncrement() == index) .filter(item -> count.getAndIncrement() == index)
.findFirst(); .findFirst();
return test.isPresent() ? test.get() : null; return test.orElse(null);
} }
public static <T, E extends Exception> Consumer<T> handleExceptionWrapper(ThrowingConsumer<T, E> consumer) { 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 takes an Object parameter called "value".
* The method loops through and checks to see if value is empty. * 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. * 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. * 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. * 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. * 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. * 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 just return that the value is not null and not empty.
* @param <V> - The type parameter * @param <V> - The type parameter
* @param value - Value to validate * @param value - Value to validate
* @return - Returns true if it is valid; false otherwise * @return - Returns true if it is valid; false otherwise
@ -1047,25 +1017,21 @@ public class Utils {
} else if (value instanceof Map){ } else if (value instanceof Map){
return !((Map)value).isEmpty(); return !((Map)value).isEmpty();
} else if (value instanceof Boolean) { } 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(); return !value.toString().trim().isEmpty();
} }
/** /**
* Validates all given values. * Validates all given values.
*
* Public method of type Boolean called "validateValues". * Public method of type Boolean called "validateValues".
* The method takes multiple V type objects called "objectToValidate". * 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 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 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. * 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. * 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 <V> - The type parameter
* @param objectsToValidate - Objects to validate * @param objectsToValidate - Objects to validate
* @return - Returns true if all objects are valid false otherwise. * @return - Returns true if all objects are valid false otherwise.
@ -1084,7 +1050,7 @@ public class Utils {
*/ */
@SafeVarargs @SafeVarargs
public static <V> boolean validateValues(boolean or, V... objectsToValidate) { public static <V> boolean validateValues(boolean or, V... objectsToValidate) {
boolean valid = true; boolean valid = !or;
try { try {
for (Object obj : objectsToValidate) { for (Object obj : objectsToValidate) {
if (or && validateValue(obj)) { if (or && validateValue(obj)) {
@ -1103,14 +1069,14 @@ public class Utils {
public static boolean isJUnitRunning() { public static boolean isJUnitRunning() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Optional<String> junit = StreamUtils.asStream(stackTrace) Optional<String> junit = StreamUtils.asStream(stackTrace)
.map(element -> element.getClassName()) .map(StackTraceElement::getClassName)
.filter(className -> className.startsWith("org.junit.")) .filter(className -> className.startsWith("org.junit."))
.findFirst(); .findFirst();
return junit.isPresent(); return junit.isPresent();
} }
private static Set<Class<?>> getWrapperTypes() { private static Set<Class<?>> getWrapperTypes() {
Set<Class<?>> ret = new HashSet<Class<?>>(); Set<Class<?>> ret = new HashSet<>();
ret.add(Boolean.class); ret.add(Boolean.class);
ret.add(Character.class); ret.add(Character.class);
ret.add(Byte.class); ret.add(Byte.class);
@ -1122,4 +1088,4 @@ public class Utils {
ret.add(String.class); ret.add(String.class);
return ret; return ret;
} }
} }

View File

@ -1,10 +1,10 @@
package net.locusworks.test; package net.locusworks.test;
import org.junit.Assert;
import org.junit.Test;
import net.locusworks.common.crypto.AES; import net.locusworks.common.crypto.AES;
import net.locusworks.common.utils.Utils; import net.locusworks.common.utils.Utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class AESEncryptionTest { public class AESEncryptionTest {
@ -12,10 +12,10 @@ public class AESEncryptionTest {
public void testEncryption() { public void testEncryption() {
try { try {
String encrypted = AES.createInstance().encrypt("hello world"); 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) { } catch (Exception ex) {
ex.printStackTrace(System.err); ex.printStackTrace(System.err);
Assert.fail(); fail();
} }
} }
@ -25,16 +25,16 @@ public class AESEncryptionTest {
try { try {
AES aes = AES.createInstance(); AES aes = AES.createInstance();
String encrypted = aes.encrypt(testString); 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); String decrypted = aes.decrypt(encrypted);
Assert.assertTrue(String.format("Decrypted String is not blank? :%s", decrypted), !Utils.isEmptyString(encrypted)); assertFalse(Utils.isEmptyString(encrypted), String.format("Decrypted String is not blank? :%s", decrypted));
Assert.assertTrue("Test String and Original String the same? :%s", testString.equals(decrypted)); assertEquals(testString, decrypted, "Test String and Original String the same? :%s");
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(System.err); ex.printStackTrace(System.err);
Assert.fail(); fail();
} }
} }

View File

@ -1,11 +1,7 @@
package net.locusworks.test; package net.locusworks.test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ AESEncryptionTest.class, FileReaderTest.class, HashSaltTest.class, RandomStringTest.class })
public class AllTests { public class AllTests {
} }

View File

@ -1,6 +1,12 @@
package net.locusworks.test; 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.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -10,26 +16,19 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import org.junit.AfterClass; import static org.junit.jupiter.api.Assertions.assertEquals;
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;
public class FileReaderTest { public class FileReaderTest {
private static final String TEST_FILE = "test_file.txt"; 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 { public static void setUpBeforeClass() throws Exception {
File testFile = new File(TEST_FILE); File testFile = new File(TEST_FILE);
FileOutputStream fos = new FileOutputStream(testFile); FileOutputStream fos = new FileOutputStream(testFile);
Integer count = ThreadLocalRandom.current().nextInt(100); int count = ThreadLocalRandom.current().nextInt(100);
for (int i = 1; i <= count; i++) { for (int i = 1; i <= count; i++) {
String randomString = RandomString.getString(ThreadLocalRandom.current().nextInt(5, 100)) + "\n"; String randomString = RandomString.getString(ThreadLocalRandom.current().nextInt(5, 100)) + "\n";
@ -40,7 +39,7 @@ public class FileReaderTest {
fos.close(); fos.close();
} }
@AfterClass @AfterAll
public static void tearDownAfterClass() throws Exception { public static void tearDownAfterClass() throws Exception {
File file = new File(TEST_FILE); File file = new File(TEST_FILE);
file.delete(); file.delete();
@ -48,48 +47,50 @@ public class FileReaderTest {
@Test @Test
public void testForLoop() { public void testForLoop() {
Integer lineCount = 0; int lineCount = 0;
try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) { try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) {
for (LineInfo s : fr) { for (LineInfo s : fr) {
lineCount++; lineCount++;
Integer lineNumber = s.getLineNumber(); Integer lineNumber = s.getLineNumber();
Integer lineLength = s.getLine().length(); int lineLength = s.getLine().length();
Integer mapLineLength = numLines.get(lineNumber); Integer mapLineLength = numLines.get(lineNumber);
assertTrue(lineLength == (mapLineLength-1)); assertEquals(lineLength, (mapLineLength - 1));
} }
} }
assertTrue(lineCount == numLines.size()); assertEquals(lineCount, numLines.size());
} }
@Test @Test
public void testIterator() { public void testIterator() {
Integer lineCount = 0; int lineCount = 0;
try(AutoCloseableIterator<LineInfo> iter = new FileReader(Paths.get(TEST_FILE))) { try(AutoCloseableIterator<LineInfo> iter = new FileReader(Paths.get(TEST_FILE))) {
while(iter.hasNext()) { while(iter.hasNext()) {
lineCount++; lineCount++;
LineInfo s = iter.next(); LineInfo s = iter.next();
Integer lineNumber = s.getLineNumber(); Integer lineNumber = s.getLineNumber();
Integer lineLength = s.getLine().length(); int lineLength = s.getLine().length();
Integer mapLineLength = numLines.get(lineNumber); Integer mapLineLength = numLines.get(lineNumber);
assertTrue(lineLength == (mapLineLength-1)); assertEquals(lineLength, (mapLineLength - 1));
} }
} }
assertTrue(lineCount == numLines.size()); assertEquals(lineCount, numLines.size());
} }
@Test @Test
public void testForIterator() { public void testForIterator() {
Integer lineCount = 0; int lineCount = 0;
for(Iterator<LineInfo> iter = new FileReader(Paths.get(TEST_FILE)); iter.hasNext();) { try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) {
lineCount++; while (((Iterator<LineInfo>) fr).hasNext()) {
LineInfo s = iter.next(); lineCount++;
Integer lineNumber = s.getLineNumber(); LineInfo s = ((Iterator<LineInfo>) fr).next();
Integer lineLength = s.getLine().length(); Integer lineNumber = s.getLineNumber();
Integer mapLineLength = numLines.get(lineNumber); int lineLength = s.getLine().length();
assertTrue(lineLength == (mapLineLength-1)); 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; package net.locusworks.test;
import org.junit.Assert;
import org.junit.Test;
import net.locusworks.common.crypto.HashSalt; import net.locusworks.common.crypto.HashSalt;
import net.locusworks.common.utils.Utils; import net.locusworks.common.utils.Utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class HashSaltTest { public class HashSaltTest {
private static String samplePassword="Hello World"; private static final String samplePassword="Hello World";
@Test @Test
public void testEncryption() { public void testEncryption() {
try { try {
String hashSalt = HashSalt.createHash(samplePassword); 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) { } catch(Exception ex) {
Assert.fail(); fail();
} }
} }
@ -25,9 +25,9 @@ public class HashSaltTest {
try { try {
String hashSalt = HashSalt.createHash(samplePassword); String hashSalt = HashSalt.createHash(samplePassword);
boolean decrypted = HashSalt.validatePassword(samplePassword, hashSalt); 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) { } catch(Exception ex) {
Assert.fail(); fail();
} }
} }

View File

@ -1,11 +1,10 @@
package net.locusworks.test; 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 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 { public class HashUtilsTest {
@ -15,24 +14,24 @@ public class HashUtilsTest {
public void testMD5() throws Exception { public void testMD5() throws Exception {
String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes()); String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes());
String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING); String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING);
assertTrue(digestUtilsMD5.equals(hashUtilsMD5)); assertEquals(digestUtilsMD5, hashUtilsMD5);
} }
@Test @Test
public void testSHA1() throws Exception { public void testSHA1() throws Exception {
String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes()); String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes());
String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING); String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING);
assertTrue(digestUtilsMD5.equals(hashUtilsMD5)); assertEquals(digestUtilsMD5, hashUtilsMD5);
} }
@Test @Test
public void testSHA512() throws Exception { public void testSHA512() throws Exception {
String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes()); String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes());
String hashUtilsMD5 = HashUtils.hash("SHA-512", TEST_STRING); 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; package net.locusworks.test;
import static org.junit.Assert.*;
import org.junit.Test;
import net.locusworks.common.immutables.Pair; import net.locusworks.common.immutables.Pair;
import net.locusworks.common.immutables.Triplet; import net.locusworks.common.immutables.Triplet;
import net.locusworks.common.immutables.Unit; 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 { public class ImmutablesTest {
@ -14,32 +14,32 @@ public class ImmutablesTest {
@Test @Test
public void testUnit() { public void testUnit() {
Unit<String> unit = new Unit<>("Hello World"); Unit<String> unit = new Unit<>("Hello World");
assertTrue(unit.getValue1().equals("Hello World")); assertEquals("Hello World", unit.getValue1());
Unit<Integer> unit2 = new Unit<>(2); Unit<Integer> unit2 = new Unit<>(2);
assertTrue(unit2.getValue1().equals(2)); assertEquals(2, (int) unit2.getValue1());
} }
@Test @Test
public void testPair() { public void testPair() {
Pair<String, String> pair1 = new Pair<>("Hello", "World"); Pair<String, String> pair1 = new Pair<>("Hello", "World");
assertTrue(pair1.getValue1().equals("Hello")); assertEquals("Hello", pair1.getValue1());
assertTrue(pair1.getValue2().equals("World")); assertEquals("World", pair1.getValue2());
Pair<String, Integer> pair2 = new Pair<>("Foo", 25); Pair<String, Integer> pair2 = new Pair<>("Foo", 25);
assertTrue(pair2.getValue1().equals("Foo")); assertEquals("Foo", pair2.getValue1());
assertTrue(pair2.getValue2().equals(25)); assertEquals(25, (int) pair2.getValue2());
Pair<Integer, Integer> pair3 = new Pair<>(1, 23); Pair<Integer, Integer> pair3 = new Pair<>(1, 23);
assertTrue(pair3.getValue1().equals(1)); assertEquals(1, (int) pair3.getValue1());
assertTrue(pair3.getValue2().equals(23)); assertEquals(23, (int) pair3.getValue2());
} }
@Test @Test
public void testTriplet() { public void testTriplet() {
Triplet<String, Integer, String> triplet1 = new Triplet<>("Hello", 24, "World"); Triplet<String, Integer, String> triplet1 = new Triplet<>("Hello", 24, "World");
assertTrue(triplet1.getValue1().equals("Hello")); assertEquals("Hello", triplet1.getValue1());
assertTrue(triplet1.getValue2().equals(24)); assertEquals(24, (int) triplet1.getValue2());
assertTrue(triplet1.getValue3().equals("World")); assertEquals("World", triplet1.getValue3());
} }
} }

View File

@ -3,20 +3,18 @@
*/ */
package net.locusworks.test; package net.locusworks.test;
import static org.junit.Assert.*;
import java.util.List; 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.immutables.Triplet;
import net.locusworks.common.objectmapper.ObjectMapperHelper; import net.locusworks.common.objectmapper.ObjectMapperHelper;
import net.locusworks.common.utils.Utils; 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.JUNIT_TEST_CHECK;
import static net.locusworks.common.utils.Constants.LOG4J_CONFIG_PROPERTY; import static net.locusworks.common.utils.Constants.LOG4J_CONFIG_PROPERTY;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Test cases to test ObjectMapperHelper.class * Test cases to test ObjectMapperHelper.class
@ -31,14 +29,14 @@ public class ObjectMapperHelperTest {
/** /**
* @throws java.lang.Exception exception * @throws java.lang.Exception exception
*/ */
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
System.setProperty(LOG4J_CONFIG_PROPERTY, "log4j2-test.xml"); System.setProperty(LOG4J_CONFIG_PROPERTY, "log4j2-test.xml");
System.setProperty(JUNIT_TEST_CHECK, "true"); System.setProperty(JUNIT_TEST_CHECK, "true");
test = new Triplet<String, Integer, String>("Hello", 24, "World"); test = new Triplet<String, Integer, String>("Hello", 24, "World");
} }
@AfterClass @AfterAll
public static void tearDownAfterClass() throws Exception { public static void tearDownAfterClass() throws Exception {
System.clearProperty(LOG4J_CONFIG_PROPERTY); System.clearProperty(LOG4J_CONFIG_PROPERTY);
System.clearProperty(JUNIT_TEST_CHECK); System.clearProperty(JUNIT_TEST_CHECK);
@ -56,8 +54,8 @@ public class ObjectMapperHelperTest {
assertTrue(value != null && !value.trim().isEmpty()); assertTrue(value != null && !value.trim().isEmpty());
Triplet<?, ?, ?> tmp = ObjectMapperHelper.readValue(value, Triplet.class).getResults(); Triplet<?, ?, ?> tmp = ObjectMapperHelper.readValue(value, Triplet.class).getResults();
assertTrue(tmp != null); assertNotNull(tmp);
assertTrue(tmp.equals(test)); assertEquals(tmp, test);
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -67,7 +65,7 @@ public class ObjectMapperHelperTest {
String value = ObjectMapperHelper.writeValue(htrList).getResults(); String value = ObjectMapperHelper.writeValue(htrList).getResults();
assertTrue(value != null && !value.trim().isEmpty()); assertTrue(value != null && !value.trim().isEmpty());
List<Triplet> tmpList = ObjectMapperHelper.readListValue(value, Triplet.class).getResults(); 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; package net.locusworks.test;
import static org.junit.Assert.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Properties; import java.util.Properties;
import org.junit.AfterClass;
import org.junit.Test;
import net.locusworks.common.configuration.PropertiesManager; 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 * Test cases for the properties manager class
@ -31,7 +30,7 @@ public class PropertiesManagerTest {
USER_EXPIRATION_DAYS("userExpirationDays"), USER_EXPIRATION_DAYS("userExpirationDays"),
LOG_LEVEL("logLevel"); LOG_LEVEL("logLevel");
private String value; private final String value;
private Configuration(String value) { private Configuration(String value) {
this.value = value; this.value = value;
@ -51,7 +50,7 @@ public class PropertiesManagerTest {
} }
} }
@AfterClass @AfterAll
public static void removeSavedProps() { public static void removeSavedProps() {
File tmp = new File(TMP_PROPS); File tmp = new File(TMP_PROPS);
if (tmp.exists()) { if (tmp.exists()) {
@ -63,7 +62,7 @@ public class PropertiesManagerTest {
public void testPropertiesLoad() { public void testPropertiesLoad() {
try { try {
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); 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.USER_EXPIRATION_DAYS.toString()));
assertTrue(props.containsKey(Configuration.DB_HOST.toString())); assertTrue(props.containsKey(Configuration.DB_HOST.toString()));
assertTrue(props.containsKey(Configuration.DB_PORT.toString())); assertTrue(props.containsKey(Configuration.DB_PORT.toString()));
@ -78,9 +77,9 @@ public class PropertiesManagerTest {
try { try {
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
Properties tmp = new Properties(); Properties tmp = new Properties();
assertTrue(tmp.keySet().size() == 0); assertEquals(0, tmp.keySet().size());
PropertiesManager.addConfiguration(tmp, props); 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.USER_EXPIRATION_DAYS.toString()));
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString())); assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString())); assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));
@ -95,11 +94,12 @@ public class PropertiesManagerTest {
try { try {
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE); Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
Properties tmp = new Properties(); Properties tmp = new Properties();
assertTrue(props.keySet().size() == ENTRY_SIZE); assert props != null;
assertTrue(tmp.keySet().size() == 0); assertEquals(ENTRY_SIZE, props.keySet().size());
assertEquals(0, tmp.keySet().size());
PropertiesManager.removeConfiguration(props, tmp); PropertiesManager.removeConfiguration(props, tmp);
assertTrue(props.keySet().size() == 0); assertEquals(0, props.keySet().size());
assertTrue(tmp.keySet().size() == 0); assertEquals(0, tmp.keySet().size());
} catch (IOException e) { } catch (IOException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
@ -112,7 +112,7 @@ public class PropertiesManagerTest {
Path tmpFile = Paths.get(TMP_PROPS); Path tmpFile = Paths.get(TMP_PROPS);
PropertiesManager.saveConfiguration(props, tmpFile, "test propertis"); PropertiesManager.saveConfiguration(props, tmpFile, "test propertis");
Properties tmp = PropertiesManager.loadConfiguration(tmpFile); 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.USER_EXPIRATION_DAYS.toString()));
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString())); assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString())); assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));

View File

@ -1,17 +1,16 @@
package net.locusworks.test; package net.locusworks.test;
import static org.junit.Assert.*;
import org.junit.Test;
import net.locusworks.common.utils.RandomString; import net.locusworks.common.utils.RandomString;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RandomStringTest { public class RandomStringTest {
@Test @Test
public void testStaticBytes() { public void testStaticBytes() {
for (Integer length = 3; length < 50; length++) { 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() { public void testStaticString() {
for (Integer length = 3; length < 50; length++) { for (Integer length = 3; length < 50; length++) {
String random = RandomString.getString(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; package net.locusworks.test;
import static org.junit.Assert.*;
import org.junit.Test;
import net.locusworks.common.utils.Utils; 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 * Test cases for the Utils class
@ -20,6 +28,30 @@ public class UtilsTest {
assertTrue(Utils.safeString(null).isEmpty()); assertTrue(Utils.safeString(null).isEmpty());
assertFalse(Utils.safeString("hello world").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 @Test
public void testEmptyString() { public void testEmptyString() {
@ -32,8 +64,55 @@ public class UtilsTest {
@Test @Test
public void testToInteger() { public void testToInteger() {
assertTrue(Utils.toInteger("Hello word", 2) == 2); assertEquals(2, (int) Utils.toInteger("Hello word", 2));
assertTrue(Utils.toInteger("23", 5023) == 23); 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());
} }
} }