Compare commits
3 Commits
develop
...
upgrade-jd
Author | SHA1 | Date | |
---|---|---|---|
800cabda34 | |||
3cd7639da1 | |||
587f8bbaf6 |
2
Jenkinsfile
vendored
2
Jenkinsfile
vendored
@ -109,7 +109,7 @@ def getSha1() {
|
||||
|
||||
def mvn(args) {
|
||||
withMaven(
|
||||
maven: 'maven-3.6.1',
|
||||
maven: 'maven-3.9.4',
|
||||
globalMavenSettingsConfig: 'locusworks-settings'
|
||||
) {
|
||||
|
||||
|
96
pom.xml
96
pom.xml
@ -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>
|
||||
<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>
|
||||
|
@ -13,7 +13,7 @@ import java.lang.annotation.Target;
|
||||
* @author Isaac Parenteau
|
||||
*
|
||||
*/
|
||||
@Target({ElementType.FIELD, ElementType.TYPE})
|
||||
@Target({ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MapValue {
|
||||
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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
|
||||
@ -44,15 +41,18 @@ public class AES {
|
||||
|
||||
private String seed;
|
||||
|
||||
private RandomString randomizer;
|
||||
|
||||
private void initSecureKey(String seed) {
|
||||
try {
|
||||
SecureRandom sr = getSecureRandom(seed);
|
||||
KeyGenerator generator = KeyGenerator.getInstance(ENCRYPTION_TYPE);
|
||||
generator.init(128, sr);
|
||||
init(generator.generateKey().getEncoded(), sr);
|
||||
|
||||
randomizer = RandomString.newInstance(sr);
|
||||
init(generator.generateKey().getEncoded());
|
||||
} catch (Exception ex) {
|
||||
System.err.println(ex);
|
||||
throw new IllegalArgumentException("Unable to initalize encryption:", ex);
|
||||
throw new IllegalArgumentException("Unable to initialize encryption:", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,7 +62,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,16 +72,14 @@ public class AES {
|
||||
/**
|
||||
* Initialize the aes engine
|
||||
* @param key secret key to use
|
||||
* @param sr
|
||||
*/
|
||||
private void init(final byte[] key, SecureRandom sr) {
|
||||
private void init(final byte[] key) {
|
||||
try {
|
||||
this.cipher = Cipher.getInstance(ENCRYPTION_ALGORITH, PROVIDER);
|
||||
this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE);
|
||||
this.ivParamSpec = new IvParameterSpec(RandomString.getBytes(16, sr));
|
||||
this.ivParamSpec = new IvParameterSpec(randomizer.getBytes(16));
|
||||
} 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 +119,7 @@ public class AES {
|
||||
}
|
||||
}
|
||||
|
||||
public AES setSeed(String seed) {
|
||||
public AES withSeed(String seed) {
|
||||
if (this.seed == null || !this.seed.equals(seed)) {
|
||||
initSecureKey(seed);
|
||||
}
|
||||
@ -135,7 +132,7 @@ public class AES {
|
||||
}
|
||||
|
||||
public static AES createInstance() {
|
||||
return createInstance(RandomString.getString(16));
|
||||
return createInstance(RandomString.getInstance().getString(16));
|
||||
}
|
||||
|
||||
public static AES createInstance(byte[] byteSeed) {
|
||||
@ -144,9 +141,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 {
|
||||
|
@ -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;
|
||||
|
@ -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();
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -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");
|
||||
|
@ -48,9 +48,7 @@ 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());
|
||||
}
|
||||
|
@ -5,6 +5,6 @@ import java.util.Iterator;
|
||||
public interface AutoCloseableIterator<T> extends Iterator<T>, AutoCloseable {
|
||||
|
||||
@Override
|
||||
public void close();
|
||||
void close();
|
||||
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
|
@ -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);
|
||||
|
@ -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();
|
||||
@ -14,7 +15,7 @@ public class ImmutableProperties extends Properties {
|
||||
super();
|
||||
if (props == null || props.isEmpty()) return;
|
||||
|
||||
props.entrySet().forEach(item -> this.put(item.getKey(), item.getValue()));
|
||||
this.putAll(props);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -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
|
||||
|
@ -1,5 +1,7 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Checks {
|
||||
|
||||
public static void checkArguments(boolean expression, String error) {
|
||||
@ -19,7 +21,7 @@ public class Checks {
|
||||
}
|
||||
|
||||
public static void checkNotNull(Object item, String error) {
|
||||
if (item == null) throw new IllegalAccessError("Provided item is null");
|
||||
Objects.requireNonNull(item, error);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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) {}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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);
|
||||
|
@ -1,5 +1,6 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Objects;
|
||||
import java.util.Random;
|
||||
@ -17,34 +18,30 @@ public class RandomString {
|
||||
private Random random;
|
||||
|
||||
private char[] symbols;
|
||||
private int length;
|
||||
|
||||
private static RandomString instance;
|
||||
|
||||
private RandomString(Integer length) {
|
||||
this(length, new SecureRandom());
|
||||
private RandomString() {
|
||||
Random random;
|
||||
try {
|
||||
random = SecureRandom.getInstance("SHA1PRNG");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
random = new SecureRandom();
|
||||
}
|
||||
init(random);
|
||||
}
|
||||
|
||||
private RandomString(Integer length, Random random) {
|
||||
this(length, random, ALPHA_NUMERIC);
|
||||
private RandomString(Random random) {
|
||||
init(random);
|
||||
}
|
||||
|
||||
private RandomString(Integer length, Random random, String symbols) {
|
||||
if (length < 1) throw new IllegalArgumentException("Length has to be greater than 1");
|
||||
if (symbols.length() < 2) throw new IllegalArgumentException("Symbols need to be greater than 2");
|
||||
this.random = Objects.requireNonNull(random);
|
||||
this.symbols = symbols.toCharArray();
|
||||
private void init(Random random) {
|
||||
this.random = Objects.requireNonNull(random, "Random generator cannot be null");
|
||||
this.symbols = ALPHA_NUMERIC.toCharArray();
|
||||
}
|
||||
|
||||
private synchronized final void setRandom(Random random) {
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
private synchronized final void setLength(int length) {
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
public String nextString() {
|
||||
private String nextString(int length) {
|
||||
if (length < 1) throw new IllegalArgumentException("String Length has to be greater than 0");
|
||||
char[] buffer = new char[length];
|
||||
for (int index = 0; index < buffer.length; index++) {
|
||||
buffer[index] = symbols[random.nextInt(symbols.length)];
|
||||
@ -52,28 +49,28 @@ public class RandomString {
|
||||
return new String(buffer);
|
||||
}
|
||||
|
||||
public static String getString(Integer length) {
|
||||
if (instance == null) {
|
||||
instance = new RandomString(length);
|
||||
}
|
||||
instance.setLength(length);
|
||||
return instance.nextString();
|
||||
public String getString(Integer length) {
|
||||
return this.nextString(length);
|
||||
}
|
||||
|
||||
public static String getString(Integer length, Random random) {
|
||||
if (instance == null) {
|
||||
instance = new RandomString(length);
|
||||
}
|
||||
instance.setLength(length);
|
||||
instance.setRandom(random);
|
||||
return instance.nextString();
|
||||
}
|
||||
|
||||
public static byte[] getBytes(Integer length) {
|
||||
public byte[] getBytes(Integer length) {
|
||||
return getString(length).getBytes(UTF_8);
|
||||
}
|
||||
|
||||
public static byte[] getBytes(Integer length, Random random) {
|
||||
return getString(length, random).getBytes(UTF_8);
|
||||
public static RandomString getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new RandomString();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static RandomString newInstance() {
|
||||
instance = new RandomString();
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static RandomString newInstance(Random random) {
|
||||
instance = new RandomString(random);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
@ -8,56 +8,82 @@ import java.util.Map;
|
||||
import static net.locusworks.common.utils.Checks.checkArguments;
|
||||
import static net.locusworks.common.utils.Checks.checkNotNull;
|
||||
|
||||
/**
|
||||
* Class to help split a string in various ways.
|
||||
* By partition (fixed length split) or by sequence (look for a specific string sequence).
|
||||
* it can also split on new line or not.
|
||||
*/
|
||||
public class Splitter {
|
||||
|
||||
private enum SplitterType {
|
||||
PARTITION,
|
||||
SEQUENCE
|
||||
}
|
||||
private String splitSeq;
|
||||
private boolean omitEmptyStrings = false;
|
||||
private int partition;
|
||||
private int limit;
|
||||
|
||||
private final SplitterType splitterType;
|
||||
private static Splitter splitter;
|
||||
|
||||
private Splitter(String seq) {
|
||||
this.splitSeq = seq;
|
||||
this.splitterType = SplitterType.SEQUENCE;
|
||||
}
|
||||
|
||||
private Splitter(int partition) {
|
||||
this.partition = partition;
|
||||
this.splitterType = SplitterType.PARTITION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove empty string from the resulting lists
|
||||
* @return this
|
||||
*/
|
||||
public Splitter omitEmptyStrings() {
|
||||
this.omitEmptyStrings = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a subset of the resulting list
|
||||
* @param limit how many items to retrieve
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an array instead of a list
|
||||
* @param sentence the string sentence to split
|
||||
* @return this
|
||||
*/
|
||||
public String[] splitToArray(String sentence) {
|
||||
List<String> list = split(sentence);
|
||||
return list.toArray(new String[list.size()]);
|
||||
return list.toArray(new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the string
|
||||
* @param sentence the string to split
|
||||
* @return the resulting list.
|
||||
*/
|
||||
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
|
||||
if (splitterType == SplitterType.PARTITION) {
|
||||
populateForFixedWidth(sentence, list);
|
||||
} else {
|
||||
populateForTrimmer(sentence, list);
|
||||
}
|
||||
|
||||
return limit > 0 ? list.subList(0, limit) : list;
|
||||
}
|
||||
|
||||
private void populateForFixedWidth(String sentence, List<String> list) {
|
||||
checkArguments(partition > 0, "Partition should be greater than 0");
|
||||
int strLength = sentence.length();
|
||||
for (int i = 0; i < strLength; i += partition) {
|
||||
list.add(sentence.substring(i, Math.min(strLength, i + partition)));
|
||||
@ -65,41 +91,69 @@ public class Splitter {
|
||||
}
|
||||
|
||||
private void populateForTrimmer(String sentence, List<String> list) {
|
||||
checkNotNull(splitSeq, "Split value provided was null");
|
||||
for (String s : sentence.split(splitSeq)) {
|
||||
if (s == null || (omitEmptyStrings && s.trim().isEmpty())) continue;
|
||||
if (omitEmptyStrings && s.trim().isEmpty())
|
||||
continue;
|
||||
list.add(s.trim());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the string on fixed length partitions
|
||||
* @param partition the length to split the string on
|
||||
* @return this
|
||||
*/
|
||||
public static Splitter fixedLengthSplit(int partition) {
|
||||
checkArguments(partition > 0, "Partition has to be greater than 0");
|
||||
splitter = new Splitter(partition);
|
||||
return splitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the length on a specified string sequence
|
||||
* @param split the sequence to split
|
||||
* @return this
|
||||
*/
|
||||
public static Splitter on(String split) {
|
||||
checkNotNull(split, "Split value provided was null");
|
||||
splitter = new Splitter(split);
|
||||
return splitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split on new line sequence
|
||||
* @return this
|
||||
*/
|
||||
public static Splitter onNewLine() {
|
||||
return on("\\r?\\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Split on spaces
|
||||
* @return this
|
||||
*/
|
||||
public static Splitter onSpace() {
|
||||
return on(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Separator on what the key value is. return map
|
||||
* @param separator the separator value
|
||||
* @return this
|
||||
*/
|
||||
public MapSplitter withKeyValueSeparator(String separator) {
|
||||
return new MapSplitter(this, separator);
|
||||
}
|
||||
|
||||
public static class MapSplitter {
|
||||
|
||||
private Splitter splitter;
|
||||
private String separator;
|
||||
private final Splitter splitter;
|
||||
private final 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;
|
||||
}
|
||||
@ -118,7 +172,8 @@ public class Splitter {
|
||||
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]);
|
||||
|
@ -2,18 +2,9 @@ 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;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
@ -23,8 +14,6 @@ import java.util.stream.IntStream;
|
||||
import net.locusworks.common.annotations.MapValue;
|
||||
import net.locusworks.common.interfaces.ThrowingConsumer;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/***
|
||||
* Utils class with generic methods
|
||||
* @author Isaac Parenteau
|
||||
@ -47,7 +36,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 +89,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,49 +98,33 @@ 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>();
|
||||
Objects.requireNonNull(mapKey, "Null key value");
|
||||
Objects.requireNonNull(mapValue, "Null map value");
|
||||
|
||||
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());
|
||||
throw new IllegalArgumentException("Unable to create instance of " + mapClass.getSimpleName() + " e: " + ex.getMessage());
|
||||
}
|
||||
|
||||
if (data.length % 2 != 0) {
|
||||
throw new IllegalArgumentException("Odd number of arguments provided");
|
||||
}
|
||||
|
||||
Object key = null;
|
||||
Integer step = -1;
|
||||
for(int i = 0; i < data.length; i+=2) {
|
||||
Object key = data[i];
|
||||
Object value = data[i + 1];
|
||||
|
||||
for (Object value : data) {
|
||||
switch(++step % 2) {
|
||||
case 0:
|
||||
if (mapKey == null) {
|
||||
throw new IllegalArgumentException("Null key value");
|
||||
}
|
||||
if (value instanceof Class) {
|
||||
try {
|
||||
value = ((Class<?>)value).newInstance();
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("Unable to create new instance of " + value);
|
||||
}
|
||||
if (!mapKey.isInstance(key)) {
|
||||
throw new IllegalArgumentException("Key is not the correct instance. Expecting " + mapKey.getName() + " Received " + key.getClass().getName());
|
||||
}
|
||||
|
||||
if (!mapKey.isInstance(value)) {
|
||||
throw new IllegalArgumentException("Key is not the correct instance. Expecting " + mapKey.getName() + " Received " + value.getClass().getName());
|
||||
}
|
||||
|
||||
key = value;
|
||||
continue;
|
||||
case 1:
|
||||
if (!mapValue.isInstance(value)) {
|
||||
throw new IllegalArgumentException("Value is not the correct instance. Expecting " + mapValue.getName() + " Received " + value.getClass().getName());
|
||||
}
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@ -160,28 +133,24 @@ public class Utils {
|
||||
* Builds a set of objects
|
||||
* @param setClass Class type of the set to create
|
||||
* @param setValue Class type of the objects being placed in the set
|
||||
* @param <V> Class type of the return object (should be the same as setValue)
|
||||
* @param <E> Class type of the return object (should be the same as setValue)
|
||||
* @param data Data to place inside the set
|
||||
* @return Set filled with the data
|
||||
* @deprecated since JDk11 can use Set.of
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <V> Set<V> buildSet(Class<?> setClass, Class<V> setValue, Object... data) {
|
||||
Set<V> results = null;
|
||||
|
||||
try {
|
||||
results = (Set<V>) setClass.newInstance();
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalArgumentException("Unable to create instance of " + setClass.getSimpleName());
|
||||
public static <E> Set<E> buildSet(Class<?> setClass, Class<E> setValue, E... data) {
|
||||
return buildSet(data);
|
||||
}
|
||||
|
||||
for (Object value : data) {
|
||||
if (!setValue.isInstance(value)) {
|
||||
throw new IllegalArgumentException("Value is not the correct instance. Expecting " + setValue.getName() + " Received " + value.getClass().getName());
|
||||
}
|
||||
results.add((V) value);
|
||||
}
|
||||
|
||||
return results;
|
||||
/**
|
||||
* Builds a set of objects
|
||||
* @param data the data to set
|
||||
* @return the set
|
||||
* @param <E> the type
|
||||
*/
|
||||
@SafeVarargs public static <E> Set<E> buildSet(E... data) {
|
||||
return Set.of(data);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -192,26 +161,16 @@ 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 and makes it unmodifiable.
|
||||
*
|
||||
* @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
|
||||
* @return unmodifiable list
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> List<E> cloneList(List<E> list) throws InstantiationException, IllegalAccessException {
|
||||
List<E> clone = new ArrayList<>();
|
||||
for (E item : list) {
|
||||
clone.add((E) cloneObject(item));
|
||||
}
|
||||
return clone;
|
||||
public static <E> List<E> cloneList(List<E> list) {
|
||||
return Collections.unmodifiableList(list);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -221,31 +180,25 @@ 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();
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <O> O cloneObject(O obj)
|
||||
throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
Object clone = obj.getClass().getDeclaredConstructor().newInstance();
|
||||
for (Field field : obj.getClass().getDeclaredFields()) {
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
if (field.get(obj) == null || Modifier.isFinal(field.getModifiers())){
|
||||
continue;
|
||||
}
|
||||
if (field.getType().isPrimitive() || field.getType().equals(String.class)
|
||||
|| field.getType().getSuperclass().equals(Number.class)
|
||||
|| field.getType().equals(Boolean.class)){
|
||||
|
||||
Class<?> type = field.getType();
|
||||
|
||||
if (isPrimitiveOrWrapper(type)) {
|
||||
field.set(clone, field.get(obj));
|
||||
} else {
|
||||
Object childObj = field.get(obj);
|
||||
if (childObj == obj) {
|
||||
field.set(clone, clone);
|
||||
} else {
|
||||
field.set(clone, cloneObject(field.get(obj)));
|
||||
}
|
||||
}
|
||||
} catch (NullPointerException ex) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return clone;
|
||||
return (O) clone;
|
||||
}
|
||||
|
||||
/***
|
||||
@ -259,18 +212,17 @@ public class Utils {
|
||||
Class<?> clazz = obj.getClass();
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
|
||||
boolean hasAnnotations = clazz.isAnnotationPresent(MapValue.class);
|
||||
|
||||
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
boolean hasAnnotations = field.isAnnotationPresent(MapValue.class);
|
||||
|
||||
String key = field.getName();
|
||||
Object value = field.get(obj);
|
||||
if (value == null) continue;
|
||||
|
||||
if (hasAnnotations) {
|
||||
if (!field.isAnnotationPresent(MapValue.class)) {
|
||||
continue;
|
||||
}
|
||||
MapValue annotation = field.getDeclaredAnnotation(MapValue.class);
|
||||
if (annotation.ignore()) {
|
||||
continue;
|
||||
@ -302,6 +254,12 @@ public class Utils {
|
||||
return convert;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an object toa string map;
|
||||
* @param obj the object to convert
|
||||
* @return the map
|
||||
* @throws Exception thrown if something happens
|
||||
*/
|
||||
public static Map<String, String> convertToStringMap(Object obj) throws Exception {
|
||||
return convertToStringMap(convertToMap(obj));
|
||||
}
|
||||
@ -314,8 +272,8 @@ public class Utils {
|
||||
* @param <K> The expected class of the Iterable list
|
||||
* @return The converted list
|
||||
*/
|
||||
public static <E, K> List<E> extractFieldToList(String fieldName, Iterable<K> list) {
|
||||
return setToList(extractFieldToSet(fieldName, list));
|
||||
public static <E, K> Set<E> extractFieldToSet(String fieldName, Iterable<K> list) {
|
||||
return listToSet(extractFieldToList(fieldName, list));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -327,10 +285,10 @@ public class Utils {
|
||||
* @return set with the desired items
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E, K> Set<E> extractFieldToSet(String fieldName, Iterable<K> list) {
|
||||
Set<E> newSet = new LinkedHashSet<>();
|
||||
Field field = null;
|
||||
for (K item : Utils.safeList(list)) {
|
||||
public static <E, K> List<E> extractFieldToList(String fieldName, Iterable<K> list) {
|
||||
List<E> newSet = new ArrayList<>();
|
||||
Field field;
|
||||
for (K item : Utils.safeIterable(list)) {
|
||||
try {
|
||||
field = getField(item.getClass(), fieldName);
|
||||
|
||||
@ -358,11 +316,11 @@ 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)) {
|
||||
for (E item : safeIterable(list)) {
|
||||
try {
|
||||
field = getField(item.getClass(), fieldName);
|
||||
|
||||
@ -384,7 +342,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,39 +351,20 @@ 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" })
|
||||
@SuppressWarnings({"unlikely-arg-type" })
|
||||
public static <E, K> E findValue(E itemToFind, String fieldName, List<K> list) {
|
||||
for (K item : Utils.safeList(list)) {
|
||||
try {
|
||||
if (isPrimitiveOrWrapper(item.getClass())) {
|
||||
if (itemToFind.equals(item)) {
|
||||
return (E) item;
|
||||
}
|
||||
} else {
|
||||
Field field = getField(item.getClass(), fieldName);
|
||||
E value = (E) field.get(item);
|
||||
if (itemToFind.equals(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
} catch(IllegalArgumentException | IllegalAccessException e) {
|
||||
throw new IllegalArgumentException(String.format("Unable to find field %s. -> %s", fieldName, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return findValues(itemToFind, fieldName, list).stream().findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@ -435,33 +373,37 @@ public class Utils {
|
||||
* @param <K> - The expected class of the Iterable list
|
||||
* @return - Returns the list.
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked", "unlikely-arg-type" })
|
||||
@SuppressWarnings({"unlikely-arg-type" })
|
||||
public static <E, K> List<E> findValues(E valueToFind, String fieldName, List<K> list) {
|
||||
List<E> tmpList = new ArrayList<>();
|
||||
|
||||
for (K item : Utils.safeList(list)) {
|
||||
try {
|
||||
if (isPrimitiveOrWrapper(item.getClass())) {
|
||||
if (valueToFind.equals(item)) {
|
||||
tmpList.add((E)item);
|
||||
}
|
||||
} else {
|
||||
Field field = getField(item.getClass(), fieldName);
|
||||
E value = (E) field.get(item);
|
||||
if (valueToFind.equals(value)) {
|
||||
tmpList.add(value);
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
throw new IllegalArgumentException(String.format("Unable to find field %s. -> %s", fieldName, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
return tmpList;
|
||||
List<E> extracted = extractFieldToList(fieldName, list);
|
||||
return extracted.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.filter(v -> v.equals(valueToFind)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement for String.format. Allows for to many parameters or to few
|
||||
* Use reflection to get the field values
|
||||
* @param clazz the class to find the field
|
||||
* @param fieldName the field name
|
||||
* @return field
|
||||
*/
|
||||
private static Field getField(Class<?> clazz, String fieldName) {
|
||||
Field field = null;
|
||||
while(clazz != null) {
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
break;
|
||||
} catch(Exception ex) {
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement for String.format. Allows for to many parameters or too few
|
||||
* Replaces {} in the string in order.
|
||||
*
|
||||
* @param message the message
|
||||
@ -504,27 +446,6 @@ public class Utils {
|
||||
return obj == null ? "Unknown" : (verbose ? obj.getClass().getName() : obj.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Use reflection to get the field values
|
||||
* @param clazz
|
||||
* @param fieldName
|
||||
* @return field
|
||||
*/
|
||||
private static Field getField(Class<?> clazz, String fieldName) {
|
||||
Field field = null;
|
||||
while(clazz != null) {
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
break;
|
||||
} catch(Exception ex) {
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value from a map
|
||||
*
|
||||
@ -551,7 +472,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 +495,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 +509,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
|
||||
@ -608,7 +529,7 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a list of items into a map
|
||||
* Converts a list of items into a map.
|
||||
*
|
||||
* @param <K> the type parameter
|
||||
* @param <V> the type parameter
|
||||
@ -626,7 +547,7 @@ public class Utils {
|
||||
Field field = getField(value.getClass(), keyFieldName);
|
||||
K key = (K) field.get(value);
|
||||
map.put(key, value);
|
||||
} catch(IllegalArgumentException | IllegalAccessException e) {
|
||||
} catch(Exception e) {
|
||||
throw new IllegalArgumentException(String.format("Unable to find field %s. -> %s", keyFieldName, e.getMessage()));
|
||||
}
|
||||
}
|
||||
@ -635,7 +556,7 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* List to set set.
|
||||
* List to set.
|
||||
*
|
||||
* @param <E> the type parameter
|
||||
* @param valueSet the value set
|
||||
@ -648,13 +569,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 +603,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 +613,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 +632,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,22 +662,22 @@ 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<>();
|
||||
for (E item : safeList(collection)) {
|
||||
for (E item : safeIterable(collection)) {
|
||||
set.add(item);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map to list list.
|
||||
* Map to list.
|
||||
*
|
||||
* @param <K> the type parameter
|
||||
* @param <V> the type parameter
|
||||
@ -776,17 +686,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 +700,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());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -814,14 +714,25 @@ public class Utils {
|
||||
* @return map with reverse key value pairs
|
||||
*/
|
||||
public static <K,V> Map<K, V> reverseMap(Map<V, K> map) {
|
||||
Map<K, V> reverseMap = new HashMap<>();
|
||||
|
||||
for(Map.Entry<V, K> entry : map.entrySet()) {
|
||||
reverseMap.put(entry.getValue(), entry.getKey());
|
||||
return map.entrySet().stream().collect(Collectors.toMap(Entry::getValue, Entry::getKey));
|
||||
}
|
||||
|
||||
return reverseMap;
|
||||
/**
|
||||
* create safe array e [ ].
|
||||
*
|
||||
* @param <E> the type parameter
|
||||
* @param list the list
|
||||
*
|
||||
* @return the e [ ]
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E[] safeArray(E[] list) {
|
||||
if (!validateValue(list)) {
|
||||
return (E[]) new Object[0];
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a safe list
|
||||
@ -833,26 +744,11 @@ public class Utils {
|
||||
*/
|
||||
public static <E> Collection<E> safeList(Collection<E> list) {
|
||||
if (!validateValue(list)) {
|
||||
return new ArrayList<E>();
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe list e [ ].
|
||||
*
|
||||
* @param <E> the type parameter
|
||||
* @param list the list
|
||||
*
|
||||
* @return the e [ ]
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E[] safeList(E[] list) {
|
||||
if (!validateValue(list)) {
|
||||
return (E[]) new Object[0];
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a safe list
|
||||
@ -862,24 +758,9 @@ public class Utils {
|
||||
*
|
||||
* @return an empty list if list is invalid or the list if its valid
|
||||
*/
|
||||
public static <E> Iterable<E> safeList(Iterable<E> list) {
|
||||
public static <E> Iterable<E> safeIterable(Iterable<E> list) {
|
||||
if (!validateValue(list)) {
|
||||
return new ArrayList<E>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a safe list
|
||||
*
|
||||
* @param <E> the type parameter
|
||||
* @param list The list to check
|
||||
*
|
||||
* @return an empty list if list is invalid or the list if its valid
|
||||
*/
|
||||
public static <E> List<E> safeList(List<E> list) {
|
||||
if (!validateValue(list)) {
|
||||
return new ArrayList<E>();
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@ -892,17 +773,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 +798,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 +829,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 +846,12 @@ 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 +880,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 +898,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,10 +919,7 @@ public class Utils {
|
||||
} else if (value instanceof Map){
|
||||
return !((Map)value).isEmpty();
|
||||
} else if (value instanceof Boolean) {
|
||||
return ((Boolean)value) == true;
|
||||
}
|
||||
else if (!(value instanceof String)) {
|
||||
return value != null;
|
||||
return ((Boolean) value);
|
||||
}
|
||||
|
||||
return !value.toString().trim().isEmpty();
|
||||
@ -1058,21 +927,25 @@ public class Utils {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <V> boolean validateValues(V... objectsToValidate) {
|
||||
return validateValues(false, objectsToValidate);
|
||||
return validateValues(false, toList(objectsToValidate));
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <V> boolean validateValuesOr(V... objectsToValidate) {
|
||||
return validateValues(true, toList(objectsToValidate));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1082,20 +955,14 @@ public class Utils {
|
||||
* @param <V> the expected class type of the objects passed in. All objects need to be of same type
|
||||
* @return true if the values are valid, false otherwise
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <V> boolean validateValues(boolean or, V... objectsToValidate) {
|
||||
boolean valid = true;
|
||||
try {
|
||||
public static <V> boolean validateValues(boolean or, List<V> objectsToValidate) {
|
||||
boolean valid = !or;
|
||||
for (Object obj : objectsToValidate) {
|
||||
if (or && validateValue(obj)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
valid &= validateValue(obj);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
@ -1103,23 +970,23 @@ 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<?>>();
|
||||
ret.add(Boolean.class);
|
||||
ret.add(Character.class);
|
||||
ret.add(Byte.class);
|
||||
ret.add(Short.class);
|
||||
ret.add(Integer.class);
|
||||
ret.add(Long.class);
|
||||
ret.add(Float.class);
|
||||
ret.add(Double.class);
|
||||
ret.add(String.class);
|
||||
return ret;
|
||||
return Set.of(
|
||||
Boolean.class,
|
||||
Character.class,
|
||||
Byte.class,
|
||||
Short.class,
|
||||
Integer.class,
|
||||
Long.class,
|
||||
Float.class,
|
||||
Double.class,
|
||||
String.class
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,233 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
|
||||
import com.fasterxml.jackson.core.*;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.introspect.Annotated;
|
||||
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
|
||||
import com.fasterxml.jackson.databind.ser.impl.WritableObjectId;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DateTimeStampSerializerTest {
|
||||
|
||||
static AtomicLong atomicLong = new AtomicLong(0);
|
||||
|
||||
@Test
|
||||
void testSerializer(){
|
||||
DateTimeStampSerializer serializer = new DateTimeStampSerializer();
|
||||
assertDoesNotThrow(() -> serializer.serialize(new Date(), new MyJsonGenerator(), new MySerializerProvider()));
|
||||
assertTrue(atomicLong.get() > 0);
|
||||
}
|
||||
|
||||
private static class MyJsonGenerator extends JsonGenerator {
|
||||
@Override public JsonGenerator setCodec(ObjectCodec objectCodec) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public ObjectCodec getCodec() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public Version version() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public JsonStreamContext getOutputContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public JsonGenerator enable(Feature feature) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public JsonGenerator disable(Feature feature) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public boolean isEnabled(Feature feature) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override public int getFeatureMask() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override public JsonGenerator setFeatureMask(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public JsonGenerator useDefaultPrettyPrinter() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public void writeStartArray() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeEndArray() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeStartObject() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeEndObject() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeFieldName(String s) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeFieldName(SerializableString serializableString)
|
||||
{
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeString(String s) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeString(char[] chars, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeString(SerializableString serializableString) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRawUTF8String(byte[] bytes, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeUTF8String(byte[] bytes, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRaw(String s) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRaw(String s, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRaw(char[] chars, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRaw(char c) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRawValue(String s) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRawValue(String s, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeRawValue(char[] chars, int i, int i1) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeBinary(Base64Variant base64Variant, byte[] bytes, int i, int i1)
|
||||
{
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public int writeBinary(Base64Variant base64Variant, InputStream inputStream, int i)
|
||||
{
|
||||
fail();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override public void writeNumber(int i) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNumber(long l) {
|
||||
atomicLong.set(l);
|
||||
}
|
||||
|
||||
@Override public void writeNumber(BigInteger bigInteger) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNumber(double v) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNumber(float v) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNumber(BigDecimal bigDecimal) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNumber(String s) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeBoolean(boolean b) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeNull() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeObject(Object o) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void writeTree(TreeNode treeNode) {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public void flush() {
|
||||
fail();
|
||||
}
|
||||
|
||||
@Override public boolean isClosed() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class MySerializerProvider extends SerializerProvider {
|
||||
@Override
|
||||
public WritableObjectId findObjectId(Object o, ObjectIdGenerator<?> objectIdGenerator) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public JsonSerializer<Object> serializerInstance(Annotated annotated, Object o) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public Object includeFilterInstance(BeanPropertyDefinition beanPropertyDefinition,
|
||||
Class<?> aClass) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override public boolean includeFilterSuppressNulls(Object o) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
110
src/test/java/net/locusworks/common/utils/FileReaderTest.java
Normal file
110
src/test/java/net/locusworks/common/utils/FileReaderTest.java
Normal file
@ -0,0 +1,110 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
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 org.mockito.MockedStatic;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
public class FileReaderTest {
|
||||
|
||||
private static final String TEST_FILE = "test_file.txt";
|
||||
private static final Map<Integer, Integer> numLines = new LinkedHashMap<>();
|
||||
|
||||
@BeforeAll
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
File testFile = new File(TEST_FILE);
|
||||
FileOutputStream fos = new FileOutputStream(testFile);
|
||||
|
||||
int count = ThreadLocalRandom.current().nextInt(100);
|
||||
|
||||
for (int i = 1; i <= count; i++) {
|
||||
String randomString = RandomString.getInstance().getString(ThreadLocalRandom.current().nextInt(5, 100)) + "\n";
|
||||
numLines.put(i, randomString.length());
|
||||
fos.write(randomString.getBytes());
|
||||
}
|
||||
|
||||
fos.close();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
File file = new File(TEST_FILE);
|
||||
file.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForLoop() {
|
||||
int lineCount = 0;
|
||||
try (FileReader fr = new FileReader(Paths.get(TEST_FILE))) {
|
||||
for (LineInfo s : fr) {
|
||||
lineCount++;
|
||||
Integer lineNumber = s.getLineNumber();
|
||||
int lineLength = s.getLine().length();
|
||||
Integer mapLineLength = numLines.get(lineNumber);
|
||||
assertEquals(lineLength, (mapLineLength - 1));
|
||||
}
|
||||
}
|
||||
assertEquals(lineCount, numLines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIterator() {
|
||||
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();
|
||||
int lineLength = s.getLine().length();
|
||||
Integer mapLineLength = numLines.get(lineNumber);
|
||||
assertEquals(lineLength, (mapLineLength - 1));
|
||||
}
|
||||
}
|
||||
assertEquals(lineCount, numLines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForIterator() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoAlgorithmException() {
|
||||
try(MockedStatic<SecureRandom> mocked = mockStatic(SecureRandom.class)) {
|
||||
mocked.when(() -> SecureRandom.getInstance(anyString())).thenThrow(NoSuchAlgorithmException.class);
|
||||
assertDoesNotThrow(() -> RandomString.newInstance());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,11 +1,10 @@
|
||||
package net.locusworks.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.junit.Test;
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
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 {
|
||||
|
||||
@ -16,7 +15,7 @@ public class HashUtilsTest {
|
||||
String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes());
|
||||
String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING);
|
||||
|
||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
||||
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -24,7 +23,7 @@ public class HashUtilsTest {
|
||||
String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes());
|
||||
String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING);
|
||||
|
||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
||||
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -32,7 +31,7 @@ public class HashUtilsTest {
|
||||
String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes());
|
||||
String hashUtilsMD5 = HashUtils.hash("SHA-512", TEST_STRING);
|
||||
|
||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
||||
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class RandomStringTest {
|
||||
|
||||
@Test
|
||||
public void testStaticBytes() {
|
||||
for (int length = 3; length < 50; length++) {
|
||||
assertEquals(RandomString.getInstance().getBytes(length).length, length);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticString() {
|
||||
for (int length = 3; length < 50; length++) {
|
||||
String random = RandomString.getInstance().getString(length);
|
||||
assertEquals(random.length(), length);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExceptions() {
|
||||
assertThrows(IllegalArgumentException.class, () -> RandomString.newInstance().getString(0));
|
||||
}
|
||||
|
||||
}
|
81
src/test/java/net/locusworks/common/utils/SplitterTest.java
Normal file
81
src/test/java/net/locusworks/common/utils/SplitterTest.java
Normal file
@ -0,0 +1,81 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SplitterTest {
|
||||
|
||||
@Test
|
||||
void testBasicSplitter() {
|
||||
List<String> split = Splitter.onSpace().split("Hello World");
|
||||
assertNotNull(split);
|
||||
assertEquals(2, split.size());
|
||||
assertEquals("Hello", split.get(0));
|
||||
assertEquals("World", split.get(1));
|
||||
|
||||
split = Splitter.fixedLengthSplit(5).split("HelloWorld");
|
||||
assertNotNull(split);
|
||||
assertEquals(2, split.size());
|
||||
assertEquals("Hello", split.get(0));
|
||||
assertEquals("World", split.get(1));
|
||||
|
||||
split = Splitter.onNewLine().split("Hello\nWorld");
|
||||
assertNotNull(split);
|
||||
assertEquals(2, split.size());
|
||||
assertEquals("Hello", split.get(0));
|
||||
assertEquals("World", split.get(1));
|
||||
|
||||
split = Splitter.onNewLine().split("Hello\r\nWorld");
|
||||
assertNotNull(split);
|
||||
assertEquals(2, split.size());
|
||||
assertEquals("Hello", split.get(0));
|
||||
assertEquals("World", split.get(1));
|
||||
|
||||
String[] array = Splitter.onSpace().splitToArray("Hello World");
|
||||
assertNotNull(array);
|
||||
assertEquals(2, array.length);
|
||||
assertEquals("Hello", array[0]);
|
||||
assertEquals("World", array[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOmitEmptyStringWithLimits() {
|
||||
List<String> split = Splitter.onSpace().split("Hello World");
|
||||
assertEquals(3, split.size());
|
||||
split = Splitter.onSpace().omitEmptyStrings().withLimit(1).split("Hello World");
|
||||
assertNotNull(split);
|
||||
assertEquals(1, split.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExceptions() {
|
||||
assertThrows(IllegalArgumentException.class, () -> Splitter.onSpace().split(""));
|
||||
assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLengthSplit(0).split("Hello World"));
|
||||
assertThrows(NullPointerException.class, () -> Splitter.on(null).split("Hello World"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void testWithKeyValueSeparator() {
|
||||
Map<String, String> map = Splitter.on(";").withKeyValueSeparator("=").split("Hello=World;bubba=hotep");
|
||||
assertEquals(2, map.size());
|
||||
assertEquals("World", map.get("Hello"));
|
||||
assertEquals("hotep", map.get("bubba"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testWithMapSplitterErrors() {
|
||||
assertThrows(IllegalArgumentException.class, () -> Splitter.on(";").withKeyValueSeparator("").split("Hello=;bubba=hotep"));
|
||||
assertThrows(IllegalArgumentException.class, () -> Splitter.on(";").withKeyValueSeparator("=").split("Hello=;bubba=hotep"));
|
||||
assertThrows(IllegalArgumentException.class, () -> Splitter.on(";").withKeyValueSeparator("=").split(null));
|
||||
Map<String, String> map = Splitter.on(";").withKeyValueSeparator("=").skipInvalidKeyValues().split("Hello=;bubba=hotep");
|
||||
assertEquals(1, map.size());
|
||||
assertEquals("hotep", map.get("bubba"));
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StreamUtilsTest {
|
||||
|
||||
@Test
|
||||
void testAsStream() {
|
||||
List<String> list = List.of("Hello", "World");
|
||||
assertEquals(2, StreamUtils.asStream(list).count());
|
||||
assertEquals(2, StreamUtils.asStream(list.iterator()).count());
|
||||
assertEquals(2, StreamUtils.asStream(list.toArray(), false).count());
|
||||
}
|
||||
|
||||
}
|
512
src/test/java/net/locusworks/common/utils/UtilsTest.java
Normal file
512
src/test/java/net/locusworks/common/utils/UtilsTest.java
Normal file
@ -0,0 +1,512 @@
|
||||
package net.locusworks.common.utils;
|
||||
|
||||
import net.locusworks.common.annotations.MapValue;
|
||||
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.lang.reflect.InvocationTargetException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test cases for the Utils class
|
||||
* @author Isaac Parenteau
|
||||
* @since 1.0.0-RELEASE
|
||||
*
|
||||
*/
|
||||
public class UtilsTest {
|
||||
|
||||
@Test
|
||||
public void testSafeString() {
|
||||
assertNotNull(Utils.safeString(null));
|
||||
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() {
|
||||
assertTrue(Utils.isEmptyString(null));
|
||||
assertTrue(Utils.isEmptyString(""));
|
||||
assertTrue(Utils.isEmptyString(" "));
|
||||
assertFalse(Utils.isEmptyString("foo"));
|
||||
assertFalse(Utils.isEmptyString(" bar "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToInteger() {
|
||||
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 testCloneList() {
|
||||
String[] values = new String[]{
|
||||
"Hello",
|
||||
"world"
|
||||
};
|
||||
List<String> cloned = Utils.cloneList(new ArrayList<>(Arrays.stream(values).toList()));
|
||||
assertEquals(2, cloned.size());
|
||||
assertThrows(UnsupportedOperationException.class, () -> cloned.add("asdf"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloneObject()
|
||||
throws InvocationTargetException, InstantiationException, IllegalAccessException,
|
||||
NoSuchMethodException {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field1 = "hi";
|
||||
clazz.field2 = "low";
|
||||
clazz.field3 = "world";
|
||||
|
||||
TestClass clazz3 = new TestClass();
|
||||
clazz3.field1 = "hi";
|
||||
clazz3.field2 = "smash";
|
||||
clazz3.field3 = "world";
|
||||
|
||||
clazz.testClass = clazz3;
|
||||
|
||||
TestClass clazz2 = Utils.cloneObject(clazz);
|
||||
assertNotNull(clazz2);
|
||||
assertEquals(clazz.field1, clazz2.field1);
|
||||
assertEquals(clazz.field2, clazz2.field2);
|
||||
assertEquals(clazz.field3, clazz2.field3);
|
||||
assertEquals(clazz.field5, clazz2.field5);
|
||||
assertEquals(clazz.number, clazz2.number);
|
||||
assertEquals(clazz.aBoolean, clazz2.aBoolean);
|
||||
assertNotNull(clazz2.field4);
|
||||
assertNull(clazz2.nullField);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCovertToMap() throws Exception {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field1 = "hi";
|
||||
clazz.field2 = "low";
|
||||
clazz.field3 = "world";
|
||||
|
||||
TestClass clazz3 = new TestClass();
|
||||
clazz.field1 = "hi";
|
||||
clazz.field2 = "low";
|
||||
clazz.field3 = "world";
|
||||
clazz.testClass = clazz3;
|
||||
|
||||
Map<String, Object> converted = Utils.convertToMap(clazz);
|
||||
|
||||
assertEquals(7, converted.size());
|
||||
assertEquals("hi", converted.get("other_field"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertToStringMap() throws Exception {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field1 = "hi";
|
||||
clazz.field2 = "low";
|
||||
clazz.field3 = "world";
|
||||
Map<String, String> converted = Utils.convertToStringMap(clazz);
|
||||
assertEquals(6, converted.size());
|
||||
assertEquals("hi", converted.get("other_field"));
|
||||
|
||||
converted = Utils.convertToStringMap(converted);
|
||||
assertEquals(6, converted.size());
|
||||
assertEquals("hi", converted.get("other_field"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildStringMap() {
|
||||
Map<String, String> myMap = Utils.buildStringHashMap("hello", "world");
|
||||
assertNotNull(myMap);
|
||||
assertEquals(1, myMap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExtractFieldToList() {
|
||||
List<TestClass> list = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field5 = i;
|
||||
list.add(clazz);
|
||||
}
|
||||
|
||||
List<Integer> extractedList = Utils.extractFieldToList("field5", list);
|
||||
Set<Integer> extractedSet = Utils.extractFieldToSet("field5", list);
|
||||
|
||||
assertEquals(10, extractedList.size());
|
||||
assertEquals(10, extractedSet.size());
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
assertEquals(i, extractedList.get(i));
|
||||
assertTrue(extractedSet.contains(i));
|
||||
}
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.extractFieldToList("fieldName", list));
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.extractFieldToSet("fieldName", list));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testFilterList() {
|
||||
List<TestClass> list = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field5 = i;
|
||||
list.add(clazz);
|
||||
}
|
||||
|
||||
list.get(0).testClass = list.get(1);
|
||||
|
||||
List<TestClass> filteredList = Utils.filterList("field5", 5, list);
|
||||
assertEquals(1, filteredList.size());
|
||||
assertEquals(5, filteredList.get(0).field5);
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.filterList("fieldName", 5, list));
|
||||
|
||||
int value = Utils.findValue(5, "field5", list);
|
||||
assertEquals(5, value);
|
||||
|
||||
TestClass tc = Utils.findValue(list.get(1), "testClass", list);
|
||||
assertNotNull(tc);
|
||||
assertEquals(1, tc.field5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFindValues() {
|
||||
List<TestClass> list = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field5 = i % 2;
|
||||
list.add(clazz);
|
||||
}
|
||||
|
||||
List<Integer> values = Utils.findValues(0, "field5", list);
|
||||
assertEquals(5, values.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildMapExceptions() {
|
||||
Throwable ex = assertThrows(IllegalArgumentException.class, () -> Utils.buildMap(String.class, String.class, String.class, "" ));
|
||||
|
||||
assertNotNull(ex);
|
||||
|
||||
ex = assertThrows(IllegalArgumentException.class, () -> Utils.buildMap(TreeMap.class, String.class, String.class, "Hello"));
|
||||
|
||||
assertEquals("Odd number of arguments provided", ex.getMessage());
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.buildMap(TreeMap.class, String.class, String.class, new Object(), "Hello"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.buildMap(TreeMap.class, String.class, String.class, "Hello", new Object()));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> Utils.buildMap(TreeMap.class, Object.class, String.class, "Hello", new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildSet() {
|
||||
Set<String> myset = Utils.buildSet(HashSet.class, String.class, "Hello", "World");
|
||||
assertNotNull(myset);
|
||||
assertEquals(2, myset.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFormatString() {
|
||||
String formatted = Utils.formatString("{} {}", "Hi", 1);
|
||||
assertEquals("Hi 1", formatted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetClassName() {
|
||||
TestClass tc = new TestClass();
|
||||
assertEquals(tc.getClass().getSimpleName(), Utils.getClassName(tc));
|
||||
assertEquals(tc.getClass().getName(), Utils.getClassName(tc, true));
|
||||
assertEquals("Unknown", Utils.getClassName(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMapValue() {
|
||||
Integer value = Utils.getMapValue(Map.of("hi", 1), "hi");
|
||||
assertEquals(1, value);
|
||||
|
||||
value = Utils.getMapValue(Map.of("hi", 1), "low", 0);
|
||||
|
||||
assertEquals(0, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsNotValid() {
|
||||
assertTrue(Utils.isNotValid(null, null, null));
|
||||
assertFalse(Utils.isNotValid("null", "null", "null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsValid() {
|
||||
assertFalse(Utils.isValid(null, null, null));
|
||||
assertTrue(Utils.isValid("null", "null", "null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testListToMap() {
|
||||
List<TestClass> list = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field5 = i;
|
||||
list.add(clazz);
|
||||
}
|
||||
|
||||
Map<Integer, TestClass> values = Utils.listToMap("field5", list);
|
||||
assertEquals(10, values.size());
|
||||
assertEquals(1, values.get(1).field5);
|
||||
|
||||
assertThrows(Throwable.class, () -> Utils.listToMap("fieldasdf5", list));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMakeArray() {
|
||||
List<TestClass> list = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
TestClass clazz = new TestClass();
|
||||
clazz.field5 = i;
|
||||
list.add(clazz);
|
||||
}
|
||||
|
||||
assertNull(Utils.makeArray(null, String.class));
|
||||
|
||||
TestClass[] array = Utils.makeArray(list, TestClass.class);
|
||||
assertEquals(10, array.length);
|
||||
for(int i = 0; i < 10; i++) {
|
||||
assertEquals(list.get(i), array[i]);
|
||||
}
|
||||
|
||||
assertNull(Utils.makeList((Collection<Object>) null));
|
||||
assertNull(Utils.makeList((Iterable<?>) null));
|
||||
assertNull(Utils.makeList((String[]) null));
|
||||
|
||||
List<TestClass> testList = Utils.makeList(list);
|
||||
for(int i = 0; i < 10; i++) {
|
||||
assertEquals(list.get(i), testList.get(i));
|
||||
}
|
||||
|
||||
TestClassList tcl = new TestClassList();
|
||||
tcl.testClassList = testList;
|
||||
|
||||
List<TestClass> testClassList = Utils.makeList(tcl);
|
||||
for(int i = 0; i < 10; i++) {
|
||||
assertEquals(list.get(i), testClassList.get(i));
|
||||
}
|
||||
|
||||
List<TestClass> testArrayList = Utils.makeList(array);
|
||||
for(int i = 0; i < 10; i++) {
|
||||
assertEquals(list.get(i), testArrayList.get(i));
|
||||
}
|
||||
|
||||
Set<TestClass> testSet = Utils.makeSet(list);
|
||||
assertEquals(10, testSet.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapToList() {
|
||||
List<Integer> values = Utils.mapToList(Map.of("Hello", 1));
|
||||
assertEquals(1, values.size());
|
||||
assertEquals(1, values.get(0));
|
||||
|
||||
Set<Integer> setValues = Utils.mapToSet(Map.of("Hello", 1));
|
||||
assertEquals(1, setValues.size());
|
||||
assertTrue(setValues.contains(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReverseMap() {
|
||||
Map<Integer, String> map = Utils.reverseMap(Map.of("Hello", 1));
|
||||
assertEquals(1, map.size());
|
||||
assertEquals("Hello", map.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSafeList() {
|
||||
assertEquals(0, Utils.safeArray(null).length);
|
||||
assertTrue(Utils.safeList(null).isEmpty());
|
||||
assertFalse(Utils.safeIterable(null).iterator().hasNext());
|
||||
assertTrue(Utils.safeSet(null).isEmpty());
|
||||
|
||||
List<String> list = List.of("Hello", "World");
|
||||
|
||||
String[] stringArray = list.toArray(new String[0]);
|
||||
|
||||
assertEquals(list, Utils.safeList(list));
|
||||
assertEquals(stringArray, Utils.safeArray(stringArray));
|
||||
assertEquals(list, Utils.safeIterable(list));
|
||||
|
||||
Set<String> testSet = Set.of("Hello", "World");
|
||||
|
||||
assertEquals(testSet, Utils.safeSet(testSet));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetToList() {
|
||||
List<String> list = Utils.setToList(Set.of("Hello", "World"));
|
||||
assertEquals(2, list.size());
|
||||
|
||||
list = Utils.toList(Set.of("Hello", "World"));
|
||||
assertEquals(2, list.size());
|
||||
|
||||
Set<String> set = Utils.toSet("Hello", "World");
|
||||
|
||||
assertEquals(2, set.size());
|
||||
|
||||
assertTrue(set.contains("Hello"));
|
||||
assertTrue(set.contains("World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToByteList() {
|
||||
byte[] bytes = new byte[10];
|
||||
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = (byte)i;
|
||||
}
|
||||
|
||||
List<Byte> byteList = Utils.toByteList(bytes);
|
||||
assertEquals(bytes.length, byteList.size());
|
||||
|
||||
for(int i = 0; i < bytes.length; i++) {
|
||||
assertEquals(bytes[i], byteList.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIterableSize() {
|
||||
List<String> stringList = List.of("Hello", "World");
|
||||
assertEquals(stringList.size(), (int)Utils.size(stringList));
|
||||
assertEquals(stringList.get(1), Utils.get(stringList, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExceptionWrapper() {
|
||||
assertThrows(RuntimeException.class, () -> List.of("Hi", "Low").forEach(Utils.handleExceptionWrapper(o -> {
|
||||
throw new Exception("bleh");
|
||||
})));
|
||||
|
||||
AtomicInteger atomicInteger = new AtomicInteger(0);
|
||||
List.of("Hi", "Low").forEach(Utils.handleExceptionWrapper(o -> {
|
||||
atomicInteger.incrementAndGet();
|
||||
}));
|
||||
|
||||
assertEquals(2, atomicInteger.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateValues() {
|
||||
assertTrue(Utils.validateValues("Hello", "World"));
|
||||
assertTrue(Utils.validateValuesOr("Hello", null));
|
||||
assertTrue(Utils.validateValuesOr(null, "Hello"));
|
||||
assertFalse(Utils.validateValuesOr(null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsJunitRunning() {
|
||||
assertTrue(Utils.isJUnitRunning());
|
||||
}
|
||||
|
||||
static class TestClassList implements Iterable<TestClass> {
|
||||
private List<TestClass> testClassList;
|
||||
@Override public Iterator<TestClass> iterator() {
|
||||
return testClassList.iterator();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class TestClass {
|
||||
@MapValue("other_field")
|
||||
private String field1;
|
||||
|
||||
@MapValue(ignore = true)
|
||||
private String field2;
|
||||
|
||||
private String field3;
|
||||
|
||||
private final String field4 = "final";
|
||||
@MapValue
|
||||
private int field5 = 5;
|
||||
|
||||
private Boolean aBoolean = Boolean.valueOf("true");
|
||||
|
||||
private Double number = 1.0d;
|
||||
|
||||
private String nullField = null;
|
||||
|
||||
private TestClass testClass;
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -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));
|
||||
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) {
|
||||
ex.printStackTrace(System.err);
|
||||
Assert.fail();
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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 {
|
||||
|
||||
}
|
||||
|
@ -1,95 +0,0 @@
|
||||
package net.locusworks.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Iterator;
|
||||
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;
|
||||
|
||||
public class FileReaderTest {
|
||||
|
||||
private static final String TEST_FILE = "test_file.txt";
|
||||
private static Map<Integer, Integer> numLines = new LinkedHashMap<>();
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
File testFile = new File(TEST_FILE);
|
||||
FileOutputStream fos = new FileOutputStream(testFile);
|
||||
|
||||
Integer count = ThreadLocalRandom.current().nextInt(100);
|
||||
|
||||
for (int i = 1; i <= count; i++) {
|
||||
String randomString = RandomString.getString(ThreadLocalRandom.current().nextInt(5, 100)) + "\n";
|
||||
numLines.put(i, randomString.length());
|
||||
fos.write(randomString.getBytes());
|
||||
}
|
||||
|
||||
fos.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
File file = new File(TEST_FILE);
|
||||
file.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForLoop() {
|
||||
Integer 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();
|
||||
Integer mapLineLength = numLines.get(lineNumber);
|
||||
assertTrue(lineLength == (mapLineLength-1));
|
||||
}
|
||||
}
|
||||
assertTrue(lineCount == numLines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIterator() {
|
||||
Integer 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();
|
||||
Integer mapLineLength = numLines.get(lineNumber);
|
||||
assertTrue(lineLength == (mapLineLength-1));
|
||||
}
|
||||
}
|
||||
assertTrue(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));
|
||||
}
|
||||
assertTrue(lineCount == numLines.size());
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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()));
|
||||
|
@ -1,26 +0,0 @@
|
||||
package net.locusworks.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import net.locusworks.common.utils.RandomString;
|
||||
|
||||
public class RandomStringTest {
|
||||
|
||||
@Test
|
||||
public void testStaticBytes() {
|
||||
for (Integer length = 3; length < 50; length++) {
|
||||
assertTrue(RandomString.getBytes(length).length == length);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticString() {
|
||||
for (Integer length = 3; length < 50; length++) {
|
||||
String random = RandomString.getString(length);
|
||||
assertTrue(random.length() == length);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
package net.locusworks.test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import net.locusworks.common.utils.Utils;
|
||||
|
||||
/**
|
||||
* Test cases for the Utils class
|
||||
* @author Isaac Parenteau
|
||||
* @since 1.0.0-RELEASE
|
||||
*
|
||||
*/
|
||||
public class UtilsTest {
|
||||
|
||||
@Test
|
||||
public void testSafeString() {
|
||||
assertNotNull(Utils.safeString(null));
|
||||
assertTrue(Utils.safeString(null).isEmpty());
|
||||
assertFalse(Utils.safeString("hello world").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyString() {
|
||||
assertTrue(Utils.isEmptyString(null));
|
||||
assertTrue(Utils.isEmptyString(""));
|
||||
assertTrue(Utils.isEmptyString(" "));
|
||||
assertFalse(Utils.isEmptyString("foo"));
|
||||
assertFalse(Utils.isEmptyString(" bar "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToInteger() {
|
||||
assertTrue(Utils.toInteger("Hello word", 2) == 2);
|
||||
assertTrue(Utils.toInteger("23", 5023) == 23);
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user