Compare commits
5 Commits
1.1-RELEAS
...
2.0-RELEAS
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ec9bead93 | |||
| 61efd0eaec | |||
| 800cabda34 | |||
| 3cd7639da1 | |||
| 587f8bbaf6 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -12,3 +12,6 @@
|
|||||||
**/*.iml
|
**/*.iml
|
||||||
**/git.properties
|
**/git.properties
|
||||||
.metadata/
|
.metadata/
|
||||||
|
id_rsa*
|
||||||
|
named*
|
||||||
|
short*
|
||||||
|
|||||||
2
Jenkinsfile
vendored
2
Jenkinsfile
vendored
@@ -109,7 +109,7 @@ def getSha1() {
|
|||||||
|
|
||||||
def mvn(args) {
|
def mvn(args) {
|
||||||
withMaven(
|
withMaven(
|
||||||
maven: 'maven-3.6.1',
|
maven: 'maven-3.9.4',
|
||||||
globalMavenSettingsConfig: 'locusworks-settings'
|
globalMavenSettingsConfig: 'locusworks-settings'
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
|||||||
115
pom.xml
115
pom.xml
@@ -18,11 +18,11 @@
|
|||||||
</scm>
|
</scm>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<log4j.version>2.14.1</log4j.version>
|
<log4j.version>2.26.1</log4j.version>
|
||||||
<slf4j.version>1.7.32</slf4j.version>
|
<slf4j.version>2.0.18</slf4j.version>
|
||||||
<jackson.version>2.12.5</jackson.version>
|
<jackson.version>2.22.1</jackson.version>
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>21</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>21</maven.compiler.target>
|
||||||
<nexus.repo>https://nexus.locusworks.net</nexus.repo>
|
<nexus.repo>https://nexus.locusworks.net</nexus.repo>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
@@ -31,28 +31,37 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.0.0-M5</version>
|
<version>3.5.6</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<forkMode>always</forkMode>
|
<argLine>@{argLine} --add-exports java.base/sun.security.jca=ALL-UNNAMED</argLine>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.8.1</version>
|
<version>3.15.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>${maven.compiler.source}</source>
|
<source>${maven.compiler.source}</source>
|
||||||
<target>${maven.compiler.target}</target>
|
<target>${maven.compiler.target}</target>
|
||||||
<failOnError>true</failOnError>
|
<failOnError>true</failOnError>
|
||||||
<compilerArgs>
|
<compilerArgs>
|
||||||
<arg>-Xlint:all</arg>
|
<arg>-Xlint:all</arg>
|
||||||
|
<arg>--add-exports</arg>
|
||||||
|
<arg>java.base/sun.security.jca=ALL-UNNAMED</arg>
|
||||||
</compilerArgs>
|
</compilerArgs>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.owasp</groupId>
|
<groupId>org.owasp</groupId>
|
||||||
<artifactId>dependency-check-maven</artifactId>
|
<artifactId>dependency-check-maven</artifactId>
|
||||||
<version>6.3.1</version>
|
<version>12.2.2</version>
|
||||||
|
<configuration>
|
||||||
|
<skipProvidedScope>true</skipProvidedScope>
|
||||||
|
<skipTestScope>true</skipTestScope>
|
||||||
|
<failOnError>true</failOnError>
|
||||||
|
<versionCheckEnabled>true</versionCheckEnabled>
|
||||||
|
<nvdApiKey>e2eb1036-9b5b-4df9-95e7-0888be947011</nvdApiKey>
|
||||||
|
</configuration>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
@@ -61,20 +70,85 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.jacoco</groupId>
|
||||||
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
|
<version>0.8.15</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>jacoco-check</id>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<rules>
|
||||||
|
<rule>
|
||||||
|
<element>PACKAGE</element>
|
||||||
|
<limits>
|
||||||
|
<limit>
|
||||||
|
<counter>LINE</counter>
|
||||||
|
<value>COVEREDRATIO</value>
|
||||||
|
<minimum>1.00</minimum>
|
||||||
|
</limit>
|
||||||
|
<limit>
|
||||||
|
<counter>BRANCH</counter>
|
||||||
|
<value>COVEREDRATIO</value>
|
||||||
|
<minimum>1.00</minimum>
|
||||||
|
</limit>
|
||||||
|
</limits>
|
||||||
|
</rule>
|
||||||
|
</rules>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<!-- Source: https://mvnrepository.com/artifact/commons-codec/commons-codec -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>commons-codec</artifactId>
|
||||||
<version>4.13.2</version>
|
<version>1.22.0</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>6.1.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
|
<version>6.1.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<version>5.23.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.flywaydb</groupId>
|
<groupId>org.flywaydb</groupId>
|
||||||
<artifactId>flyway-core</artifactId>
|
<artifactId>flyway-core</artifactId>
|
||||||
<version>7.15.0</version>
|
<version>12.10.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
@@ -103,14 +177,9 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||||
<artifactId>httpclient</artifactId>
|
<artifactId>httpclient5</artifactId>
|
||||||
<version>4.5.13</version>
|
<version>5.6.2</version>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>httpmime</artifactId>
|
|
||||||
<version>4.5.13</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Jackson -->
|
<!-- Jackson -->
|
||||||
@@ -122,7 +191,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-annotations</artifactId>
|
<artifactId>jackson-annotations</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>2.22</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
@@ -133,7 +202,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.8.8</version>
|
<version>2.14.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import java.nio.charset.Charset;
|
|||||||
*
|
*
|
||||||
* <p>See the Guava User Guide article on <a
|
* <p>See the Guava User Guide article on <a
|
||||||
* href="https://github.com/google/guava/wiki/StringsExplained#charsets">{@code Charsets}</a>.
|
* href="https://github.com/google/guava/wiki/StringsExplained#charsets">{@code Charsets}</a>.
|
||||||
*
|
* <p>
|
||||||
* Please do not add new Charset references to this class, unless those character encodings are
|
* Please do not add new Charset references to this class, unless those character encodings are
|
||||||
* part of the set required to be supported by all Java platform implementations! Any Charsets
|
* part of the set required to be supported by all Java platform implementations! Any Charsets
|
||||||
* initialized here may cause unexpected delays when this class is loaded. See the Charset
|
* initialized here may cause unexpected delays when this class is loaded. See the Charset
|
||||||
@@ -32,7 +32,8 @@ import java.nio.charset.Charset;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public final class Charsets {
|
public final class Charsets {
|
||||||
private Charsets() {}
|
private Charsets() {
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* US-ASCII: seven-bit ASCII, the Basic Latin block of the Unicode character set (ISO646-US).
|
* US-ASCII: seven-bit ASCII, the Basic Latin block of the Unicode character set (ISO646-US).
|
||||||
|
|||||||
@@ -10,10 +10,11 @@ import java.lang.annotation.Target;
|
|||||||
* This is at the field level and will map the
|
* This is at the field level and will map the
|
||||||
* filed name as the key and the field value as the value
|
* filed name as the key and the field value as the value
|
||||||
* in the map
|
* in the map
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
@Target({ElementType.FIELD, ElementType.TYPE})
|
@Target({ElementType.FIELD})
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface MapValue {
|
public @interface MapValue {
|
||||||
|
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ public class ConfigurationManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Save the configuration values to file
|
* Save the configuration values to file
|
||||||
|
*
|
||||||
* @param confs Configuration property values to save
|
* @param confs Configuration property values to save
|
||||||
* @throws Exception general exception
|
* @throws Exception general exception
|
||||||
*/
|
*/
|
||||||
@@ -97,6 +98,7 @@ public class ConfigurationManager {
|
|||||||
public String getPropertyValue(String key) {
|
public String getPropertyValue(String key) {
|
||||||
return getPropertyValue(key, null);
|
return getPropertyValue(key, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPropertyValue(String key, String defaultValue) {
|
public String getPropertyValue(String key, String defaultValue) {
|
||||||
return configuration.containsKey(key) ? configuration.getProperty(key) : defaultValue;
|
return configuration.containsKey(key) ? configuration.getProperty(key) : defaultValue;
|
||||||
}
|
}
|
||||||
@@ -128,7 +130,9 @@ public class ConfigurationManager {
|
|||||||
|
|
||||||
//Check to see if the old value changed
|
//Check to see if the old value changed
|
||||||
String oldValue = props.getProperty(fieldName);
|
String oldValue = props.getProperty(fieldName);
|
||||||
if (Utils.isNotValid(oldValue, fieldValue) || oldValue.equals(fieldValue)) { continue; }
|
if (Utils.isNotValid(oldValue, fieldValue) || oldValue.equals(fieldValue)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
|
|||||||
@@ -15,15 +15,19 @@ import java.util.Properties;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import net.locusworks.common.immutables.Pair;
|
import net.locusworks.common.immutables.Pair;
|
||||||
|
import net.locusworks.common.immutables.Unit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Properties manager class to help load and read properties
|
* Properties manager class to help load and read properties
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 2.0.0
|
||||||
* @date 02/15/2018
|
* @date 09/17/2023
|
||||||
*/
|
*/
|
||||||
public class PropertiesManager {
|
public class PropertiesManager {
|
||||||
/**
|
/**
|
||||||
* Load a configuration from resource
|
* Load a configuration from a resource
|
||||||
|
*
|
||||||
* @param clazz class loader
|
* @param clazz class loader
|
||||||
* @param src source of the file
|
* @param src source of the file
|
||||||
* @return properties
|
* @return properties
|
||||||
@@ -44,6 +48,7 @@ public class PropertiesManager {
|
|||||||
/**
|
/**
|
||||||
* Load configuration from a file. This method has been deprecated and may be removed in
|
* Load configuration from a file. This method has been deprecated and may be removed in
|
||||||
* future released. Please use java.nio.Path
|
* future released. Please use java.nio.Path
|
||||||
|
*
|
||||||
* @param file File to load
|
* @param file File to load
|
||||||
* @return properties
|
* @return properties
|
||||||
* @throws IOException Exception thrown the file can't be read
|
* @throws IOException Exception thrown the file can't be read
|
||||||
@@ -55,6 +60,7 @@ public class PropertiesManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Load configuration from a file.
|
* Load configuration from a file.
|
||||||
|
*
|
||||||
* @param path the path to the file
|
* @param path the path to the file
|
||||||
* @return properties
|
* @return properties
|
||||||
* @throws IOException Exception thrown the file can't be read
|
* @throws IOException Exception thrown the file can't be read
|
||||||
@@ -64,13 +70,14 @@ public class PropertiesManager {
|
|||||||
return new Properties();
|
return new Properties();
|
||||||
}
|
}
|
||||||
|
|
||||||
try(BufferedReader br = Files.newBufferedReader(path)) {
|
try (BufferedReader br = Files.newBufferedReader(path)) {
|
||||||
return loadConfiguration(br);
|
return loadConfiguration(br);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load configuration from a buffered reader
|
* Load configuration from a buffered reader
|
||||||
|
*
|
||||||
* @param reader Buffered reader to read the properties values from
|
* @param reader Buffered reader to read the properties values from
|
||||||
* @return properties
|
* @return properties
|
||||||
* @throws IOException Exception thrown the file can't be read
|
* @throws IOException Exception thrown the file can't be read
|
||||||
@@ -83,12 +90,14 @@ public class PropertiesManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Add configurations from one properties file to another
|
* Add configurations from one properties file to another
|
||||||
|
*
|
||||||
* @param to Properties file to copy values to
|
* @param to Properties file to copy values to
|
||||||
* @param from Properties file to copy values from
|
* @param from Properties file to copy values from
|
||||||
* @return a map containing the results of the values added
|
* @return a map containing the results of the values added
|
||||||
*/
|
*/
|
||||||
public static Map<String, String> addConfiguration(Properties to, Properties from) {
|
public static Map<String, String> addConfiguration(Properties to, Properties from) {
|
||||||
Map<String, String> results = from.entrySet()
|
|
||||||
|
return from.entrySet()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(entry -> !to.containsKey(entry.getKey()))
|
.filter(entry -> !to.containsKey(entry.getKey()))
|
||||||
.map(entry -> {
|
.map(entry -> {
|
||||||
@@ -97,36 +106,34 @@ public class PropertiesManager {
|
|||||||
to.put(key, value);
|
to.put(key, value);
|
||||||
return new Pair<String, String>(key, value);
|
return new Pair<String, String>(key, value);
|
||||||
})
|
})
|
||||||
.collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2()));
|
.collect(Collectors.toMap(Unit::getValue1, Pair::getValue2));
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes configuration values that are not present in the comparedTo
|
* Removes configuration values that are not present in the comparedTo
|
||||||
|
*
|
||||||
* @param from Properties file to remove values from
|
* @param from Properties file to remove values from
|
||||||
* @param comparedTo Properties file to compare to
|
* @param comparedTo Properties file to compare to
|
||||||
* @return a map containing the results of the values removed
|
* @return a map containing the results of the values removed
|
||||||
*/
|
*/
|
||||||
public static Map<String, String> removeConfiguration(Properties from, Properties comparedTo) {
|
public static Map<String, String> removeConfiguration(Properties from, Properties comparedTo) {
|
||||||
Map<String, String> results = from.keySet()
|
|
||||||
|
return from.keySet()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(key -> !comparedTo.containsKey(key)) //only get the items that are not in the comparedTo properties
|
.filter(key -> !comparedTo.containsKey(key)) //only get the items that are not in the comparedTo properties
|
||||||
.map(key -> new Pair<String, String>(String.valueOf(key), String.valueOf(from.get(key))))
|
.map(key -> new Pair<String, String>(String.valueOf(key), String.valueOf(from.get(key))))
|
||||||
.collect(Collectors.toList()) //Create a list of paired items (key value) of the items that were filtered
|
.toList() //Create a list of paired items (key value) of the items that were filtered
|
||||||
.stream()
|
.stream()
|
||||||
.map(pair -> { //remove those pairs from the from properties
|
.peek(pair -> { //remove those pairs from the from properties
|
||||||
from.remove(pair.getValue1());
|
from.remove(pair.getValue1());
|
||||||
return pair;
|
|
||||||
})
|
})
|
||||||
.collect(Collectors.toMap(key -> key.getValue1(), value -> value.getValue2())); //create a map of what was removed
|
.collect(Collectors.toMap(Unit::getValue1, Pair::getValue2));
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>Save the properties file to disk.</p>
|
* <p>Save the properties file to disk.</p>
|
||||||
* <p><b>This method has been depecreated and could be removed in future release.<br/>Please use java.nio.Path</b></p>
|
* <p><b>This method has been depecreated and could be removed in future release.<br/>Please use java.nio.Path</b></p>
|
||||||
|
*
|
||||||
* @param props Properties file to save
|
* @param props Properties file to save
|
||||||
* @param fileToSave File to save to
|
* @param fileToSave File to save to
|
||||||
* @param comment Any comments to add
|
* @param comment Any comments to add
|
||||||
@@ -139,12 +146,13 @@ public class PropertiesManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>Save the properties file to disk.</p>
|
* <p>Save the properties file to disk.</p>
|
||||||
|
*
|
||||||
* @param props Properties file to save
|
* @param props Properties file to save
|
||||||
* @param fileToSave File to save to
|
* @param fileToSave File to save to
|
||||||
* @param comment Any comments to add
|
* @param comment Any comments to add
|
||||||
*/
|
*/
|
||||||
public static void saveConfiguration(Properties props, Path fileToSave, String comment) {
|
public static void saveConfiguration(Properties props, Path fileToSave, String comment) {
|
||||||
try(OutputStream fos = Files.newOutputStream(fileToSave)) {
|
try (OutputStream fos = Files.newOutputStream(fileToSave)) {
|
||||||
props.store(fos, comment == null ? "" : comment);
|
props.store(fos, comment == null ? "" : comment);
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
throw new RuntimeException(ex.getMessage(), ex);
|
throw new RuntimeException(ex.getMessage(), ex);
|
||||||
|
|||||||
@@ -7,23 +7,22 @@ import javax.crypto.KeyGenerator;
|
|||||||
import javax.crypto.spec.IvParameterSpec;
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
import java.security.InvalidAlgorithmParameterException;
|
import java.security.*;
|
||||||
import java.security.InvalidKeyException;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
|
||||||
import net.locusworks.common.utils.RandomString;
|
import net.locusworks.common.utils.RandomString;
|
||||||
import net.locusworks.common.utils.Utils;
|
import net.locusworks.common.utils.Utils;
|
||||||
|
|
||||||
import static net.locusworks.common.Charsets.UTF_8;
|
import static net.locusworks.common.Charsets.UTF_8;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AES encryption/decryption class
|
* AES encryption/decryption class
|
||||||
* This class will encrypt/decrypt data. The encryption key is never known.
|
* This class will encrypt/decrypt data. The encryption key is never known.
|
||||||
* Instead it is is generated by the provided seed. As long as the seed stays the same
|
* Instead, it is generated by the provided seed. As long as the seed stays the same
|
||||||
* the key will remain the same and the encryption/decryption will work. This
|
* the key will remain the same and the encryption/decryption will work. This
|
||||||
* provides and added security.
|
* provides and added security.
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
@@ -32,7 +31,7 @@ import static net.locusworks.common.Charsets.UTF_8;
|
|||||||
public class AES {
|
public class AES {
|
||||||
|
|
||||||
private static final String ENCRYPTION_TYPE = "AES";
|
private static final String ENCRYPTION_TYPE = "AES";
|
||||||
private static final String ENCRYPTION_ALGORITH = "AES/CBC/PKCS5Padding";
|
private static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5Padding";
|
||||||
private static final String PROVIDER = "SunJCE";
|
private static final String PROVIDER = "SunJCE";
|
||||||
private static final String ALGORITHM = "SHA1PRNG";
|
private static final String ALGORITHM = "SHA1PRNG";
|
||||||
|
|
||||||
@@ -44,25 +43,28 @@ public class AES {
|
|||||||
|
|
||||||
private String seed;
|
private String seed;
|
||||||
|
|
||||||
|
private RandomString randomizer;
|
||||||
|
|
||||||
private void initSecureKey(String seed) {
|
private void initSecureKey(String seed) {
|
||||||
try {
|
try {
|
||||||
SecureRandom sr = getSecureRandom(seed);
|
SecureRandom sr = getSecureRandom(seed);
|
||||||
KeyGenerator generator = KeyGenerator.getInstance(ENCRYPTION_TYPE);
|
KeyGenerator generator = KeyGenerator.getInstance(ENCRYPTION_TYPE);
|
||||||
generator.init(128, sr);
|
generator.init(128, sr);
|
||||||
init(generator.generateKey().getEncoded(), sr);
|
|
||||||
|
randomizer = RandomString.newInstance(sr);
|
||||||
|
init(generator.generateKey().getEncoded());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.err.println(ex);
|
throw new IllegalArgumentException("Unable to initialize encryption:", ex);
|
||||||
throw new IllegalArgumentException("Unable to initalize encryption:", ex);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the secure random object to be the same across all platforms
|
* Initializes the secure random object to be the same across all platforms
|
||||||
* with regard to provider and algorithm used
|
* with regard to provider and algorithm used
|
||||||
|
*
|
||||||
* @param seed Seed to initialize SecureRandom with
|
* @param seed Seed to initialize SecureRandom with
|
||||||
* @return SecureRandom object
|
* @return SecureRandom object
|
||||||
* @throws NoSuchAlgorithmException thrown when algorithm can't be used
|
* @throws NoSuchAlgorithmException thrown when algorithm can't be used
|
||||||
* @throws NoSuchProviderException thrown when the provider cant be found
|
|
||||||
*/
|
*/
|
||||||
private static SecureRandom getSecureRandom(String seed) throws NoSuchAlgorithmException {
|
private static SecureRandom getSecureRandom(String seed) throws NoSuchAlgorithmException {
|
||||||
SecureRandom sr = SecureRandom.getInstance(ALGORITHM);
|
SecureRandom sr = SecureRandom.getInstance(ALGORITHM);
|
||||||
@@ -72,17 +74,16 @@ public class AES {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the aes engine
|
* Initialize the aes engine
|
||||||
|
*
|
||||||
* @param key secret key to use
|
* @param key secret key to use
|
||||||
* @param sr
|
|
||||||
*/
|
*/
|
||||||
private void init(final byte[] key, SecureRandom sr) {
|
private void init(final byte[] key) {
|
||||||
try {
|
try {
|
||||||
this.cipher = Cipher.getInstance(ENCRYPTION_ALGORITH, PROVIDER);
|
this.cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, PROVIDER);
|
||||||
this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE);
|
this.secretKeySpec = new SecretKeySpec(key, ENCRYPTION_TYPE);
|
||||||
this.ivParamSpec = new IvParameterSpec(RandomString.getBytes(16, sr));
|
this.ivParamSpec = new IvParameterSpec(randomizer.getBytes(16));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.err.println(ex);
|
throw new IllegalArgumentException("Unable to initialize encryption:", ex);
|
||||||
throw new IllegalArgumentException("Unable to initalize encryption:", ex);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,12 +118,13 @@ public class AES {
|
|||||||
try {
|
try {
|
||||||
cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, this.ivParamSpec);
|
cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, this.ivParamSpec);
|
||||||
return new String(cipher.doFinal(cipherText), UTF_8);
|
return new String(cipher.doFinal(cipherText), UTF_8);
|
||||||
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
|
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException |
|
||||||
|
InvalidAlgorithmParameterException e) {
|
||||||
throw new IllegalArgumentException(e.getMessage(), e);
|
throw new IllegalArgumentException(e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public AES setSeed(String seed) {
|
public AES withSeed(String seed) {
|
||||||
if (this.seed == null || !this.seed.equals(seed)) {
|
if (this.seed == null || !this.seed.equals(seed)) {
|
||||||
initSecureKey(seed);
|
initSecureKey(seed);
|
||||||
}
|
}
|
||||||
@@ -135,7 +137,7 @@ public class AES {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static AES createInstance() {
|
public static AES createInstance() {
|
||||||
return createInstance(RandomString.getString(16));
|
return createInstance(RandomString.getInstance().getString(16));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AES createInstance(byte[] byteSeed) {
|
public static AES createInstance(byte[] byteSeed) {
|
||||||
@@ -144,9 +146,7 @@ public class AES {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static AES createInstance(String seed) {
|
public static AES createInstance(String seed) {
|
||||||
AES aes = new AES();
|
return new AES().withSeed(seed);
|
||||||
aes.setSeed(seed);
|
|
||||||
return aes;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws NoSuchAlgorithmException {
|
public static void main(String[] args) throws NoSuchAlgorithmException {
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
package net.locusworks.common.crypto;
|
package net.locusworks.common.crypto;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
import java.security.PrivateKey;
|
import java.security.PrivateKey;
|
||||||
|
|
||||||
import net.locusworks.common.Charsets;
|
import net.locusworks.common.Charsets;
|
||||||
|
|
||||||
public class AESKey implements PrivateKey {
|
public class AESKey implements PrivateKey {
|
||||||
|
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = -8452357427706386362L;
|
private static final long serialVersionUID = -8452357427706386362L;
|
||||||
private String seed;
|
private final String seed;
|
||||||
|
|
||||||
public AESKey(String seed) {
|
public AESKey(String seed) {
|
||||||
this.seed = seed;
|
this.seed = seed;
|
||||||
|
|||||||
@@ -20,19 +20,19 @@ public class EncryptionKeyFactory extends KeyFactory {
|
|||||||
|
|
||||||
public PrivateKey generatePrivateKey(KeySpec keySpec) throws InvalidKeySpecException {
|
public PrivateKey generatePrivateKey(KeySpec keySpec) throws InvalidKeySpecException {
|
||||||
if (keySpec instanceof AESKeySpec) {
|
if (keySpec instanceof AESKeySpec) {
|
||||||
return ((AESKeySpec)keySpec).generateKey();
|
return ((AESKeySpec) keySpec).generateKey();
|
||||||
}
|
}
|
||||||
return super.generatePrivate(keySpec);
|
return super.generatePrivate(keySpec);
|
||||||
}
|
}
|
||||||
|
|
||||||
public PublicKey generatePublicKey(KeySpec keySpec) throws InvalidKeySpecException {
|
public PublicKey generatePublicKey(KeySpec keySpec) throws InvalidKeySpecException {
|
||||||
keySpec = keySpec instanceof SSHEncodedKeySpec ? ((SSHEncodedKeySpec)keySpec).convertToRSAPubKeySpec() : keySpec;
|
keySpec = keySpec instanceof SSHEncodedKeySpec ? ((SSHEncodedKeySpec) keySpec).convertToRSAPubKeySpec() : keySpec;
|
||||||
return super.generatePublic(keySpec);
|
return super.generatePublic(keySpec);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static EncryptionKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException {
|
public static EncryptionKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException {
|
||||||
Instance instance = GetInstance.getInstance("KeyFactory", KeyFactorySpi.class, algorithm);
|
Instance instance = GetInstance.getInstance("KeyFactory", KeyFactorySpi.class, algorithm);
|
||||||
return new EncryptionKeyFactory((KeyFactorySpi)instance.impl, instance.provider, algorithm);
|
return new EncryptionKeyFactory((KeyFactorySpi) instance.impl, instance.provider, algorithm);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import javax.crypto.spec.PBEKeySpec;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The type Hash salt.
|
* The type Hash salt.
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
@@ -51,7 +52,6 @@ public class HashSalt {
|
|||||||
* Returns a salted PBKDF2 hash of the password.
|
* Returns a salted PBKDF2 hash of the password.
|
||||||
*
|
*
|
||||||
* @param password the password to hash
|
* @param password the password to hash
|
||||||
*
|
|
||||||
* @return a salted PBKDF2 hash of the password
|
* @return a salted PBKDF2 hash of the password
|
||||||
* @throws NoSuchAlgorithmException the no such algorithm exception
|
* @throws NoSuchAlgorithmException the no such algorithm exception
|
||||||
* @throws InvalidKeySpecException the invalid key spec exception
|
* @throws InvalidKeySpecException the invalid key spec exception
|
||||||
@@ -64,7 +64,6 @@ public class HashSalt {
|
|||||||
* Returns a salted PBKDF2 hash of the password.
|
* Returns a salted PBKDF2 hash of the password.
|
||||||
*
|
*
|
||||||
* @param password the password to hash
|
* @param password the password to hash
|
||||||
*
|
|
||||||
* @return a salted PBKDF2 hash of the password
|
* @return a salted PBKDF2 hash of the password
|
||||||
* @throws NoSuchAlgorithmException the no such algorithm exception
|
* @throws NoSuchAlgorithmException the no such algorithm exception
|
||||||
* @throws InvalidKeySpecException the invalid key spec exception
|
* @throws InvalidKeySpecException the invalid key spec exception
|
||||||
@@ -86,7 +85,6 @@ public class HashSalt {
|
|||||||
*
|
*
|
||||||
* @param password the password to check
|
* @param password the password to check
|
||||||
* @param correctHash the hash of the valid password
|
* @param correctHash the hash of the valid password
|
||||||
*
|
|
||||||
* @return true if the password is correct, false if not
|
* @return true if the password is correct, false if not
|
||||||
* @throws NoSuchAlgorithmException the no such algorithm exception
|
* @throws NoSuchAlgorithmException the no such algorithm exception
|
||||||
* @throws InvalidKeySpecException the invalid key spec exception
|
* @throws InvalidKeySpecException the invalid key spec exception
|
||||||
@@ -100,7 +98,6 @@ public class HashSalt {
|
|||||||
*
|
*
|
||||||
* @param password the password to check
|
* @param password the password to check
|
||||||
* @param correctHash the hash of the valid password
|
* @param correctHash the hash of the valid password
|
||||||
*
|
|
||||||
* @return true if the password is correct, false if not
|
* @return true if the password is correct, false if not
|
||||||
* @throws NoSuchAlgorithmException the no such algorithm exception
|
* @throws NoSuchAlgorithmException the no such algorithm exception
|
||||||
* @throws InvalidKeySpecException the invalid key spec exception
|
* @throws InvalidKeySpecException the invalid key spec exception
|
||||||
@@ -130,7 +127,7 @@ public class HashSalt {
|
|||||||
*/
|
*/
|
||||||
private static boolean slowEquals(byte[] a, byte[] b) {
|
private static boolean slowEquals(byte[] a, byte[] b) {
|
||||||
int diff = a.length ^ b.length;
|
int diff = a.length ^ b.length;
|
||||||
for(int i = 0; i < a.length && i < b.length; i++)
|
for (int i = 0; i < a.length && i < b.length; i++)
|
||||||
diff |= a[i] ^ b[i];
|
diff |= a[i] ^ b[i];
|
||||||
return diff == 0;
|
return diff == 0;
|
||||||
}
|
}
|
||||||
@@ -158,8 +155,8 @@ public class HashSalt {
|
|||||||
*/
|
*/
|
||||||
private static byte[] fromHex(String hex) {
|
private static byte[] fromHex(String hex) {
|
||||||
byte[] binary = new byte[hex.length() / 2];
|
byte[] binary = new byte[hex.length() / 2];
|
||||||
for(int i = 0; i < binary.length; i++) {
|
for (int i = 0; i < binary.length; i++) {
|
||||||
binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
|
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
|
||||||
}
|
}
|
||||||
return binary;
|
return binary;
|
||||||
}
|
}
|
||||||
@@ -174,13 +171,13 @@ public class HashSalt {
|
|||||||
BigInteger bi = new BigInteger(1, array);
|
BigInteger bi = new BigInteger(1, array);
|
||||||
String hex = bi.toString(16);
|
String hex = bi.toString(16);
|
||||||
int paddingLength = (array.length * 2) - hex.length();
|
int paddingLength = (array.length * 2) - hex.length();
|
||||||
if(paddingLength > 0)
|
if (paddingLength > 0)
|
||||||
return String.format("%0" + paddingLength + "d", 0) + hex;
|
return String.format("%0" + paddingLength + "d", 0) + hex;
|
||||||
else
|
else
|
||||||
return hex;
|
return hex;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main (String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
if (args == null || !(args.length > 0)) {
|
if (args == null || !(args.length > 0)) {
|
||||||
throw new IllegalArgumentException("No args provided. Need password as argument");
|
throw new IllegalArgumentException("No args provided. Need password as argument");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,8 @@ public class KeyFile implements AutoCloseable {
|
|||||||
this.encryptionType = encryptionType;
|
this.encryptionType = encryptionType;
|
||||||
}
|
}
|
||||||
|
|
||||||
private KeyFile() {}
|
private KeyFile() {
|
||||||
|
}
|
||||||
|
|
||||||
private void loadFromFile(String fileName) {
|
private void loadFromFile(String fileName) {
|
||||||
if (Utils.isEmptyString(fileName)) return;
|
if (Utils.isEmptyString(fileName)) return;
|
||||||
@@ -65,16 +66,20 @@ public class KeyFile implements AutoCloseable {
|
|||||||
throw new IllegalArgumentException(String.format("Unable to find file with name %s. Please check path", fileName));
|
throw new IllegalArgumentException(String.format("Unable to find file with name %s. Please check path", fileName));
|
||||||
}
|
}
|
||||||
|
|
||||||
String contentStr = IOUtils.toString(new FileInputStream(keyFile), Charsets.UTF_8);
|
String contentStr;
|
||||||
|
try (FileInputStream input = new FileInputStream(keyFile)) {
|
||||||
|
contentStr = IOUtils.toString(input, Charsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
boolean rsaFormat = !contentStr.startsWith("ssh-rsa") && !contentStr.startsWith("aes-seed");
|
boolean rsaFormat = !contentStr.startsWith("ssh-rsa") && !contentStr.startsWith("aes-seed");
|
||||||
if (rsaFormat) {
|
if (rsaFormat) {
|
||||||
contentStr = contentStr.replace("-----.*", "");
|
contentStr = contentStr.replaceAll("-----[^-]+-----", "");
|
||||||
|
contentStr = contentStr.replaceAll("\\s", "");
|
||||||
|
} else {
|
||||||
|
contentStr = contentStr.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
contentStr = contentStr.replace("\\r?\\n", "");
|
byte[] content = rsaFormat ? Base64.getDecoder().decode(contentStr) : contentStr.getBytes(Charsets.UTF_8);
|
||||||
|
|
||||||
byte[] content = rsaFormat ? Base64.getDecoder().decode(contentStr): contentStr.getBytes(Charsets.UTF_8);
|
|
||||||
|
|
||||||
EncryptionKeyFactory kf = EncryptionKeyFactory.getInstance("RSA");
|
EncryptionKeyFactory kf = EncryptionKeyFactory.getInstance("RSA");
|
||||||
|
|
||||||
@@ -90,10 +95,13 @@ public class KeyFile implements AutoCloseable {
|
|||||||
this.key = ksh.isPrivate() ? kf.generatePrivateKey(ksh.getKeySpec()) : kf.generatePublicKey(ksh.getKeySpec());
|
this.key = ksh.isPrivate() ? kf.generatePrivateKey(ksh.getKeySpec()) : kf.generatePublicKey(ksh.getKeySpec());
|
||||||
this.encryptionType = ksh.getEncryptionType();
|
this.encryptionType = ksh.getEncryptionType();
|
||||||
break;
|
break;
|
||||||
} catch (NullPointerException | InvalidKeySpecException ikse) { continue; }
|
} catch (NullPointerException | InvalidKeySpecException ikse) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if (this.key == null) {
|
||||||
throw new InvalidKeySpecException(String.format("Unable to determine if file %s is a private or public key. Not type of PKCS8, X509, SSH or AES spec", fileName));
|
throw new InvalidKeySpecException(String.format("Unable to determine if file %s is a private or public key. Not type of PKCS8, X509, SSH or AES spec", fileName));
|
||||||
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
throw new RuntimeException(ex);
|
throw new RuntimeException(ex);
|
||||||
}
|
}
|
||||||
@@ -102,7 +110,7 @@ public class KeyFile implements AutoCloseable {
|
|||||||
public void write(String fileName) {
|
public void write(String fileName) {
|
||||||
try {
|
try {
|
||||||
String data;
|
String data;
|
||||||
switch(this.encryptionType) {
|
switch (this.encryptionType) {
|
||||||
case AES:
|
case AES:
|
||||||
data = String.format("%s %s", this.key.getFormat(), Base64.getEncoder().encodeToString(this.key.getEncoded()));
|
data = String.format("%s %s", this.key.getFormat(), Base64.getEncoder().encodeToString(this.key.getEncoded()));
|
||||||
IOUtils.writeStringToFile(fileName, data);
|
IOUtils.writeStringToFile(fileName, data);
|
||||||
@@ -110,11 +118,11 @@ public class KeyFile implements AutoCloseable {
|
|||||||
case SSH:
|
case SSH:
|
||||||
try (DataOutputStreamHelper dosh = new DataOutputStreamHelper()) {
|
try (DataOutputStreamHelper dosh = new DataOutputStreamHelper()) {
|
||||||
getSSHPubKeyBytes(this.key)
|
getSSHPubKeyBytes(this.key)
|
||||||
.forEach(handleExceptionWrapper(item ->{
|
.forEach(handleExceptionWrapper(item -> {
|
||||||
dosh.writeInt(item.length);
|
dosh.writeInt(item.length);
|
||||||
dosh.write(item);
|
dosh.write(item);
|
||||||
}));
|
}));
|
||||||
data = String.format("ssh-rsa", dosh.base64Encoded(), this.description);
|
data = String.format("ssh-rsa %s %s", dosh.base64Encoded(), this.description);
|
||||||
IOUtils.writeStringToFile(fileName, data);
|
IOUtils.writeStringToFile(fileName, data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -178,7 +186,7 @@ public class KeyFile implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private List<byte[]> getSSHPubKeyBytes(Key key) {
|
private List<byte[]> getSSHPubKeyBytes(Key key) {
|
||||||
RSAPublicKey rpk = (RSAPublicKey)key;
|
RSAPublicKey rpk = (RSAPublicKey) key;
|
||||||
return Arrays.asList("ssh-rsa".getBytes(Charsets.UTF_8),
|
return Arrays.asList("ssh-rsa".getBytes(Charsets.UTF_8),
|
||||||
rpk.getPublicExponent().toByteArray(),
|
rpk.getPublicExponent().toByteArray(),
|
||||||
rpk.getModulus().toByteArray()
|
rpk.getModulus().toByteArray()
|
||||||
@@ -186,9 +194,9 @@ public class KeyFile implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static class KeySpecHelper {
|
private static class KeySpecHelper {
|
||||||
private KeySpec keySpec;
|
private final KeySpec keySpec;
|
||||||
private boolean isPrivate;
|
private final boolean isPrivate;
|
||||||
private EncryptionType encryptionType;
|
private final EncryptionType encryptionType;
|
||||||
|
|
||||||
public KeySpecHelper(KeySpec keySpec, boolean isPrivate, EncryptionType encryptionType) {
|
public KeySpecHelper(KeySpec keySpec, boolean isPrivate, EncryptionType encryptionType) {
|
||||||
super();
|
super();
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import net.locusworks.common.io.IOUtils;
|
|||||||
public class RSA {
|
public class RSA {
|
||||||
|
|
||||||
private static final String ENCRYPTION_TYPE = "RSA";
|
private static final String ENCRYPTION_TYPE = "RSA";
|
||||||
private static final String ENCRYPTION_ALGORITHM = "RSA/ECB/PKCS10PADDING";
|
private static final String ENCRYPTION_ALGORITHM = "RSA/ECB/PKCS1PADDING";
|
||||||
private static final String PROVIDER = "SunJCE";
|
private static final String PROVIDER = "SunJCE";
|
||||||
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
|
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ public class RSA {
|
|||||||
public static KeyPair loadKeyPair(String publicKey, String privateKey) {
|
public static KeyPair loadKeyPair(String publicKey, String privateKey) {
|
||||||
KeyFile pubKey = KeyFile.read(publicKey);
|
KeyFile pubKey = KeyFile.read(publicKey);
|
||||||
KeyFile prvKey = KeyFile.read(privateKey);
|
KeyFile prvKey = KeyFile.read(privateKey);
|
||||||
return new KeyPair((PublicKey)pubKey.getKey(), (PrivateKey)prvKey.getKey());
|
return new KeyPair((PublicKey) pubKey.getKey(), (PrivateKey) prvKey.getKey());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean generateAndWriteSSHKeys() {
|
public static boolean generateAndWriteSSHKeys() {
|
||||||
@@ -139,14 +139,14 @@ public class RSA {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static boolean writePemFile(Key key, String fileName, String description, boolean sshFormat) {
|
private static boolean writePemFile(Key key, String fileName, String description, boolean sshFormat) {
|
||||||
try(KeyFile kf = sshFormat ? new KeyFile(key, description, EncryptionType.SSH) : new KeyFile(key, description)) {
|
try (KeyFile kf = sshFormat ? new KeyFile(key, description, EncryptionType.SSH) : new KeyFile(key, description)) {
|
||||||
kf.write(fileName);
|
kf.write(fileName);
|
||||||
}
|
}
|
||||||
return Files.exists(Paths.get(fileName));
|
return Files.exists(Paths.get(fileName));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void calculateKeyLength(Key key, String message) throws IllegalBlockSizeException {
|
private static void calculateKeyLength(Key key, String message) throws IllegalBlockSizeException {
|
||||||
int keyLength = ((RSAKey)key).getModulus().bitLength();
|
int keyLength = ((RSAKey) key).getModulus().bitLength();
|
||||||
int requiredKeyLength = calculateRequiredKeyLength(message);
|
int requiredKeyLength = calculateRequiredKeyLength(message);
|
||||||
if (keyLength < requiredKeyLength) {
|
if (keyLength < requiredKeyLength) {
|
||||||
throw new IllegalBlockSizeException(String.format("RSA key size of %d is not large enough to encrypt message of length %d. "
|
throw new IllegalBlockSizeException(String.format("RSA key size of %d is not large enough to encrypt message of length %d. "
|
||||||
|
|||||||
@@ -37,8 +37,7 @@ public class SSHEncodedKeySpec extends EncodedKeySpec {
|
|||||||
checkArguments(SSH_MARKER.equals(marker), "Looking for marker %s but received %s", SSH_MARKER, marker);
|
checkArguments(SSH_MARKER.equals(marker), "Looking for marker %s but received %s", SSH_MARKER, marker);
|
||||||
BigInteger publicExponent = new BigInteger(readLengthFirst(stream));
|
BigInteger publicExponent = new BigInteger(readLengthFirst(stream));
|
||||||
BigInteger modulus = new BigInteger(readLengthFirst(stream));
|
BigInteger modulus = new BigInteger(readLengthFirst(stream));
|
||||||
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
|
return new RSAPublicKeySpec(modulus, publicExponent);
|
||||||
return keySpec;
|
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
throw new InvalidKeySpecException(ex);
|
throw new InvalidKeySpecException(ex);
|
||||||
}
|
}
|
||||||
@@ -50,11 +49,11 @@ public class SSHEncodedKeySpec extends EncodedKeySpec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] readLengthFirst(InputStream in) throws IOException {
|
private static byte[] readLengthFirst(InputStream in) throws IOException {
|
||||||
int[] bytes = new int[] {in.read(), in.read(), in.read(), in.read()};
|
int[] bytes = new int[]{in.read(), in.read(), in.read(), in.read()};
|
||||||
int length = 0;
|
int length = 0;
|
||||||
int shift = 24;
|
int shift = 24;
|
||||||
for (int i = 0; i < bytes.length; i++) {
|
for (int aByte : bytes) {
|
||||||
length += bytes[i] << shift;
|
length += aByte << shift;
|
||||||
shift -= 8;
|
shift -= 8;
|
||||||
}
|
}
|
||||||
byte[] val = new byte[length];
|
byte[] val = new byte[length];
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package net.locusworks.common.exceptions;
|
package net.locusworks.common.exceptions;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
|
|
||||||
/***
|
/***
|
||||||
* Custom exception class for the patch repository
|
* Custom exception class for the patch repository
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
@@ -8,6 +10,7 @@ package net.locusworks.common.exceptions;
|
|||||||
public class ApplicationException extends Exception {
|
public class ApplicationException extends Exception {
|
||||||
private final Integer code;
|
private final Integer code;
|
||||||
boolean success = false;
|
boolean success = false;
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
public static ApplicationException egregiousServer() {
|
public static ApplicationException egregiousServer() {
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package net.locusworks.common.immutables;
|
package net.locusworks.common.immutables;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class that holds two immutable objects as a pair
|
* Class that holds two immutable objects as a pair
|
||||||
* @author Isaac Parenteau
|
*
|
||||||
* @version 1.0.0
|
|
||||||
* @param <V1> class type of object 1
|
* @param <V1> class type of object 1
|
||||||
* @param <V2> class type of object 2
|
* @param <V2> class type of object 2
|
||||||
|
* @author Isaac Parenteau
|
||||||
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class Pair<V1, V2> extends Unit<V1> {
|
public class Pair<V1, V2> extends Unit<V1> {
|
||||||
|
|
||||||
@@ -20,6 +23,7 @@ public class Pair<V1, V2> extends Unit<V1> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param value1 Object 1
|
* @param value1 Object 1
|
||||||
* @param value2 Object 2
|
* @param value2 Object 2
|
||||||
*/
|
*/
|
||||||
@@ -30,14 +34,19 @@ public class Pair<V1, V2> extends Unit<V1> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Set value2
|
* Set value2
|
||||||
|
*
|
||||||
* @param value2 value to set it
|
* @param value2 value to set it
|
||||||
*/
|
*/
|
||||||
public void setValue2(V2 value2) {
|
public void setValue2(V2 value2) {
|
||||||
|
if (Objects.nonNull(this.value2)) {
|
||||||
|
throw new IllegalArgumentException("Value2 already set. Cannot change");
|
||||||
|
}
|
||||||
this.value2 = value2;
|
this.value2 = value2;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get value2
|
* Get value2
|
||||||
|
*
|
||||||
* @return value2
|
* @return value2
|
||||||
*/
|
*/
|
||||||
public V2 getValue2() {
|
public V2 getValue2() {
|
||||||
@@ -46,10 +55,10 @@ public class Pair<V1, V2> extends Unit<V1> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
if (!(other instanceof Pair)) return false;
|
if (other == null) return false;
|
||||||
|
if (!(other instanceof Pair<?, ?> pair)) return false;
|
||||||
|
|
||||||
Pair<?, ?> otherPair = (Pair<?, ?>)other;
|
return this.getValue2().equals(pair.getValue2()) &&
|
||||||
|
this.getValue1().equals(pair.getValue1());
|
||||||
return super.equals(otherPair) && this.getValue2().equals(otherPair.getValue2());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,15 @@
|
|||||||
package net.locusworks.common.immutables;
|
package net.locusworks.common.immutables;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class that holds three immutable objects as triplets
|
* Class that holds three immutable objects as triplets
|
||||||
* @author Isaac Parenteau
|
*
|
||||||
* @version 1.0.0
|
|
||||||
* @param <V1> class type of object 1
|
* @param <V1> class type of object 1
|
||||||
* @param <V2> class type of object 2
|
* @param <V2> class type of object 2
|
||||||
* @param <V3> class type of object 3
|
* @param <V3> class type of object 3
|
||||||
|
* @author Isaac Parenteau
|
||||||
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
|
public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
|
||||||
|
|
||||||
@@ -21,6 +24,7 @@ public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param value1 Object 1
|
* @param value1 Object 1
|
||||||
* @param value2 Object 2
|
* @param value2 Object 2
|
||||||
* @param value3 Object 3
|
* @param value3 Object 3
|
||||||
@@ -32,14 +36,19 @@ public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Set value 3
|
* Set value 3
|
||||||
|
*
|
||||||
* @param value3 value 3
|
* @param value3 value 3
|
||||||
*/
|
*/
|
||||||
public void setValue3(V3 value3) {
|
public void setValue3(V3 value3) {
|
||||||
|
if (Objects.nonNull(this.value3)) {
|
||||||
|
throw new IllegalArgumentException("Value3 already set. Cannot change");
|
||||||
|
}
|
||||||
this.value3 = value3;
|
this.value3 = value3;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get value 3
|
* Get value 3
|
||||||
|
*
|
||||||
* @return value 3
|
* @return value 3
|
||||||
*/
|
*/
|
||||||
public V3 getValue3() {
|
public V3 getValue3() {
|
||||||
@@ -48,10 +57,11 @@ public class Triplet<V1, V2, V3> extends Pair<V1, V2> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
if (!(other instanceof Triplet)) return false;
|
if (other == null) return false;
|
||||||
|
if (!(other instanceof Triplet<?, ?, ?> triplet)) return false;
|
||||||
|
|
||||||
Triplet<?, ?, ?> otherTriplet = (Triplet<?, ?, ?>)other;
|
return this.getValue3().equals(triplet.getValue3()) &&
|
||||||
|
this.getValue2().equals(triplet.getValue2()) &&
|
||||||
return super.equals(otherTriplet) && this.getValue3().equals(otherTriplet.getValue3());
|
this.getValue1().equals(triplet.getValue1());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
package net.locusworks.common.immutables;
|
package net.locusworks.common.immutables;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class that holds three immutable objects as triplets
|
* Class that holds three immutable objects as triplets
|
||||||
|
*
|
||||||
|
* @param <V1> class type of object 1
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @param <V1> class type of object 1
|
|
||||||
*/
|
*/
|
||||||
public class Unit<V1> {
|
public class Unit<V1> {
|
||||||
|
|
||||||
@@ -13,10 +16,12 @@ public class Unit<V1> {
|
|||||||
/**
|
/**
|
||||||
* Default constructor with no values
|
* Default constructor with no values
|
||||||
*/
|
*/
|
||||||
public Unit() {}
|
public Unit() {
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constuctor
|
* Constructor
|
||||||
|
*
|
||||||
* @param value1 value 1
|
* @param value1 value 1
|
||||||
*/
|
*/
|
||||||
public Unit(V1 value1) {
|
public Unit(V1 value1) {
|
||||||
@@ -25,14 +30,19 @@ public class Unit<V1> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Set value 1
|
* Set value 1
|
||||||
|
*
|
||||||
* @param value1 value 1
|
* @param value1 value 1
|
||||||
*/
|
*/
|
||||||
public void setValue1(V1 value1) {
|
public void setValue1(V1 value1) {
|
||||||
|
if (Objects.nonNull(this.value1)) {
|
||||||
|
throw new IllegalArgumentException("Value1 already set. Cannot change");
|
||||||
|
}
|
||||||
this.value1 = value1;
|
this.value1 = value1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get value 1
|
* Get value 1
|
||||||
|
*
|
||||||
* @return value1
|
* @return value1
|
||||||
*/
|
*/
|
||||||
public V1 getValue1() {
|
public V1 getValue1() {
|
||||||
@@ -41,10 +51,8 @@ public class Unit<V1> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
if (!(other instanceof Unit)) return false;
|
if (other == null) return false;
|
||||||
|
if (!(other instanceof Unit<?>)) return false;
|
||||||
Unit<?> otherUnit = (Unit<?>)other;
|
return this.getValue1().equals(((Unit<?>) other).getValue1());
|
||||||
|
|
||||||
return this.getValue1().equals(otherUnit.getValue1());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,6 @@ import java.util.Iterator;
|
|||||||
public interface AutoCloseableIterator<T> extends Iterator<T>, AutoCloseable {
|
public interface AutoCloseableIterator<T> extends Iterator<T>, AutoCloseable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close();
|
void close();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ public class IOUtils {
|
|||||||
* This method buffers the input internally, so there is no need to use a
|
* This method buffers the input internally, so there is no need to use a
|
||||||
* <code>BufferedInputStream</code>.
|
* <code>BufferedInputStream</code>.
|
||||||
*
|
*
|
||||||
* @param input the <code>InputStream</code> to read from, not null
|
* @param stream the <code>InputStream</code> to read from, not null
|
||||||
* @param encoding the encoding to use, null means platform default
|
* @param charset the encoding to use, null means platform default
|
||||||
* @return the list of Strings, never null
|
* @return the list of Strings, never null
|
||||||
* @throws NullPointerException if the input is null
|
* @throws NullPointerException if the input is null
|
||||||
* @throws IOException if an I/O error occurs
|
* @throws IOException if an I/O error occurs
|
||||||
@@ -74,7 +74,7 @@ public class IOUtils {
|
|||||||
public static List<String> readLines(final Reader input) throws IOException {
|
public static List<String> readLines(final Reader input) throws IOException {
|
||||||
final BufferedReader reader = toBufferedReader(input);
|
final BufferedReader reader = toBufferedReader(input);
|
||||||
final List<String> list = new ArrayList<>();
|
final List<String> list = new ArrayList<>();
|
||||||
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
|
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
|
||||||
list.add(line);
|
list.add(line);
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
@@ -136,6 +136,7 @@ public class IOUtils {
|
|||||||
}
|
}
|
||||||
return (int) count;
|
return (int) count;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Copies bytes from an <code>InputStream</code> to an <code>OutputStream</code> using an internal buffer of the
|
* Copies bytes from an <code>InputStream</code> to an <code>OutputStream</code> using an internal buffer of the
|
||||||
* given size.
|
* given size.
|
||||||
@@ -172,7 +173,7 @@ public class IOUtils {
|
|||||||
*/
|
*/
|
||||||
public static void copy(final InputStream input, final Writer output, final Charset inputEncoding)
|
public static void copy(final InputStream input, final Writer output, final Charset inputEncoding)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
final InputStreamReader in = new InputStreamReader(input, inputEncoding.toString());
|
final InputStreamReader in = new InputStreamReader(input, inputEncoding);
|
||||||
copy(in, output);
|
copy(in, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,7 +330,7 @@ public class IOUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void writeStringToFile(Path file, String data, Charset charset) throws IOException {
|
public static void writeStringToFile(Path file, String data, Charset charset) throws IOException {
|
||||||
try(Writer writer = Files.newBufferedWriter(file, charset)) {
|
try (Writer writer = Files.newBufferedWriter(file, charset)) {
|
||||||
writer.write(data);
|
writer.write(data);
|
||||||
writer.flush();
|
writer.flush();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ public class MigrationItem {
|
|||||||
protected Flyway flyway = null;
|
protected Flyway flyway = null;
|
||||||
protected MigrationInfo[] pendingMigrations;
|
protected MigrationInfo[] pendingMigrations;
|
||||||
protected MigrationInfo[] allMigrations;
|
protected MigrationInfo[] allMigrations;
|
||||||
private MigrationCallback callback;
|
private final MigrationCallback callback;
|
||||||
|
|
||||||
public MigrationItem(Flyway flyway, MigrationCallback callback) {
|
public MigrationItem(Flyway flyway, MigrationCallback callback) {
|
||||||
this.allMigrations = flyway.info().all();
|
this.allMigrations = flyway.info().all();
|
||||||
this.pendingMigrations = flyway.info().pending();
|
this.pendingMigrations = flyway.info().pending();
|
||||||
this.flyway=flyway;
|
this.flyway = flyway;
|
||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,12 @@
|
|||||||
package net.locusworks.common.net;
|
package net.locusworks.common.net;
|
||||||
|
|
||||||
import java.security.SecureRandom;
|
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
import net.locusworks.common.net.ssl.SSLManager;
|
||||||
import javax.net.ssl.TrustManager;
|
import org.apache.hc.client5.http.classic.HttpClient;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||||
import org.apache.http.HttpEntity;
|
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.hc.core5.http.HttpEntity;
|
||||||
import org.apache.http.client.HttpClient;
|
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
|
||||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
|
||||||
import org.apache.http.util.EntityUtils;
|
|
||||||
|
|
||||||
import net.locusworks.common.net.certmanagers.TrustAllCertsManager;
|
|
||||||
import net.locusworks.common.net.hostverifiers.AllHostValidVerifyer;
|
|
||||||
|
|
||||||
public class HttpClientHelper {
|
public class HttpClientHelper {
|
||||||
|
|
||||||
@@ -32,13 +24,14 @@ public class HttpClientHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final String[] TLS = new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"};
|
private static final String[] TLS = new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"};
|
||||||
|
|
||||||
private HttpClient client;
|
private final HttpClient client;
|
||||||
private String baseUrl;
|
private final String baseUrl;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor to handle http connection
|
* Constructor to handle http connection
|
||||||
|
*
|
||||||
* @param protocol protocol to use (http or https)
|
* @param protocol protocol to use (http or https)
|
||||||
* @param host the host url
|
* @param host the host url
|
||||||
* @param port the host port
|
* @param port the host port
|
||||||
@@ -60,36 +53,27 @@ public class HttpClientHelper {
|
|||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCertsManager() };
|
return SSLManager.getTrustAllTLSClient();
|
||||||
//Setup the ssl instance using tls
|
|
||||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
|
||||||
sslContext.init(null, trustAllCerts, new SecureRandom());
|
|
||||||
|
|
||||||
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, TLS, null, new AllHostValidVerifyer());
|
|
||||||
|
|
||||||
builder = builder.setSSLSocketFactory(sslsf);
|
|
||||||
|
|
||||||
return builder.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the http GET response code
|
* Get the http GET response code
|
||||||
|
*
|
||||||
* @param endpoint endpoint to get the response from
|
* @param endpoint endpoint to get the response from
|
||||||
* @return responseCode
|
* @return responseCode
|
||||||
* @throws Exception general exception
|
* @throws Exception general exception
|
||||||
*/
|
*/
|
||||||
public Integer getGetResponseCode(String endpoint) throws Exception {
|
public Integer getResponseCode(String endpoint) throws Exception {
|
||||||
String url = this.baseUrl + endpoint;
|
String url = this.baseUrl + endpoint;
|
||||||
|
|
||||||
HttpResponse response = this.client.execute(new HttpGet(url));
|
return this.client.execute(new HttpGet(url), response -> {
|
||||||
|
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
int responseCode = response.getCode();
|
||||||
Integer responseCode = response.getStatusLine().getStatusCode();
|
|
||||||
|
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
return responseCode;
|
return responseCode;
|
||||||
};
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,16 +9,20 @@ import javax.net.ssl.X509TrustManager;
|
|||||||
public class TrustAllCertsManager implements X509TrustManager {
|
public class TrustAllCertsManager implements X509TrustManager {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }
|
public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }
|
public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public X509Certificate[] getAcceptedIssuers() { return null; }
|
public X509Certificate[] getAcceptedIssuers() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
public static TrustManager[] trustAllCerts() {
|
public static TrustManager[] trustAllCerts() {
|
||||||
return new TrustManager[] { new TrustAllCertsManager() };
|
return new TrustManager[]{new TrustAllCertsManager()};
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package net.locusworks.common.net.hostverifiers;
|
||||||
|
|
||||||
|
import javax.net.ssl.HostnameVerifier;
|
||||||
|
import javax.net.ssl.SSLSession;
|
||||||
|
|
||||||
|
public class AllHostValidVerifier implements HostnameVerifier {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean verify(String arg0, SSLSession arg1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package net.locusworks.common.net.hostverifiers;
|
|
||||||
|
|
||||||
import javax.net.ssl.HostnameVerifier;
|
|
||||||
import javax.net.ssl.SSLSession;
|
|
||||||
|
|
||||||
public class AllHostValidVerifyer implements HostnameVerifier {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean verify(String arg0, SSLSession arg1) { return true; }
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -7,24 +7,35 @@ import java.security.SecureRandom;
|
|||||||
import javax.net.ssl.SSLContext;
|
import javax.net.ssl.SSLContext;
|
||||||
import javax.net.ssl.TrustManager;
|
import javax.net.ssl.TrustManager;
|
||||||
|
|
||||||
import org.apache.http.client.HttpClient;
|
|
||||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
|
||||||
|
|
||||||
import net.locusworks.common.net.certmanagers.TrustAllCertsManager;
|
import net.locusworks.common.net.certmanagers.TrustAllCertsManager;
|
||||||
import net.locusworks.common.net.hostverifiers.AllHostValidVerifyer;
|
import org.apache.hc.client5.http.classic.HttpClient;
|
||||||
|
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||||
|
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||||
|
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||||
|
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
||||||
|
import org.apache.hc.client5.http.ssl.TlsSocketStrategy;
|
||||||
|
|
||||||
public class SSLManager {
|
public class SSLManager {
|
||||||
|
|
||||||
public static final String[] TLS = new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"};
|
public static final String[] TLS = new String[] {"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"};
|
||||||
|
|
||||||
public static HttpClient getTrustAllTLSClient() throws NoSuchAlgorithmException, KeyManagementException {
|
public static HttpClient getTrustAllTLSClient() throws NoSuchAlgorithmException, KeyManagementException {
|
||||||
SSLContext context = SSLContext.getInstance("TLS");
|
TrustManager[] trustAllCerts = new TrustManager[]{new TrustAllCertsManager()};
|
||||||
context.init(null, new TrustManager[] { new TrustAllCertsManager() }, new SecureRandom());
|
//Setup the ssl instance using tls
|
||||||
|
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||||
|
sslContext.init(null, trustAllCerts, new SecureRandom());
|
||||||
|
TlsSocketStrategy tlsStrategy = new DefaultClientTlsStrategy(sslContext);
|
||||||
|
|
||||||
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(context, TLS, null, new AllHostValidVerifyer());
|
HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
|
||||||
|
.setTlsSocketStrategy(tlsStrategy)
|
||||||
|
.build();
|
||||||
|
|
||||||
return HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
|
return HttpClients.custom()
|
||||||
|
.setConnectionManager(connectionManager)
|
||||||
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private SSLManager() { }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package net.locusworks.common.objectmapper;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Error handler for the object mapper class
|
* Error handler for the object mapper class
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
|
|||||||
@@ -14,21 +14,24 @@ import com.google.gson.GsonBuilder;
|
|||||||
/**
|
/**
|
||||||
* Object mapper to map to convert objects to json string or
|
* Object mapper to map to convert objects to json string or
|
||||||
* json string back to object
|
* json string back to object
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
*/
|
*/
|
||||||
public class ObjectMapperHelper {
|
public class ObjectMapperHelper {
|
||||||
|
|
||||||
private static ObjectMapper mapper;
|
private static final ObjectMapper mapper;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
mapper = new ObjectMapper();
|
mapper = new ObjectMapper();
|
||||||
mapper.setSerializationInclusion(Include.NON_NULL);
|
mapper.setDefaultPropertyInclusion(Include.NON_NULL);
|
||||||
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
|
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write an object out to json
|
* Write an object out to json
|
||||||
|
*
|
||||||
* @param object Object to convert to json
|
* @param object Object to convert to json
|
||||||
* @return return a string representation of the object converted to json
|
* @return return a string representation of the object converted to json
|
||||||
*/
|
*/
|
||||||
@@ -42,8 +45,8 @@ public class ObjectMapperHelper {
|
|||||||
gsonBuilder.setPrettyPrinting();
|
gsonBuilder.setPrettyPrinting();
|
||||||
Gson gson = gsonBuilder.create();
|
Gson gson = gsonBuilder.create();
|
||||||
results = gson.toJson(object);
|
results = gson.toJson(object);
|
||||||
} catch (Exception e) {
|
} catch (Throwable e) {
|
||||||
new ObjectMapperResults<>(e);
|
return new ObjectMapperResults<>(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new ObjectMapperResults<>(results);
|
return new ObjectMapperResults<>(results);
|
||||||
@@ -51,6 +54,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert binary data to an object
|
* Convert binary data to an object
|
||||||
|
*
|
||||||
* @param src Binary data to convert
|
* @param src Binary data to convert
|
||||||
* @param clazz Class to convert the data to
|
* @param clazz Class to convert the data to
|
||||||
* @param <T> The expected class of the value
|
* @param <T> The expected class of the value
|
||||||
@@ -66,6 +70,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a json string to an object
|
* Convert a json string to an object
|
||||||
|
*
|
||||||
* @param src Json String
|
* @param src Json String
|
||||||
* @param clazz Class to convert the json string to
|
* @param clazz Class to convert the json string to
|
||||||
* @param <T> The expected class of the value
|
* @param <T> The expected class of the value
|
||||||
@@ -81,6 +86,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert an java object to a class
|
* Convert an java object to a class
|
||||||
|
*
|
||||||
* @param src Object to convert
|
* @param src Object to convert
|
||||||
* @param clazz Class to convert the object to
|
* @param clazz Class to convert the object to
|
||||||
* @param <T> The expected class of the value
|
* @param <T> The expected class of the value
|
||||||
@@ -89,7 +95,7 @@ public class ObjectMapperHelper {
|
|||||||
public static <T> ObjectMapperResults<T> readValue(Object src, Class<T> clazz) {
|
public static <T> ObjectMapperResults<T> readValue(Object src, Class<T> clazz) {
|
||||||
try {
|
try {
|
||||||
if (src instanceof String) {
|
if (src instanceof String) {
|
||||||
return readValue((String)src, clazz);
|
return readValue((String) src, clazz);
|
||||||
}
|
}
|
||||||
return readValue(mapper.writeValueAsString(src), clazz);
|
return readValue(mapper.writeValueAsString(src), clazz);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
@@ -99,6 +105,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an object to a list
|
* Converts an object to a list
|
||||||
|
*
|
||||||
* @param object Object to convert
|
* @param object Object to convert
|
||||||
* @param objectClass Class to convert the object to
|
* @param objectClass Class to convert the object to
|
||||||
* @param <T> The expected class of the object
|
* @param <T> The expected class of the object
|
||||||
@@ -110,6 +117,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an object to a list
|
* Converts an object to a list
|
||||||
|
*
|
||||||
* @param object Object to convert
|
* @param object Object to convert
|
||||||
* @param objectClass Class to convert the object to
|
* @param objectClass Class to convert the object to
|
||||||
* @param listClass List type to make
|
* @param listClass List type to make
|
||||||
@@ -120,7 +128,7 @@ public class ObjectMapperHelper {
|
|||||||
public static <T, L extends Collection<?>> ObjectMapperListResults<List<T>> readListValue(Object object, Class<T> objectClass, Class<L> listClass) {
|
public static <T, L extends Collection<?>> ObjectMapperListResults<List<T>> readListValue(Object object, Class<T> objectClass, Class<L> listClass) {
|
||||||
try {
|
try {
|
||||||
if (object instanceof String) {
|
if (object instanceof String) {
|
||||||
return readListValue((String)object, objectClass, listClass);
|
return readListValue((String) object, objectClass, listClass);
|
||||||
}
|
}
|
||||||
return readListValue(mapper.writeValueAsString(object), objectClass, listClass);
|
return readListValue(mapper.writeValueAsString(object), objectClass, listClass);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
@@ -130,6 +138,7 @@ public class ObjectMapperHelper {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an object to a list
|
* Converts an object to a list
|
||||||
|
*
|
||||||
* @param src Source to convert
|
* @param src Source to convert
|
||||||
* @param objectClass Class to convert the object to
|
* @param objectClass Class to convert the object to
|
||||||
* @param listClass List type to make
|
* @param listClass List type to make
|
||||||
|
|||||||
@@ -4,15 +4,17 @@ import java.util.Collection;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Holds the results from the object mapper list conversion
|
* Holds the results from the object mapper list conversion
|
||||||
|
*
|
||||||
|
* @param <T> class type of the object mapper
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
* @param <T> class type of the object mapper
|
|
||||||
*/
|
*/
|
||||||
public class ObjectMapperListResults<T extends Collection<?>> extends ObjectMapperResults<T> {
|
public class ObjectMapperListResults<T extends Collection<?>> extends ObjectMapperResults<T> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param results results from the conversion
|
* @param results results from the conversion
|
||||||
*/
|
*/
|
||||||
public ObjectMapperListResults(T results) {
|
public ObjectMapperListResults(T results) {
|
||||||
@@ -21,6 +23,7 @@ public class ObjectMapperListResults<T extends Collection<?>> extends ObjectMapp
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param exception exception that was thrown during conversion
|
* @param exception exception that was thrown during conversion
|
||||||
*/
|
*/
|
||||||
public ObjectMapperListResults(Throwable exception) {
|
public ObjectMapperListResults(Throwable exception) {
|
||||||
@@ -29,6 +32,7 @@ public class ObjectMapperListResults<T extends Collection<?>> extends ObjectMapp
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param results results from the conversion
|
* @param results results from the conversion
|
||||||
* @param exception exception that was thrown during conversion
|
* @param exception exception that was thrown during conversion
|
||||||
*/
|
*/
|
||||||
@@ -39,6 +43,7 @@ public class ObjectMapperListResults<T extends Collection<?>> extends ObjectMapp
|
|||||||
/**
|
/**
|
||||||
* Add the error handler to the results to retrieve the error that caused
|
* Add the error handler to the results to retrieve the error that caused
|
||||||
* the exception
|
* the exception
|
||||||
|
*
|
||||||
* @param error the error handler to use
|
* @param error the error handler to use
|
||||||
* @return this
|
* @return this
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ package net.locusworks.common.objectmapper;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Holds the results from the object mapper list conversion
|
* Holds the results from the object mapper list conversion
|
||||||
|
*
|
||||||
|
* @param <T> class type of the object being converted from json to object
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
* @param <T> class type of the object being converted from json to object
|
|
||||||
*/
|
*/
|
||||||
public class ObjectMapperResults<T> {
|
public class ObjectMapperResults<T> {
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param results results from the conversion
|
* @param results results from the conversion
|
||||||
*/
|
*/
|
||||||
public ObjectMapperResults(T results) {
|
public ObjectMapperResults(T results) {
|
||||||
@@ -22,6 +24,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param exception exception that was thrown during conversion
|
* @param exception exception that was thrown during conversion
|
||||||
*/
|
*/
|
||||||
public ObjectMapperResults(Throwable exception) {
|
public ObjectMapperResults(Throwable exception) {
|
||||||
@@ -30,6 +33,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param results results from the conversion
|
* @param results results from the conversion
|
||||||
* @param exception exception that was thrown during conversion
|
* @param exception exception that was thrown during conversion
|
||||||
*/
|
*/
|
||||||
@@ -40,6 +44,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* get the exception that happened during conversion
|
* get the exception that happened during conversion
|
||||||
|
*
|
||||||
* @return exception
|
* @return exception
|
||||||
*/
|
*/
|
||||||
public Throwable getException() {
|
public Throwable getException() {
|
||||||
@@ -48,6 +53,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the exception
|
* Set the exception
|
||||||
|
*
|
||||||
* @param exception
|
* @param exception
|
||||||
*/
|
*/
|
||||||
public void setException(Throwable exception) {
|
public void setException(Throwable exception) {
|
||||||
@@ -56,6 +62,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the result
|
* Get the result
|
||||||
|
*
|
||||||
* @return the converted results
|
* @return the converted results
|
||||||
*/
|
*/
|
||||||
public T getResults() {
|
public T getResults() {
|
||||||
@@ -64,6 +71,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* set the results
|
* set the results
|
||||||
|
*
|
||||||
* @param results results to set
|
* @param results results to set
|
||||||
*/
|
*/
|
||||||
public void setResults(T results) {
|
public void setResults(T results) {
|
||||||
@@ -72,6 +80,7 @@ public class ObjectMapperResults<T> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Check to see if the conversion caused an error
|
* Check to see if the conversion caused an error
|
||||||
|
*
|
||||||
* @return true if there is an error, false otherwise
|
* @return true if there is an error, false otherwise
|
||||||
*/
|
*/
|
||||||
public boolean hasError() {
|
public boolean hasError() {
|
||||||
@@ -81,6 +90,7 @@ public class ObjectMapperResults<T> {
|
|||||||
/**
|
/**
|
||||||
* Add the error handler to the results to retrieve the error that caused
|
* Add the error handler to the results to retrieve the error that caused
|
||||||
* the exception
|
* the exception
|
||||||
|
*
|
||||||
* @param error the error handler to use
|
* @param error the error handler to use
|
||||||
* @return this
|
* @return this
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package net.locusworks.common.properties;
|
package net.locusworks.common.properties;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
public class ImmutableProperties extends Properties {
|
public class ImmutableProperties extends Properties {
|
||||||
|
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = 65942088008978137L;
|
private static final long serialVersionUID = 65942088008978137L;
|
||||||
|
|
||||||
public ImmutableProperties() {
|
public ImmutableProperties() {
|
||||||
@@ -14,7 +16,7 @@ public class ImmutableProperties extends Properties {
|
|||||||
super();
|
super();
|
||||||
if (props == null || props.isEmpty()) return;
|
if (props == null || props.isEmpty()) return;
|
||||||
|
|
||||||
props.entrySet().forEach(item -> this.put(item.getKey(), item.getValue()));
|
this.putAll(props);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,38 +1,7 @@
|
|||||||
package net.locusworks.common.properties;
|
package net.locusworks.common.properties;
|
||||||
|
|
||||||
/*
|
import java.io.*;
|
||||||
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
|
import java.nio.charset.StandardCharsets;
|
||||||
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
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.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
@@ -67,7 +36,7 @@ import java.util.Set;
|
|||||||
* {@link #store(java.io.Writer, java.lang.String) store(Writer, String)}
|
* {@link #store(java.io.Writer, java.lang.String) store(Writer, String)}
|
||||||
* methods load and store properties from and to a character based stream
|
* methods load and store properties from and to a character based stream
|
||||||
* in a simple line-oriented format specified below.
|
* in a simple line-oriented format specified below.
|
||||||
*
|
* <p>
|
||||||
* The {@link #load(java.io.InputStream) load(InputStream)} <tt>/</tt>
|
* The {@link #load(java.io.InputStream) load(InputStream)} <tt>/</tt>
|
||||||
* {@link #store(java.io.OutputStream, java.lang.String) store(OutputStream, String)}
|
* {@link #store(java.io.OutputStream, java.lang.String) store(OutputStream, String)}
|
||||||
* methods work the same way as the load(Reader)/store(Writer, String) pair, except
|
* methods work the same way as the load(Reader)/store(Writer, String) pair, except
|
||||||
@@ -111,18 +80,18 @@ import java.util.Set;
|
|||||||
* <p>This class is thread-safe: multiple threads can share a single
|
* <p>This class is thread-safe: multiple threads can share a single
|
||||||
* <tt>Properties</tt> object without the need for external synchronization.
|
* <tt>Properties</tt> object without the need for external synchronization.
|
||||||
*
|
*
|
||||||
* @see <a href="../../../technotes/tools/solaris/native2ascii.html">native2ascii tool for Solaris</a>
|
|
||||||
* @see <a href="../../../technotes/tools/windows/native2ascii.html">native2ascii tool for Windows</a>
|
|
||||||
*
|
|
||||||
* @author Arthur van Hoff
|
* @author Arthur van Hoff
|
||||||
* @author Michael McCloskey
|
* @author Michael McCloskey
|
||||||
* @author Xueming Shen
|
* @author Xueming Shen
|
||||||
|
* @see <a href="../../../technotes/tools/solaris/native2ascii.html">native2ascii tool for Solaris</a>
|
||||||
|
* @see <a href="../../../technotes/tools/windows/native2ascii.html">native2ascii tool for Windows</a>
|
||||||
* @since JDK1.0
|
* @since JDK1.0
|
||||||
*/
|
*/
|
||||||
public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
public class OrderedProperties extends LinkedHashMap<Object, Object> {
|
||||||
/**
|
/**
|
||||||
* use serialVersionUID from JDK 1.1.X for interoperability
|
* use serialVersionUID from JDK 1.1.X for interoperability
|
||||||
*/
|
*/
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = 4112578634023874840L;
|
private static final long serialVersionUID = 4112578634023874840L;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -224,9 +193,9 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* terminator. All of these key termination characters may be
|
* terminator. All of these key termination characters may be
|
||||||
* included in the key by escaping them with a preceding backslash
|
* included in the key by escaping them with a preceding backslash
|
||||||
* character; for example,<p>
|
* character; for example,<p>
|
||||||
*
|
* <p>
|
||||||
* {@code \:\=}<p>
|
* {@code \:\=}<p>
|
||||||
*
|
* <p>
|
||||||
* would be the two-character key {@code ":="}. Line
|
* would be the two-character key {@code ":="}. Line
|
||||||
* terminator characters can be included using {@code \r} and
|
* terminator characters can be included using {@code \r} and
|
||||||
* {@code \n} escape sequences. Any white space after the
|
* {@code \n} escape sequences. Any white space after the
|
||||||
@@ -247,7 +216,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* <pre>
|
* <pre>
|
||||||
* Truth = Beauty
|
* Truth = Beauty
|
||||||
* Truth:Beauty
|
* Truth:Beauty
|
||||||
* Truth :Beauty
|
* Truth: Beauty
|
||||||
* </pre>
|
* </pre>
|
||||||
* As another example, the following three lines specify a single
|
* As another example, the following three lines specify a single
|
||||||
* property:
|
* property:
|
||||||
@@ -275,7 +244,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* sequences similar to those used for character and string literals
|
* sequences similar to those used for character and string literals
|
||||||
* (see sections 3.3 and 3.10.6 of
|
* (see sections 3.3 and 3.10.6 of
|
||||||
* <cite>The Java™ Language Specification</cite>).
|
* <cite>The Java™ Language Specification</cite>).
|
||||||
*
|
* <p>
|
||||||
* The differences from the character escape sequences and Unicode
|
* The differences from the character escape sequences and Unicode
|
||||||
* escapes used for characters and strings are:
|
* escapes used for characters and strings are:
|
||||||
*
|
*
|
||||||
@@ -331,7 +300,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* The specified stream remains open after this method returns.
|
* The specified stream remains open after this method returns.
|
||||||
*
|
*
|
||||||
* @param inStream the input stream.
|
* @param inStream the input stream.
|
||||||
* @exception IOException if an error occurred when reading from the
|
* @throws IOException if an error occurred when reading from the
|
||||||
* input stream.
|
* input stream.
|
||||||
* @throws IllegalArgumentException if the input stream contains a
|
* @throws IllegalArgumentException if the input stream contains a
|
||||||
* malformed Unicode escape sequence.
|
* malformed Unicode escape sequence.
|
||||||
@@ -341,7 +310,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
load0(new LineReader(inStream));
|
load0(new LineReader(inStream));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void load0 (LineReader lr) throws IOException {
|
private void load0(LineReader lr) throws IOException {
|
||||||
char[] convtBuf = new char[1024];
|
char[] convtBuf = new char[1024];
|
||||||
int limit;
|
int limit;
|
||||||
int keyLen;
|
int keyLen;
|
||||||
@@ -399,7 +368,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* Method returns the char length of the "logical line" and stores
|
* Method returns the char length of the "logical line" and stores
|
||||||
* the line in "lineBuf".
|
* the line in "lineBuf".
|
||||||
*/
|
*/
|
||||||
class LineReader {
|
static class LineReader {
|
||||||
public LineReader(InputStream inStream) {
|
public LineReader(InputStream inStream) {
|
||||||
this.inStream = inStream;
|
this.inStream = inStream;
|
||||||
inByteBuf = new byte[8192];
|
inByteBuf = new byte[8192];
|
||||||
@@ -431,8 +400,8 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
if (inOff >= inLimit) {
|
if (inOff >= inLimit) {
|
||||||
inLimit = (inStream==null)?reader.read(inCharBuf)
|
inLimit = (inStream == null) ? reader.read(inCharBuf)
|
||||||
:inStream.read(inByteBuf);
|
: inStream.read(inByteBuf);
|
||||||
inOff = 0;
|
inOff = 0;
|
||||||
if (inLimit <= 0) {
|
if (inLimit <= 0) {
|
||||||
if (len == 0 || isCommentLine) {
|
if (len == 0 || isCommentLine) {
|
||||||
@@ -479,9 +448,6 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
lineBuf[len++] = c;
|
lineBuf[len++] = c;
|
||||||
if (len == lineBuf.length) {
|
if (len == lineBuf.length) {
|
||||||
int newLength = lineBuf.length * 2;
|
int newLength = lineBuf.length * 2;
|
||||||
if (newLength < 0) {
|
|
||||||
newLength = Integer.MAX_VALUE;
|
|
||||||
}
|
|
||||||
char[] buf = new char[newLength];
|
char[] buf = new char[newLength];
|
||||||
System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
|
System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
|
||||||
lineBuf = buf;
|
lineBuf = buf;
|
||||||
@@ -492,10 +458,9 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
} else {
|
} else {
|
||||||
precedingBackslash = false;
|
precedingBackslash = false;
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
// reached EOL
|
// reached EOL
|
||||||
if (isCommentLine || len == 0) {
|
if (isCommentLine) {
|
||||||
isCommentLine = false;
|
isCommentLine = false;
|
||||||
isNewLine = true;
|
isNewLine = true;
|
||||||
skipWhiteSpace = true;
|
skipWhiteSpace = true;
|
||||||
@@ -503,9 +468,9 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (inOff >= inLimit) {
|
if (inOff >= inLimit) {
|
||||||
inLimit = (inStream==null)
|
inLimit = (inStream == null)
|
||||||
?reader.read(inCharBuf)
|
? reader.read(inCharBuf)
|
||||||
:inStream.read(inByteBuf);
|
: inStream.read(inByteBuf);
|
||||||
inOff = 0;
|
inOff = 0;
|
||||||
if (inLimit <= 0) {
|
if (inLimit <= 0) {
|
||||||
if (precedingBackslash) {
|
if (precedingBackslash) {
|
||||||
@@ -535,12 +500,9 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* Converts encoded \uxxxx to unicode chars
|
* Converts encoded \uxxxx to unicode chars
|
||||||
* and changes special saved chars to their original forms
|
* and changes special saved chars to their original forms
|
||||||
*/
|
*/
|
||||||
private String loadConvert (char[] in, int off, int len, char[] convtBuf) {
|
private String loadConvert(char[] in, int off, int len, char[] convtBuf) {
|
||||||
if (convtBuf.length < len) {
|
if (convtBuf.length < len) {
|
||||||
int newLen = len * 2;
|
int newLen = len * 2;
|
||||||
if (newLen < 0) {
|
|
||||||
newLen = Integer.MAX_VALUE;
|
|
||||||
}
|
|
||||||
convtBuf = new char[newLen];
|
convtBuf = new char[newLen];
|
||||||
}
|
}
|
||||||
char aChar;
|
char aChar;
|
||||||
@@ -552,30 +514,20 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
aChar = in[off++];
|
aChar = in[off++];
|
||||||
if (aChar == '\\') {
|
if (aChar == '\\') {
|
||||||
aChar = in[off++];
|
aChar = in[off++];
|
||||||
if(aChar == 'u') {
|
if (aChar == 'u') {
|
||||||
// Read the xxxx
|
// Read the xxxx
|
||||||
int value=0;
|
int value = 0;
|
||||||
for (int i=0; i<4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
aChar = in[off++];
|
aChar = in[off++];
|
||||||
switch (aChar) {
|
value = switch (aChar) {
|
||||||
case '0': case '1': case '2': case '3': case '4':
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> (value << 4) + aChar - '0';
|
||||||
case '5': case '6': case '7': case '8': case '9':
|
case 'a', 'b', 'c', 'd', 'e', 'f' -> (value << 4) + 10 + aChar - 'a';
|
||||||
value = (value << 4) + aChar - '0';
|
case 'A', 'B', 'C', 'D', 'E', 'F' -> (value << 4) + 10 + aChar - 'A';
|
||||||
break;
|
default -> throw new IllegalArgumentException(
|
||||||
case 'a': case 'b': case 'c':
|
|
||||||
case 'd': case 'e': case 'f':
|
|
||||||
value = (value << 4) + 10 + aChar - 'a';
|
|
||||||
break;
|
|
||||||
case 'A': case 'B': case 'C':
|
|
||||||
case 'D': case 'E': case 'F':
|
|
||||||
value = (value << 4) + 10 + aChar - 'A';
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"Malformed \\uxxxx encoding.");
|
"Malformed \\uxxxx encoding.");
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
out[outLen++] = (char) value;
|
||||||
out[outLen++] = (char)value;
|
|
||||||
} else {
|
} else {
|
||||||
if (aChar == 't') aChar = '\t';
|
if (aChar == 't') aChar = '\t';
|
||||||
else if (aChar == 'r') aChar = '\r';
|
else if (aChar == 'r') aChar = '\r';
|
||||||
@@ -587,7 +539,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
out[outLen++] = aChar;
|
out[outLen++] = aChar;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new String (out, 0, outLen);
|
return new String(out, 0, outLen);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -599,51 +551,58 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
boolean escapeUnicode) {
|
boolean escapeUnicode) {
|
||||||
int len = theString.length();
|
int len = theString.length();
|
||||||
int bufLen = len * 2;
|
int bufLen = len * 2;
|
||||||
if (bufLen < 0) {
|
|
||||||
bufLen = Integer.MAX_VALUE;
|
|
||||||
}
|
|
||||||
StringBuffer outBuffer = new StringBuffer(bufLen);
|
StringBuffer outBuffer = new StringBuffer(bufLen);
|
||||||
|
|
||||||
for(int x=0; x<len; x++) {
|
for (int x = 0; x < len; x++) {
|
||||||
char aChar = theString.charAt(x);
|
char aChar = theString.charAt(x);
|
||||||
// Handle common case first, selecting largest block that
|
// Handle common case first, selecting largest block that
|
||||||
// avoids the specials below
|
// avoids the specials below
|
||||||
if ((aChar > 61) && (aChar < 127)) {
|
if ((aChar > 61) && (aChar < 127)) {
|
||||||
if (aChar == '\\') {
|
if (aChar == '\\') {
|
||||||
outBuffer.append('\\'); outBuffer.append('\\');
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append('\\');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
outBuffer.append(aChar);
|
outBuffer.append(aChar);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
switch(aChar) {
|
switch (aChar) {
|
||||||
case ' ':
|
case ' ':
|
||||||
if (x == 0 || escapeSpace)
|
if (x == 0 || escapeSpace)
|
||||||
outBuffer.append('\\');
|
outBuffer.append('\\');
|
||||||
outBuffer.append(' ');
|
outBuffer.append(' ');
|
||||||
break;
|
break;
|
||||||
case '\t':outBuffer.append('\\'); outBuffer.append('t');
|
case '\t':
|
||||||
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append('t');
|
||||||
break;
|
break;
|
||||||
case '\n':outBuffer.append('\\'); outBuffer.append('n');
|
case '\n':
|
||||||
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append('n');
|
||||||
break;
|
break;
|
||||||
case '\r':outBuffer.append('\\'); outBuffer.append('r');
|
case '\r':
|
||||||
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append('r');
|
||||||
break;
|
break;
|
||||||
case '\f':outBuffer.append('\\'); outBuffer.append('f');
|
case '\f':
|
||||||
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append('f');
|
||||||
break;
|
break;
|
||||||
case '=': // Fall through
|
case '=': // Fall through
|
||||||
case ':': // Fall through
|
case ':': // Fall through
|
||||||
case '#': // Fall through
|
case '#': // Fall through
|
||||||
case '!':
|
case '!':
|
||||||
outBuffer.append('\\'); outBuffer.append(aChar);
|
outBuffer.append('\\');
|
||||||
|
outBuffer.append(aChar);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode ) {
|
if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode) {
|
||||||
outBuffer.append('\\');
|
outBuffer.append('\\');
|
||||||
outBuffer.append('u');
|
outBuffer.append('u');
|
||||||
outBuffer.append(toHex((aChar >> 12) & 0xF));
|
outBuffer.append(toHex((aChar >> 12) & 0xF));
|
||||||
outBuffer.append(toHex((aChar >> 8) & 0xF));
|
outBuffer.append(toHex((aChar >> 8) & 0xF));
|
||||||
outBuffer.append(toHex((aChar >> 4) & 0xF));
|
outBuffer.append(toHex((aChar >> 4) & 0xF));
|
||||||
outBuffer.append(toHex( aChar & 0xF));
|
outBuffer.append(toHex(aChar & 0xF));
|
||||||
} else {
|
} else {
|
||||||
outBuffer.append(aChar);
|
outBuffer.append(aChar);
|
||||||
}
|
}
|
||||||
@@ -663,14 +622,14 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
uu[1] = 'u';
|
uu[1] = 'u';
|
||||||
while (current < len) {
|
while (current < len) {
|
||||||
char c = comments.charAt(current);
|
char c = comments.charAt(current);
|
||||||
if (c > '\u00ff' || c == '\n' || c == '\r') {
|
if (c > 'ÿ' || c == '\n' || c == '\r') {
|
||||||
if (last != current)
|
if (last != current)
|
||||||
bw.write(comments.substring(last, current));
|
bw.write(comments.substring(last, current));
|
||||||
if (c > '\u00ff') {
|
if (c > 'ÿ') {
|
||||||
uu[2] = toHex((c >> 12) & 0xf);
|
uu[2] = toHex((c >> 12) & 0xf);
|
||||||
uu[3] = toHex((c >> 8) & 0xf);
|
uu[3] = toHex((c >> 8) & 0xf);
|
||||||
uu[4] = toHex((c >> 4) & 0xf);
|
uu[4] = toHex((c >> 4) & 0xf);
|
||||||
uu[5] = toHex( c & 0xf);
|
uu[5] = toHex(c & 0xf);
|
||||||
bw.write(new String(uu));
|
bw.write(new String(uu));
|
||||||
} else {
|
} else {
|
||||||
bw.newLine();
|
bw.newLine();
|
||||||
@@ -697,23 +656,21 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* Calls the {@code store(OutputStream out, String comments)} method
|
* Calls the {@code store(OutputStream out, String comments)} method
|
||||||
* and suppresses IOExceptions that were thrown.
|
* and suppresses IOExceptions that were thrown.
|
||||||
*
|
*
|
||||||
|
* @param out an output stream.
|
||||||
|
* @throws ClassCastException if this {@code Properties} object
|
||||||
|
* contains any keys or values that are not
|
||||||
|
* {@code Strings}.
|
||||||
* @deprecated This method does not throw an IOException if an I/O error
|
* @deprecated This method does not throw an IOException if an I/O error
|
||||||
* occurs while saving the property list. The preferred way to save a
|
* occurs while saving the property list. The preferred way to save a
|
||||||
* properties list is via the {@code store(OutputStream out,
|
* properties list is via the {@code store(OutputStream out,
|
||||||
* String comments)} method or the
|
* String comments)} method or the
|
||||||
* {@code storeToXML(OutputStream os, String comment)} method.
|
* {@code storeToXML(OutputStream os, String comment)} method.
|
||||||
*
|
|
||||||
* @param out an output stream.
|
|
||||||
* @param comments a description of the property list.
|
|
||||||
* @exception ClassCastException if this {@code Properties} object
|
|
||||||
* contains any keys or values that are not
|
|
||||||
* {@code Strings}.
|
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public void save(OutputStream out, String comments) {
|
public void save(OutputStream out, String comments) {
|
||||||
try {
|
try {
|
||||||
store(out, comments);
|
store(out, comments);
|
||||||
} catch (IOException e) {
|
} catch (IOException ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -758,17 +715,16 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
*
|
*
|
||||||
* @param writer an output character stream writer.
|
* @param writer an output character stream writer.
|
||||||
* @param comments a description of the property list.
|
* @param comments a description of the property list.
|
||||||
* @exception IOException if writing this property list to the specified
|
* @throws IOException if writing this property list to the specified
|
||||||
* output stream throws an <tt>IOException</tt>.
|
* output stream throws an <tt>IOException</tt>.
|
||||||
* @exception ClassCastException if this {@code Properties} object
|
* @throws ClassCastException if this {@code Properties} object
|
||||||
* contains any keys or values that are not {@code Strings}.
|
* contains any keys or values that are not {@code Strings}.
|
||||||
* @exception NullPointerException if {@code writer} is null.
|
* @throws NullPointerException if {@code writer} is null.
|
||||||
* @since 1.6
|
* @since 1.6
|
||||||
*/
|
*/
|
||||||
public void store(Writer writer, String comments)
|
public void store(Writer writer, String comments)
|
||||||
throws IOException
|
throws IOException {
|
||||||
{
|
store0((writer instanceof BufferedWriter) ? (BufferedWriter) writer
|
||||||
store0((writer instanceof BufferedWriter)?(BufferedWriter)writer
|
|
||||||
: new BufferedWriter(writer),
|
: new BufferedWriter(writer),
|
||||||
comments,
|
comments,
|
||||||
false);
|
false);
|
||||||
@@ -803,35 +759,34 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* After the entries have been written, the output stream is flushed.
|
* After the entries have been written, the output stream is flushed.
|
||||||
* The output stream remains open after this method returns.
|
* The output stream remains open after this method returns.
|
||||||
* <p>
|
* <p>
|
||||||
|
*
|
||||||
* @param out an output stream.
|
* @param out an output stream.
|
||||||
* @param comments a description of the property list.
|
* @param comments a description of the property list.
|
||||||
* @exception IOException if writing this property list to the specified
|
* @throws IOException if writing this property list to the specified
|
||||||
* output stream throws an <tt>IOException</tt>.
|
* output stream throws an <tt>IOException</tt>.
|
||||||
* @exception ClassCastException if this {@code Properties} object
|
* @throws ClassCastException if this {@code Properties} object
|
||||||
* contains any keys or values that are not {@code Strings}.
|
* contains any keys or values that are not {@code Strings}.
|
||||||
* @exception NullPointerException if {@code out} is null.
|
* @throws NullPointerException if {@code out} is null.
|
||||||
* @since 1.2
|
* @since 1.2
|
||||||
*/
|
*/
|
||||||
public void store(OutputStream out, String comments)
|
public void store(OutputStream out, String comments)
|
||||||
throws IOException
|
throws IOException {
|
||||||
{
|
store0(new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.ISO_8859_1)),
|
||||||
store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")),
|
|
||||||
comments,
|
comments,
|
||||||
true);
|
true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void store0(BufferedWriter bw, String comments, boolean escUnicode)
|
private void store0(BufferedWriter bw, String comments, boolean escUnicode)
|
||||||
throws IOException
|
throws IOException {
|
||||||
{
|
|
||||||
if (comments != null) {
|
if (comments != null) {
|
||||||
writeComments(bw, comments);
|
writeComments(bw, comments);
|
||||||
}
|
}
|
||||||
bw.write("#" + new Date().toString());
|
bw.write("#" + new Date().toString());
|
||||||
bw.newLine();
|
bw.newLine();
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
for (Enumeration<?> e = keys(); e.hasMoreElements();) {
|
for (Enumeration<?> e = keys(); e.hasMoreElements(); ) {
|
||||||
String key = (String)e.nextElement();
|
String key = (String) e.nextElement();
|
||||||
String val = (String)get(key);
|
String val = (String) get(key);
|
||||||
key = saveConvert(key, true, escUnicode);
|
key = saveConvert(key, true, escUnicode);
|
||||||
/* No need to escape embedded and trailing spaces for value, hence
|
/* No need to escape embedded and trailing spaces for value, hence
|
||||||
* pass false to flag.
|
* pass false to flag.
|
||||||
@@ -857,7 +812,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
*/
|
*/
|
||||||
public String getProperty(String key) {
|
public String getProperty(String key) {
|
||||||
Object oval = super.get(key);
|
Object oval = super.get(key);
|
||||||
String sval = (oval instanceof String) ? (String)oval : null;
|
String sval = (oval instanceof String) ? (String) oval : null;
|
||||||
return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
|
return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -869,7 +824,6 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
*
|
*
|
||||||
* @param key the hashtable key.
|
* @param key the hashtable key.
|
||||||
* @param defaultValue a default value.
|
* @param defaultValue a default value.
|
||||||
*
|
|
||||||
* @return the value in this property list with the specified key value.
|
* @return the value in this property list with the specified key value.
|
||||||
* @see #setProperty
|
* @see #setProperty
|
||||||
* @see #defaults
|
* @see #defaults
|
||||||
@@ -894,7 +848,7 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* @see #stringPropertyNames
|
* @see #stringPropertyNames
|
||||||
*/
|
*/
|
||||||
public Enumeration<?> propertyNames() {
|
public Enumeration<?> propertyNames() {
|
||||||
LinkedHashMap<String,Object> h = new LinkedHashMap<>();
|
LinkedHashMap<String, Object> h = new LinkedHashMap<>();
|
||||||
enumerate(h);
|
enumerate(h);
|
||||||
return Collections.enumeration(h.keySet());
|
return Collections.enumeration(h.keySet());
|
||||||
}
|
}
|
||||||
@@ -932,17 +886,9 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
* is not a string.
|
* is not a string.
|
||||||
*/
|
*/
|
||||||
public void list(PrintStream out) {
|
public void list(PrintStream out) {
|
||||||
out.println("-- listing properties --");
|
PrintWriter writer = new PrintWriter(out);
|
||||||
LinkedHashMap<String,Object> h = new LinkedHashMap<>();
|
list(writer);
|
||||||
enumerate(h);
|
writer.flush();
|
||||||
for (Enumeration<String> e = Collections.enumeration(h.keySet()) ; e.hasMoreElements() ;) {
|
|
||||||
String key = e.nextElement();
|
|
||||||
String val = (String)h.get(key);
|
|
||||||
if (val.length() > 40) {
|
|
||||||
val = val.substring(0, 37) + "...";
|
|
||||||
}
|
|
||||||
out.println(key + "=" + val);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -961,11 +907,11 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
*/
|
*/
|
||||||
public void list(PrintWriter out) {
|
public void list(PrintWriter out) {
|
||||||
out.println("-- listing properties --");
|
out.println("-- listing properties --");
|
||||||
LinkedHashMap<String,Object> h = new LinkedHashMap<>();
|
LinkedHashMap<String, Object> h = new LinkedHashMap<>();
|
||||||
enumerate(h);
|
enumerate(h);
|
||||||
for (Enumeration<String> e = Collections.enumeration(h.keySet()) ; e.hasMoreElements() ;) {
|
for (Enumeration<String> e = Collections.enumeration(h.keySet()); e.hasMoreElements(); ) {
|
||||||
String key = e.nextElement();
|
String key = e.nextElement();
|
||||||
String val = (String)h.get(key);
|
String val = (String) h.get(key);
|
||||||
if (val.length() > 40) {
|
if (val.length() > 40) {
|
||||||
val = val.substring(0, 37) + "...";
|
val = val.substring(0, 37) + "...";
|
||||||
}
|
}
|
||||||
@@ -974,17 +920,18 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enumerates all key/value pairs in the specified hashtable.
|
* Lists all key/value pairs in the specified hashtable.
|
||||||
|
*
|
||||||
* @param h the hashtable
|
* @param h the hashtable
|
||||||
* @throws ClassCastException if any of the property keys
|
* @throws ClassCastException if any of the property keys
|
||||||
* is not of String type.
|
* is not of the String type.
|
||||||
*/
|
*/
|
||||||
private synchronized void enumerate(LinkedHashMap<String,Object> h) {
|
private synchronized void enumerate(LinkedHashMap<String, Object> h) {
|
||||||
if (defaults != null) {
|
if (defaults != null) {
|
||||||
defaults.enumerate(h);
|
defaults.enumerate(h);
|
||||||
}
|
}
|
||||||
for (Enumeration<?> e = keys() ; e.hasMoreElements() ;) {
|
for (Enumeration<?> e = keys(); e.hasMoreElements(); ) {
|
||||||
String key = (String)e.nextElement();
|
String key = (String) e.nextElement();
|
||||||
h.put(key, get(key));
|
h.put(key, get(key));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -996,13 +943,14 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
/**
|
/**
|
||||||
* Enumerates all key/value pairs in the specified hashtable
|
* Enumerates all key/value pairs in the specified hashtable
|
||||||
* and omits the property if the key or value is not a string.
|
* and omits the property if the key or value is not a string.
|
||||||
|
*
|
||||||
* @param h the hashtable
|
* @param h the hashtable
|
||||||
*/
|
*/
|
||||||
private synchronized void enumerateStringProperties(Map<String, String> h) {
|
private synchronized void enumerateStringProperties(Map<String, String> h) {
|
||||||
if (defaults != null) {
|
if (defaults != null) {
|
||||||
defaults.enumerateStringProperties(h);
|
defaults.enumerateStringProperties(h);
|
||||||
}
|
}
|
||||||
for (Enumeration<?> e = keys() ; e.hasMoreElements() ;) {
|
for (Enumeration<?> e = keys(); e.hasMoreElements(); ) {
|
||||||
Object k = e.nextElement();
|
Object k = e.nextElement();
|
||||||
Object v = get(k);
|
Object v = get(k);
|
||||||
if (k instanceof String && v instanceof String) {
|
if (k instanceof String && v instanceof String) {
|
||||||
@@ -1013,14 +961,17 @@ public class OrderedProperties extends LinkedHashMap<Object,Object> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a nibble to a hex character
|
* Convert a nibble to a hex character
|
||||||
|
*
|
||||||
* @param nibble the nibble to convert.
|
* @param nibble the nibble to convert.
|
||||||
*/
|
*/
|
||||||
private static char toHex(int nibble) {
|
private static char toHex(int nibble) {
|
||||||
return hexDigit[(nibble & 0xF)];
|
return hexDigit[(nibble & 0xF)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A table of hex digits */
|
/**
|
||||||
|
* A table of hex digits
|
||||||
|
*/
|
||||||
private static final char[] hexDigit = {
|
private static final char[] hexDigit = {
|
||||||
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
|
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package net.locusworks.common.utils;
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
public class Checks {
|
public class Checks {
|
||||||
|
|
||||||
public static void checkArguments(boolean expression, String error) {
|
public static void checkArguments(boolean expression, String error) {
|
||||||
@@ -19,7 +21,7 @@ public class Checks {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void checkNotNull(Object item, String error) {
|
public static void checkNotNull(Object item, String error) {
|
||||||
if (item == null) throw new IllegalAccessError("Provided item is null");
|
Objects.requireNonNull(item, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,18 @@ package net.locusworks.common.utils;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Class to hold final static constant values used across the system
|
* Class to hold final static constant values used across the system
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
*/
|
*/
|
||||||
public class Constants {
|
public class Constants {
|
||||||
|
|
||||||
public static final short TRUE = (short)1;
|
public static final short TRUE = (short) 1;
|
||||||
public static final short FALSE = (short)0;
|
public static final short FALSE = (short) 0;
|
||||||
|
|
||||||
public static final short EXIT_SUCCESS = (short)0;
|
public static final short EXIT_SUCCESS = (short) 0;
|
||||||
public static final short EXIT_FAIL = (short)1;
|
public static final short EXIT_FAIL = (short) 1;
|
||||||
|
|
||||||
public static final String LOG4J_CONFIG_PROPERTY = "log4j.configurationFile";
|
public static final String LOG4J_CONFIG_PROPERTY = "log4j.configurationFile";
|
||||||
public static final String JUNIT_TEST_CHECK = "junit.test";
|
public static final String JUNIT_TEST_CHECK = "junit.test";
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import java.util.Base64;
|
|||||||
|
|
||||||
import net.locusworks.common.Charsets;
|
import net.locusworks.common.Charsets;
|
||||||
|
|
||||||
public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable{
|
public class DataOutputStreamHelper extends DataOutputStream implements AutoCloseable {
|
||||||
|
|
||||||
public DataOutputStreamHelper() {
|
public DataOutputStreamHelper() {
|
||||||
this(new ByteArrayOutputStream());
|
this(new ByteArrayOutputStream());
|
||||||
@@ -23,7 +23,7 @@ public class DataOutputStreamHelper extends DataOutputStream implements AutoClos
|
|||||||
return new byte[0];
|
return new byte[0];
|
||||||
}
|
}
|
||||||
if (super.out instanceof ByteArrayOutputStream) {
|
if (super.out instanceof ByteArrayOutputStream) {
|
||||||
return ((ByteArrayOutputStream)super.out).toByteArray();
|
return ((ByteArrayOutputStream) super.out).toByteArray();
|
||||||
}
|
}
|
||||||
return super.out.toString().getBytes(Charsets.UTF_8);
|
return super.out.toString().getBytes(Charsets.UTF_8);
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,8 @@ public class DataOutputStreamHelper extends DataOutputStream implements AutoClos
|
|||||||
try {
|
try {
|
||||||
super.out.close();
|
super.out.close();
|
||||||
super.out = null;
|
super.out = null;
|
||||||
} catch (Exception ex) {}
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import com.fasterxml.jackson.databind.JsonDeserializer;
|
|||||||
* </pre>
|
* </pre>
|
||||||
* Will specify to use this deserializer class when a json field {@code purgeEndDate} is encountered in the json
|
* Will specify to use this deserializer class when a json field {@code purgeEndDate} is encountered in the json
|
||||||
* string and will try to convert the string into a date object and inject the value back into the class
|
* string and will try to convert the string into a date object and inject the value back into the class
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
@@ -30,14 +31,14 @@ public class DateTimeStampDeserializer extends JsonDeserializer<Date> {
|
|||||||
private static final String EXPANDED_WITH_TIMEZONE = "MMM d, yyyy HH:mm:ss z";
|
private static final String EXPANDED_WITH_TIMEZONE = "MMM d, yyyy HH:mm:ss z";
|
||||||
private static final String EXPANDED_WITH_AM_PM = "MMM d, yyyy h:mm:ss a";
|
private static final String EXPANDED_WITH_AM_PM = "MMM d, yyyy h:mm:ss a";
|
||||||
|
|
||||||
private static final String[] formats = new String[] {
|
private static final String[] formats = new String[]{
|
||||||
DEFAULT,
|
DEFAULT,
|
||||||
EXPANDED,
|
EXPANDED,
|
||||||
EXPANDED_WITH_TIMEZONE,
|
EXPANDED_WITH_TIMEZONE,
|
||||||
EXPANDED_WITH_AM_PM,
|
EXPANDED_WITH_AM_PM,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static final Integer[] styles = new Integer[] {
|
private static final Integer[] styles = new Integer[]{
|
||||||
SimpleDateFormat.LONG,
|
SimpleDateFormat.LONG,
|
||||||
SimpleDateFormat.FULL,
|
SimpleDateFormat.FULL,
|
||||||
SimpleDateFormat.MEDIUM,
|
SimpleDateFormat.MEDIUM,
|
||||||
@@ -45,25 +46,26 @@ public class DateTimeStampDeserializer extends JsonDeserializer<Date> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
public Date deserialize(JsonParser p, DeserializationContext context) throws IOException {
|
||||||
String value = p.getText();
|
String value = p.getText();
|
||||||
|
|
||||||
Date date = null;
|
Date date;
|
||||||
//First try to see if the value can be parsed into a long
|
//First, try to see if the value can be parsed into along
|
||||||
try {
|
try {
|
||||||
date = new Date(Long.parseLong(value));
|
date = new Date(Long.parseLong(value));
|
||||||
return date;
|
return date;
|
||||||
} catch (Exception ex) { }
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
//Next iterate over the built in styles to see if it can be converted
|
//Next, iterate over the built-in styles to see if it can be converted
|
||||||
for (Integer style: styles) {
|
for (Integer style : styles) {
|
||||||
date = formatDate(style, value);
|
date = formatDate(style, value);
|
||||||
if (date != null) {
|
if (date != null) {
|
||||||
return date;
|
return date;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Lastly iterate over the custom styles specified in format to see if it can be converted
|
//Lastly, iterate over the custom styles specified in format to see if it can be converted
|
||||||
for (String fmt : formats) {
|
for (String fmt : formats) {
|
||||||
date = formatDate(fmt, value);
|
date = formatDate(fmt, value);
|
||||||
if (date != null) {
|
if (date != null) {
|
||||||
@@ -77,6 +79,7 @@ public class DateTimeStampDeserializer extends JsonDeserializer<Date> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a string value to a date object
|
* Convert a string value to a date object
|
||||||
|
*
|
||||||
* @param format The format to use in reference to the source
|
* @param format The format to use in reference to the source
|
||||||
* @param source the source to convert
|
* @param source the source to convert
|
||||||
* @return Date object if the conversion was success; null otherwise
|
* @return Date object if the conversion was success; null otherwise
|
||||||
@@ -92,6 +95,7 @@ public class DateTimeStampDeserializer extends JsonDeserializer<Date> {
|
|||||||
/**
|
/**
|
||||||
* Convert a string value to a date object using SimpleDateFormats
|
* Convert a string value to a date object using SimpleDateFormats
|
||||||
* built in styles
|
* built in styles
|
||||||
|
*
|
||||||
* @param style The style to use
|
* @param style The style to use
|
||||||
* @param source the source to convert
|
* @param source the source to convert
|
||||||
* @return Date object if the conversion was success; null otherwise
|
* @return Date object if the conversion was success; null otherwise
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package net.locusworks.common.utils;
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.Serial;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonGenerator;
|
import com.fasterxml.jackson.core.JsonGenerator;
|
||||||
@@ -18,9 +19,10 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
|||||||
* </pre>
|
* </pre>
|
||||||
* Will specify to use this serializer class when the {@code purgeEndDate} is encountered when converting to json
|
* Will specify to use this serializer class when the {@code purgeEndDate} is encountered when converting to json
|
||||||
* and will try to convert the date object to its timestamp equivalent
|
* and will try to convert the date object to its timestamp equivalent
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @date 02/15/2018
|
|
||||||
* @version 1.0
|
* @version 1.0
|
||||||
|
* @date 02/15/2018
|
||||||
* @see com.fasterxml.jackson.databind.annotation.JsonSerialize
|
* @see com.fasterxml.jackson.databind.annotation.JsonSerialize
|
||||||
* @see com.fasterxml.jackson.databind.ser.std.StdSerializer
|
* @see com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||||
*/
|
*/
|
||||||
@@ -29,6 +31,7 @@ public class DateTimeStampSerializer extends StdSerializer<Date> {
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
@Serial
|
||||||
private static final long serialVersionUID = -4753139740916300831L;
|
private static final long serialVersionUID = -4753139740916300831L;
|
||||||
|
|
||||||
public DateTimeStampSerializer() {
|
public DateTimeStampSerializer() {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package net.locusworks.common.utils;
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
import static net.locusworks.common.Charsets.UTF_8;
|
import static net.locusworks.common.Charsets.UTF_8;
|
||||||
|
import static net.locusworks.common.utils.ObjectUtils.getResourceStream;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -11,11 +12,13 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import net.locusworks.common.interfaces.AutoCloseableIterator;
|
import net.locusworks.common.interfaces.AutoCloseableIterator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class to read in a file that can be used in the try-with-resource block
|
* Class to read in a file that can be used in the try-with-resource block
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
@@ -28,6 +31,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param fileName Name of the file to read
|
* @param fileName Name of the file to read
|
||||||
*/
|
*/
|
||||||
public FileReader(String fileName) {
|
public FileReader(String fileName) {
|
||||||
@@ -36,6 +40,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param file File to read
|
* @param file File to read
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
@@ -45,6 +50,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param file File to read
|
* @param file File to read
|
||||||
*/
|
*/
|
||||||
public FileReader(Path file) {
|
public FileReader(Path file) {
|
||||||
@@ -53,6 +59,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
*
|
||||||
* @param reader Buffered reader to read data from
|
* @param reader Buffered reader to read data from
|
||||||
*/
|
*/
|
||||||
public FileReader(BufferedReader reader) {
|
public FileReader(BufferedReader reader) {
|
||||||
@@ -61,11 +68,15 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialization helper
|
* Initialization helper
|
||||||
|
*
|
||||||
* @param fileName Name of the file to load
|
* @param fileName Name of the file to load
|
||||||
* This will look into the resources directory if it cannot
|
* This will look into the resources directory if it cannot
|
||||||
* find the file directly.
|
* find the file directly.
|
||||||
*/
|
*/
|
||||||
private void init(String fileName) {
|
private void init(String fileName) {
|
||||||
|
if (fileName == null) {
|
||||||
|
throw new IllegalArgumentException("File name cannot be null");
|
||||||
|
}
|
||||||
//check to see if the file exists
|
//check to see if the file exists
|
||||||
Path f = Paths.get(fileName);
|
Path f = Paths.get(fileName);
|
||||||
if (Files.exists(f)) {
|
if (Files.exists(f)) {
|
||||||
@@ -74,14 +85,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Check to see if the file is in the resources directory
|
//Check to see if the file is in the resources directory
|
||||||
InputStream is = this.getClass().getResourceAsStream(fileName);
|
InputStream is = getResourceStream(fileName);
|
||||||
if (is == null) {
|
|
||||||
is = this.getClass().getClassLoader().getResourceAsStream(fileName);
|
|
||||||
}
|
|
||||||
//If it cant be found, throw a runtime exception
|
|
||||||
if (is == null) {
|
|
||||||
throw new IllegalArgumentException("Unable to find resource with name of" + fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8));
|
BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8));
|
||||||
init(br);
|
init(br);
|
||||||
@@ -89,6 +93,7 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializer helper to load file
|
* Initializer helper to load file
|
||||||
|
*
|
||||||
* @param file File to load
|
* @param file File to load
|
||||||
*/
|
*/
|
||||||
private void init(Path file) {
|
private void init(Path file) {
|
||||||
@@ -106,9 +111,13 @@ public class FileReader implements AutoCloseableIterator<FileReader.LineInfo>, I
|
|||||||
/**
|
/**
|
||||||
* Initializer helper for buffered reader
|
* Initializer helper for buffered reader
|
||||||
* This is ultimately where all initializers end as a buffered reader
|
* This is ultimately where all initializers end as a buffered reader
|
||||||
|
*
|
||||||
* @param reader buffered reader to load
|
* @param reader buffered reader to load
|
||||||
*/
|
*/
|
||||||
private void init(BufferedReader reader) {
|
private void init(BufferedReader reader) {
|
||||||
|
if (reader == null) {
|
||||||
|
throw new IllegalArgumentException("Buffered Reader cannot be null");
|
||||||
|
}
|
||||||
this.reader = reader;
|
this.reader = reader;
|
||||||
this.lineNumber = 0;
|
this.lineNumber = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import java.security.MessageDigest;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Wrapper class that leverages java's MessageDigest to hash files
|
* Wrapper class that leverages java's MessageDigest to hash files
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
@@ -37,6 +38,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a string literal
|
* Hash a string literal
|
||||||
|
*
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param data String to hash
|
* @param data String to hash
|
||||||
* @return hash value of the string literal
|
* @return hash value of the string literal
|
||||||
@@ -47,9 +49,10 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a string literal
|
* Hash a string literal
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
*
|
||||||
|
* @param hashType Hash types supported by MessageDigest (i.e., MD5, SHA-1, SHA-512)
|
||||||
* @param data String to hash
|
* @param data String to hash
|
||||||
* @param toLower True to output the hash in lower case. False to output in upper case
|
* @param toLower True to output the hash in lower case. False to output in the upper case
|
||||||
* @return hash value of the string literal
|
* @return hash value of the string literal
|
||||||
*/
|
*/
|
||||||
public static String hash(String hashType, String data, boolean toLower) {
|
public static String hash(String hashType, String data, boolean toLower) {
|
||||||
@@ -64,6 +67,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a file
|
* Hash a file
|
||||||
|
*
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param data File to hash
|
* @param data File to hash
|
||||||
* @return hash value of the file
|
* @return hash value of the file
|
||||||
@@ -79,6 +83,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a file
|
* Hash a file
|
||||||
|
*
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param data File to hash
|
* @param data File to hash
|
||||||
* @param toLower True to output the hash in lower case. False to output in upper case
|
* @param toLower True to output the hash in lower case. False to output in upper case
|
||||||
@@ -94,6 +99,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a byte array
|
* Hash a byte array
|
||||||
|
*
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param data data to hash
|
* @param data data to hash
|
||||||
* @return hash value of the data
|
* @return hash value of the data
|
||||||
@@ -104,6 +110,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash a byte array
|
* Hash a byte array
|
||||||
|
*
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param data data to hash
|
* @param data data to hash
|
||||||
* @param toLower True to output the hash in lower case. False to output in upper case
|
* @param toLower True to output the hash in lower case. False to output in upper case
|
||||||
@@ -115,6 +122,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash an input stream
|
* Hash an input stream
|
||||||
|
*
|
||||||
* @param stream Stream with the data to hash
|
* @param stream Stream with the data to hash
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @return Hash value of the input stream
|
* @return Hash value of the input stream
|
||||||
@@ -125,6 +133,7 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Hash an input stream
|
* Hash an input stream
|
||||||
|
*
|
||||||
* @param stream Stream with the data to hash
|
* @param stream Stream with the data to hash
|
||||||
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
* @param hashType Hash types supported by MessageDigest (i.e MD5, SHA-1, SHA-512)
|
||||||
* @param toLower True to output the hash in lower case. False to output in upper case
|
* @param toLower True to output the hash in lower case. False to output in upper case
|
||||||
@@ -132,7 +141,7 @@ public class HashUtils {
|
|||||||
*/
|
*/
|
||||||
public static String hash(InputStream stream, String hashType, boolean toLower) {
|
public static String hash(InputStream stream, String hashType, boolean toLower) {
|
||||||
MessageDigest digest = null;
|
MessageDigest digest = null;
|
||||||
try(InputStream is = stream) {
|
try (InputStream is = stream) {
|
||||||
digest = MessageDigest.getInstance(hashType);
|
digest = MessageDigest.getInstance(hashType);
|
||||||
|
|
||||||
byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
|
byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
|
||||||
@@ -151,9 +160,10 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode the hash data back to a string
|
* Encode the hash data back to a string
|
||||||
|
*
|
||||||
* @param data Data to encode
|
* @param data Data to encode
|
||||||
* @param toLower output to lower case
|
* @param toLower output to lower case
|
||||||
* @return
|
* @return encoded string
|
||||||
*/
|
*/
|
||||||
private static String encodeHexString(byte[] data, boolean toLower) {
|
private static String encodeHexString(byte[] data, boolean toLower) {
|
||||||
return new String(encodeHex(data, toLower));
|
return new String(encodeHex(data, toLower));
|
||||||
@@ -161,9 +171,10 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode the hash data to a character array
|
* Encode the hash data to a character array
|
||||||
|
*
|
||||||
* @param data Data to encode
|
* @param data Data to encode
|
||||||
* @param toLower output to lower case
|
* @param toLower output to lower case
|
||||||
* @return
|
* @return encoded character array
|
||||||
*/
|
*/
|
||||||
private static char[] encodeHex(byte[] data, boolean toLower) {
|
private static char[] encodeHex(byte[] data, boolean toLower) {
|
||||||
return encodeHex(data, toLower ? DIGITS_LOWER : DIGITS_UPPER);
|
return encodeHex(data, toLower ? DIGITS_LOWER : DIGITS_UPPER);
|
||||||
@@ -171,9 +182,10 @@ public class HashUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Encode the hex to a character array
|
* Encode the hex to a character array
|
||||||
|
*
|
||||||
* @param data Data to encode
|
* @param data Data to encode
|
||||||
* @param toDigits digits to use
|
* @param toDigits digits to use
|
||||||
* @return
|
* @return encoded character array
|
||||||
*/
|
*/
|
||||||
private static char[] encodeHex(byte[] data, char[] toDigits) {
|
private static char[] encodeHex(byte[] data, char[] toDigits) {
|
||||||
int l = data.length;
|
int l = data.length;
|
||||||
|
|||||||
38
src/main/java/net/locusworks/common/utils/ObjectUtils.java
Normal file
38
src/main/java/net/locusworks/common/utils/ObjectUtils.java
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Object Utils. Functions to perform on objects
|
||||||
|
*/
|
||||||
|
public class ObjectUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform an action if an object is not null otherwise do nothing.
|
||||||
|
*
|
||||||
|
* @param object the object to test
|
||||||
|
* @param consumer the consumer to perform.
|
||||||
|
* @param <T> the type
|
||||||
|
*/
|
||||||
|
public static <T> void performIfNotNull(T object, Consumer<T> consumer) {
|
||||||
|
if (Objects.isNull(object)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
consumer.accept(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static InputStream getResourceStream(String resourceName) {
|
||||||
|
InputStream is = ObjectUtils.class.getResourceAsStream(resourceName);
|
||||||
|
if (is == null) {
|
||||||
|
is = ObjectUtils.class.getClassLoader().getResourceAsStream(resourceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is == null) {
|
||||||
|
throw new NullPointerException("Unable to find resource with name of " + resourceName);
|
||||||
|
}
|
||||||
|
return is;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package net.locusworks.common.utils;
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
@@ -17,34 +18,30 @@ public class RandomString {
|
|||||||
private Random random;
|
private Random random;
|
||||||
|
|
||||||
private char[] symbols;
|
private char[] symbols;
|
||||||
private int length;
|
|
||||||
|
|
||||||
private static RandomString instance;
|
private static RandomString instance;
|
||||||
|
|
||||||
private RandomString(Integer length) {
|
private RandomString() {
|
||||||
this(length, new SecureRandom());
|
Random random;
|
||||||
|
try {
|
||||||
|
random = SecureRandom.getInstance("SHA1PRNG");
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
random = new SecureRandom();
|
||||||
|
}
|
||||||
|
init(random);
|
||||||
}
|
}
|
||||||
|
|
||||||
private RandomString(Integer length, Random random) {
|
private RandomString(Random random) {
|
||||||
this(length, random, ALPHA_NUMERIC);
|
init(random);
|
||||||
}
|
}
|
||||||
|
|
||||||
private RandomString(Integer length, Random random, String symbols) {
|
private void init(Random random) {
|
||||||
if (length < 1) throw new IllegalArgumentException("Length has to be greater than 1");
|
this.random = Objects.requireNonNull(random, "Random generator cannot be null");
|
||||||
if (symbols.length() < 2) throw new IllegalArgumentException("Symbols need to be greater than 2");
|
this.symbols = ALPHA_NUMERIC.toCharArray();
|
||||||
this.random = Objects.requireNonNull(random);
|
|
||||||
this.symbols = symbols.toCharArray();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized final void setRandom(Random random) {
|
private String nextString(int length) {
|
||||||
this.random = random;
|
if (length < 1) throw new IllegalArgumentException("String Length has to be greater than 0");
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized final void setLength(int length) {
|
|
||||||
this.length = length;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String nextString() {
|
|
||||||
char[] buffer = new char[length];
|
char[] buffer = new char[length];
|
||||||
for (int index = 0; index < buffer.length; index++) {
|
for (int index = 0; index < buffer.length; index++) {
|
||||||
buffer[index] = symbols[random.nextInt(symbols.length)];
|
buffer[index] = symbols[random.nextInt(symbols.length)];
|
||||||
@@ -52,28 +49,28 @@ public class RandomString {
|
|||||||
return new String(buffer);
|
return new String(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getString(Integer length) {
|
public String getString(Integer length) {
|
||||||
if (instance == null) {
|
return this.nextString(length);
|
||||||
instance = new RandomString(length);
|
|
||||||
}
|
|
||||||
instance.setLength(length);
|
|
||||||
return instance.nextString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getString(Integer length, Random random) {
|
public byte[] getBytes(Integer length) {
|
||||||
if (instance == null) {
|
|
||||||
instance = new RandomString(length);
|
|
||||||
}
|
|
||||||
instance.setLength(length);
|
|
||||||
instance.setRandom(random);
|
|
||||||
return instance.nextString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static byte[] getBytes(Integer length) {
|
|
||||||
return getString(length).getBytes(UTF_8);
|
return getString(length).getBytes(UTF_8);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] getBytes(Integer length, Random random) {
|
public static RandomString getInstance() {
|
||||||
return getString(length, random).getBytes(UTF_8);
|
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,87 @@ import java.util.Map;
|
|||||||
import static net.locusworks.common.utils.Checks.checkArguments;
|
import static net.locusworks.common.utils.Checks.checkArguments;
|
||||||
import static net.locusworks.common.utils.Checks.checkNotNull;
|
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 {
|
public class Splitter {
|
||||||
|
private enum SplitterType {
|
||||||
|
PARTITION,
|
||||||
|
SEQUENCE
|
||||||
|
}
|
||||||
|
|
||||||
private String splitSeq;
|
private String splitSeq;
|
||||||
private boolean omitEmptyStrings = false;
|
private boolean omitEmptyStrings = false;
|
||||||
private int partition;
|
private int partition;
|
||||||
private int limit;
|
private int limit;
|
||||||
|
private final SplitterType splitterType;
|
||||||
private static Splitter splitter;
|
private static Splitter splitter;
|
||||||
|
|
||||||
private Splitter(String seq) {
|
private Splitter(String seq) {
|
||||||
this.splitSeq = seq;
|
this.splitSeq = seq;
|
||||||
|
this.splitterType = SplitterType.SEQUENCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Splitter(int partition) {
|
private Splitter(int partition) {
|
||||||
this.partition = partition;
|
this.partition = partition;
|
||||||
|
this.splitterType = SplitterType.PARTITION;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove empty string from the resulting lists
|
||||||
|
*
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public Splitter omitEmptyStrings() {
|
public Splitter omitEmptyStrings() {
|
||||||
this.omitEmptyStrings = true;
|
this.omitEmptyStrings = true;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a subset of the resulting list
|
||||||
|
*
|
||||||
|
* @param limit how many items to retrieve
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public Splitter withLimit(int limit) {
|
public Splitter withLimit(int limit) {
|
||||||
this.limit = limit;
|
this.limit = limit;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MapSplitter withKeyValueSeparator(String separator) {
|
/**
|
||||||
checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null");
|
* Return an array instead of a list
|
||||||
return new MapSplitter(this, separator);
|
*
|
||||||
}
|
* @param sentence the string sentence to split
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public String[] splitToArray(String sentence) {
|
public String[] splitToArray(String sentence) {
|
||||||
List<String> list = split(sentence);
|
List<String> list = split(sentence);
|
||||||
return list.toArray(new String[list.size()]);
|
return list.toArray(new String[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split the string
|
||||||
|
*
|
||||||
|
* @param sentence the string to split
|
||||||
|
* @return the resulting list.
|
||||||
|
*/
|
||||||
public List<String> split(String sentence) {
|
public List<String> split(String sentence) {
|
||||||
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
|
checkArguments(!Utils.isEmptyString(sentence), "provided value is null or empty");
|
||||||
List<String> list = new ArrayList<>();
|
List<String> list = new ArrayList<>();
|
||||||
|
|
||||||
if (!Utils.isEmptyString(splitSeq))
|
if (splitterType == SplitterType.PARTITION) {
|
||||||
populateForTrimmer(sentence, list);
|
|
||||||
else
|
|
||||||
populateForFixedWidth(sentence, list);
|
populateForFixedWidth(sentence, list);
|
||||||
|
} else {
|
||||||
|
populateForTrimmer(sentence, list);
|
||||||
|
}
|
||||||
|
|
||||||
return limit > 0 ? list.subList(0, limit) : list;
|
return limit > 0 ? list.subList(0, limit) : list;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void populateForFixedWidth(String sentence, List<String> list) {
|
private void populateForFixedWidth(String sentence, List<String> list) {
|
||||||
|
checkArguments(partition > 0, "Partition should be greater than 0");
|
||||||
int strLength = sentence.length();
|
int strLength = sentence.length();
|
||||||
for (int i = 0; i < strLength; i += partition) {
|
for (int i = 0; i < strLength; i += partition) {
|
||||||
list.add(sentence.substring(i, Math.min(strLength, i + partition)));
|
list.add(sentence.substring(i, Math.min(strLength, i + partition)));
|
||||||
@@ -65,41 +96,74 @@ public class Splitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void populateForTrimmer(String sentence, List<String> list) {
|
private void populateForTrimmer(String sentence, List<String> list) {
|
||||||
|
checkNotNull(splitSeq, "Split value provided was null");
|
||||||
for (String s : sentence.split(splitSeq)) {
|
for (String s : sentence.split(splitSeq)) {
|
||||||
if (s == null || (omitEmptyStrings && s.trim().isEmpty())) continue;
|
if (omitEmptyStrings && s.trim().isEmpty())
|
||||||
|
continue;
|
||||||
list.add(s.trim());
|
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) {
|
public static Splitter fixedLengthSplit(int partition) {
|
||||||
checkArguments(partition > 0, "Partition has to be greater than 0");
|
|
||||||
splitter = new Splitter(partition);
|
splitter = new Splitter(partition);
|
||||||
return splitter;
|
return splitter;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split the length on a specified string sequence
|
||||||
|
*
|
||||||
|
* @param split the sequence to split
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public static Splitter on(String split) {
|
public static Splitter on(String split) {
|
||||||
checkNotNull(split, "Split value provided was null");
|
|
||||||
splitter = new Splitter(split);
|
splitter = new Splitter(split);
|
||||||
return splitter;
|
return splitter;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split on new line sequence
|
||||||
|
*
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public static Splitter onNewLine() {
|
public static Splitter onNewLine() {
|
||||||
return on("\\r?\\n");
|
return on("\\r?\\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split on spaces
|
||||||
|
*
|
||||||
|
* @return this
|
||||||
|
*/
|
||||||
public static Splitter onSpace() {
|
public static Splitter onSpace() {
|
||||||
return on(" ");
|
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 {
|
public static class MapSplitter {
|
||||||
|
|
||||||
private Splitter splitter;
|
private final Splitter splitter;
|
||||||
private String separator;
|
private final String separator;
|
||||||
private boolean skipInvalid = false;
|
private boolean skipInvalid = false;
|
||||||
|
|
||||||
private MapSplitter(Splitter splitter, String separator) {
|
private MapSplitter(Splitter splitter, String separator) {
|
||||||
checkNotNull(splitter, "Splitter cannot be null");
|
checkNotNull(splitter, "Splitter cannot be null");
|
||||||
checkArguments(!Utils.isEmptyString(separator), "Key value separator cannot be empty or null");
|
checkArguments(!Utils.isEmptyString(separator),
|
||||||
|
"Key value separator cannot be empty or null");
|
||||||
this.splitter = splitter;
|
this.splitter = splitter;
|
||||||
this.separator = separator;
|
this.separator = separator;
|
||||||
}
|
}
|
||||||
@@ -118,7 +182,8 @@ public class Splitter {
|
|||||||
try {
|
try {
|
||||||
checkArguments(keyValue.length == 2, "invalid length found for key value mapping");
|
checkArguments(keyValue.length == 2, "invalid length found for key value mapping");
|
||||||
} catch (IllegalArgumentException ex) {
|
} catch (IllegalArgumentException ex) {
|
||||||
if (!skipInvalid) throw ex;
|
if (!skipInvalid)
|
||||||
|
throw ex;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
map.put(keyValue[0], keyValue[1]);
|
map.put(keyValue[0], keyValue[1]);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import java.util.stream.StreamSupport;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility class to make iterators streamable
|
* Utility class to make iterators streamable
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
* @date 02/15/2018
|
* @date 02/15/2018
|
||||||
@@ -14,7 +15,8 @@ import java.util.stream.StreamSupport;
|
|||||||
public class StreamUtils {
|
public class StreamUtils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a iterator to a stream
|
* Convert an iterator to a stream
|
||||||
|
*
|
||||||
* @param iterator the iterator to convert
|
* @param iterator the iterator to convert
|
||||||
* @param <T> the class type
|
* @param <T> the class type
|
||||||
* @return stream of the iterator
|
* @return stream of the iterator
|
||||||
@@ -29,6 +31,7 @@ public class StreamUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an array to a stream
|
* Converts an array to a stream
|
||||||
|
*
|
||||||
* @param items the items to convert
|
* @param items the items to convert
|
||||||
* @param <T> the class type
|
* @param <T> the class type
|
||||||
* @return stream of the array
|
* @return stream of the array
|
||||||
@@ -39,6 +42,7 @@ public class StreamUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an array to a stream
|
* Converts an array to a stream
|
||||||
|
*
|
||||||
* @param items the items to convert
|
* @param items the items to convert
|
||||||
* @param parallel make the stream parallel if set to true
|
* @param parallel make the stream parallel if set to true
|
||||||
* @param <T> the class type
|
* @param <T> the class type
|
||||||
@@ -54,6 +58,7 @@ public class StreamUtils {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert an iterator to a stream
|
* Convert an iterator to a stream
|
||||||
|
*
|
||||||
* @param iterator iterator to convert
|
* @param iterator iterator to convert
|
||||||
* @param parallel make the stream parallel if set to true.
|
* @param parallel make the stream parallel if set to true.
|
||||||
* @param <T> the class type
|
* @param <T> the class type
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ package net.locusworks.common.utils;
|
|||||||
*/
|
*/
|
||||||
public class Success {
|
public class Success {
|
||||||
private boolean success = true;
|
private boolean success = true;
|
||||||
private Object body;
|
private final Object body;
|
||||||
|
|
||||||
protected Success() {
|
protected Success() {
|
||||||
this(true, true);
|
this(true, true);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,165 @@
|
|||||||
|
package net.locusworks.common.configuration;
|
||||||
|
|
||||||
|
import net.locusworks.common.exceptions.ApplicationException;
|
||||||
|
import net.locusworks.common.interfaces.PersistableRequest;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
class ConfigurationCoverageTest {
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
static class Manager extends ConfigurationManager {
|
||||||
|
void initialize(Path base, byte[] key, ConfigurationCallback callback) throws Exception {
|
||||||
|
init(base.toString(), "test.properties", key, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void initialize(Path base, ConfigurationCallback callback) throws Exception {
|
||||||
|
init(base.toString(), "test.properties", callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Request implements PersistableRequest {
|
||||||
|
private String dbHost;
|
||||||
|
private String dbPort;
|
||||||
|
private String ignored;
|
||||||
|
|
||||||
|
Request(String dbHost, String dbPort, String ignored) {
|
||||||
|
this.dbHost = dbHost;
|
||||||
|
this.dbPort = dbPort;
|
||||||
|
this.ignored = ignored;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void managerCreatesLoadsReconcilesSavesAndReportsConfiguration() throws Exception {
|
||||||
|
List<String> messages = new ArrayList<>();
|
||||||
|
Manager manager = new Manager();
|
||||||
|
manager.initialize(tempDir, "seed".getBytes(), messages::add);
|
||||||
|
|
||||||
|
assertEquals("localhost", manager.getPropertyValue("dbHost"));
|
||||||
|
assertEquals("fallback", manager.getPropertyValue("missing", "fallback"));
|
||||||
|
assertNull(manager.getPropertyValue("missing"));
|
||||||
|
assertEquals(4, manager.getConfiguration().size());
|
||||||
|
assertTrue(Files.exists(tempDir.resolve("test.properties")));
|
||||||
|
assertTrue(messages.stream().anyMatch(m -> m.contains("Added new configuration")));
|
||||||
|
|
||||||
|
Properties changed = new Properties();
|
||||||
|
changed.putAll(manager.getConfiguration());
|
||||||
|
changed.setProperty("dbHost", "remote");
|
||||||
|
changed.setProperty("obsolete", "remove me");
|
||||||
|
manager.saveToConf(changed);
|
||||||
|
assertEquals("remote", manager.getPropertyValue("dbHost"));
|
||||||
|
assertFalse(manager.getConfiguration().containsKey("obsolete"));
|
||||||
|
assertTrue(messages.stream().anyMatch(m -> m.contains("Saved config file")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void managerPersistsSelectedPlainAndEncryptedFieldsAndSkipsUnchangedOnes() throws Exception {
|
||||||
|
Manager manager = new Manager();
|
||||||
|
manager.initialize(tempDir, new byte[0], null);
|
||||||
|
|
||||||
|
assertThrows(ApplicationException.class,
|
||||||
|
() -> manager.saveConfiguration(new Request("x", "1", "x"), null, null));
|
||||||
|
assertThrows(ApplicationException.class,
|
||||||
|
() -> manager.saveConfiguration(new Request("x", "1", "x"), Set.of(), null));
|
||||||
|
|
||||||
|
manager.saveConfiguration(new Request("new-host", "3306", "ignored"),
|
||||||
|
Set.of("dbHost", "dbPort"), null);
|
||||||
|
assertEquals("new-host", manager.getPropertyValue("dbHost"));
|
||||||
|
assertEquals("3306", manager.getPropertyValue("dbPort"));
|
||||||
|
|
||||||
|
manager.saveConfiguration(new Request("encrypted-host", "3306", "ignored"),
|
||||||
|
Set.of("dbHost", "dbPort", "ignored"), Set.of("dbHost"));
|
||||||
|
assertNotEquals("encrypted-host", manager.getPropertyValue("dbHost"));
|
||||||
|
|
||||||
|
assertThrows(ApplicationException.class,
|
||||||
|
() -> manager.saveConfiguration(null, Set.of("dbHost"), Set.of()));
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> manager.saveConfiguration(
|
||||||
|
new Request("ignored", "3306", "ignored"), Set.of("dbPort"), Set.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void managerConvenienceInitializationAndBothLoadFailuresAreCovered() throws Exception {
|
||||||
|
Path convenience = Files.createDirectory(tempDir.resolve("convenience"));
|
||||||
|
Manager normal = new Manager();
|
||||||
|
normal.initialize(convenience, null);
|
||||||
|
assertNotNull(normal.getConfiguration());
|
||||||
|
|
||||||
|
try (MockedStatic<PropertiesManager> properties = mockStatic(PropertiesManager.class, CALLS_REAL_METHODS)) {
|
||||||
|
properties.when(() -> PropertiesManager.loadConfiguration(Manager.class, "test.properties"))
|
||||||
|
.thenThrow(new java.io.IOException("template failed"));
|
||||||
|
assertThrows(java.io.IOException.class,
|
||||||
|
() -> new Manager().initialize(tempDir, "seed".getBytes(), null));
|
||||||
|
}
|
||||||
|
|
||||||
|
Path activeFailure = Files.createDirectory(tempDir.resolve("active-failure"));
|
||||||
|
try (MockedStatic<PropertiesManager> properties = mockStatic(PropertiesManager.class, CALLS_REAL_METHODS)) {
|
||||||
|
Path activeFile = activeFailure.resolve("test.properties");
|
||||||
|
properties.when(() -> PropertiesManager.loadConfiguration(activeFile))
|
||||||
|
.thenThrow(new java.io.IOException("active failed"));
|
||||||
|
Manager recovered = new Manager();
|
||||||
|
recovered.initialize(activeFailure, "seed".getBytes(), null);
|
||||||
|
assertEquals(4, recovered.getConfiguration().size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
|
void propertiesManagerCoversResourcesFilesReadersMergeRemovalAndSaveFailures() throws Exception {
|
||||||
|
assertNotNull(new PropertiesManager());
|
||||||
|
assertNull(PropertiesManager.loadConfiguration(getClass(), "missing.properties"));
|
||||||
|
Properties resource = PropertiesManager.loadConfiguration(getClass(), "/test.properties");
|
||||||
|
assertEquals(4, resource.size());
|
||||||
|
|
||||||
|
Path missing = tempDir.resolve("missing.properties");
|
||||||
|
assertTrue(PropertiesManager.loadConfiguration(missing).isEmpty());
|
||||||
|
|
||||||
|
Properties parsed = PropertiesManager.loadConfiguration(
|
||||||
|
new BufferedReader(new StringReader("one=1\ntwo=2")));
|
||||||
|
assertEquals("1", parsed.getProperty("one"));
|
||||||
|
|
||||||
|
Properties destination = new Properties();
|
||||||
|
destination.setProperty("one", "existing");
|
||||||
|
Properties additions = new Properties();
|
||||||
|
additions.setProperty("one", "replacement");
|
||||||
|
additions.setProperty("two", "2");
|
||||||
|
assertEquals(1, PropertiesManager.addConfiguration(destination, additions).size());
|
||||||
|
assertEquals("existing", destination.getProperty("one"));
|
||||||
|
|
||||||
|
destination.setProperty("obsolete", "old");
|
||||||
|
Properties expected = new Properties();
|
||||||
|
expected.setProperty("one", "existing");
|
||||||
|
assertEquals(2, PropertiesManager.removeConfiguration(destination, expected).size());
|
||||||
|
assertEquals(Set.of("one"), destination.keySet());
|
||||||
|
|
||||||
|
Path saved = tempDir.resolve("saved.properties");
|
||||||
|
PropertiesManager.saveConfiguration(expected, saved.toFile(), null);
|
||||||
|
assertEquals("existing", PropertiesManager.loadConfiguration(saved.toFile()).getProperty("one"));
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> PropertiesManager.saveConfiguration(expected, tempDir, "failure"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package net.locusworks.common.crypto;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
|
||||||
|
class AESAndHashSaltCoverageTest {
|
||||||
|
@Test
|
||||||
|
void aesFactoriesSeedChangesEmptyValuesAndFailures() throws Exception {
|
||||||
|
AES bytes = AES.createInstance("byte seed".getBytes());
|
||||||
|
assertEquals("byte seed", bytes.getSeed());
|
||||||
|
assertEquals("", bytes.decrypt(bytes.encrypt(null)));
|
||||||
|
assertEquals("", bytes.decrypt(null));
|
||||||
|
|
||||||
|
String encrypted = bytes.encrypt("value");
|
||||||
|
assertSame(bytes, bytes.withSeed("byte seed"));
|
||||||
|
assertEquals("value", bytes.decrypt(encrypted));
|
||||||
|
assertSame(bytes, bytes.withSeed("different seed"));
|
||||||
|
assertEquals("different seed", bytes.getSeed());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bytes.decrypt(encrypted));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bytes.decrypt("AA=="));
|
||||||
|
assertNotNull(AES.createInstance());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> AES.createInstance((String) null));
|
||||||
|
|
||||||
|
AES uninitialized = new AES();
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> uninitialized.encrypt("value"));
|
||||||
|
Method init = AES.class.getDeclaredMethod("init", byte[].class);
|
||||||
|
init.setAccessible(true);
|
||||||
|
InvocationTargetException initFailure = assertThrows(InvocationTargetException.class,
|
||||||
|
() -> init.invoke(uninitialized, (Object) new byte[16]));
|
||||||
|
assertInstanceOf(IllegalArgumentException.class, initFailure.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aesMainValidatesArgumentsAndSupportsEncryptAndDecryptModes() throws Exception {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> AES.main(null));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> AES.main(new String[0]));
|
||||||
|
assertDoesNotThrow(() -> AES.main(new String[]{"plain"}));
|
||||||
|
|
||||||
|
AES aes = AES.createInstance("seed");
|
||||||
|
assertDoesNotThrow(() -> AES.main(new String[]{aes.encrypt("plain"), "seed"}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hashSaltSupportsStringAndCharacterPasswordsAndInvalidInputs() throws Exception {
|
||||||
|
assertNotNull(new HashSalt());
|
||||||
|
String hash = HashSalt.createHash("password".toCharArray());
|
||||||
|
assertTrue(HashSalt.validatePassword("password".toCharArray(), hash));
|
||||||
|
assertFalse(HashSalt.validatePassword("wrong", hash));
|
||||||
|
assertFalse(HashSalt.validatePassword("wrong".toCharArray(), hash));
|
||||||
|
assertThrows(RuntimeException.class, () -> HashSalt.validatePassword("password", "bad"));
|
||||||
|
|
||||||
|
Method toHex = HashSalt.class.getDeclaredMethod("toHex", byte[].class);
|
||||||
|
toHex.setAccessible(true);
|
||||||
|
assertEquals("0001", toHex.invoke(null, (Object) new byte[]{0, 1}));
|
||||||
|
|
||||||
|
Method slowEquals = HashSalt.class.getDeclaredMethod("slowEquals", byte[].class, byte[].class);
|
||||||
|
slowEquals.setAccessible(true);
|
||||||
|
assertEquals(false, slowEquals.invoke(null, new byte[]{1}, new byte[]{1, 2}));
|
||||||
|
assertEquals(false, slowEquals.invoke(null, new byte[]{1, 2}, new byte[]{1}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hashSaltMainValidatesArgumentsAndPrintsHash() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> HashSalt.main(null));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> HashSalt.main(new String[0]));
|
||||||
|
assertDoesNotThrow(() -> HashSalt.main(new String[]{"password"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package net.locusworks.common.crypto;
|
||||||
|
|
||||||
|
import net.locusworks.common.crypto.KeyFile.EncryptionType;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.security.KeyPair;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
class CryptoCoverageTest {
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aesKeyAndSpecRoundTripAndRejectMalformedData() throws Exception {
|
||||||
|
AESKey key = new AESKey("repeatable seed");
|
||||||
|
assertEquals("aes", key.getAlgorithm());
|
||||||
|
assertEquals("aes-seed", key.getFormat());
|
||||||
|
assertArrayEquals("repeatable seed".getBytes(StandardCharsets.UTF_8), key.getEncoded());
|
||||||
|
|
||||||
|
String encoded = "aes-seed " + Base64.getEncoder().encodeToString(key.getEncoded());
|
||||||
|
AESKeySpec spec = new AESKeySpec(encoded.getBytes(StandardCharsets.UTF_8));
|
||||||
|
assertEquals("aes", spec.getFormat());
|
||||||
|
assertArrayEquals(key.getEncoded(), spec.generateKey().getEncoded());
|
||||||
|
assertThrows(InvalidKeySpecException.class,
|
||||||
|
() -> new AESKeySpec("wrong value".getBytes(StandardCharsets.UTF_8)).generateKey());
|
||||||
|
assertThrows(InvalidKeySpecException.class,
|
||||||
|
() -> new AESKeySpec("aes-seed !!!".getBytes(StandardCharsets.UTF_8)).generateKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void encryptionKeyFactoryHandlesAesRsaAndSshSpecs() throws Exception {
|
||||||
|
EncryptionKeyFactory factory = EncryptionKeyFactory.getInstance("RSA");
|
||||||
|
String aes = "aes-seed " + Base64.getEncoder().encodeToString("seed".getBytes(StandardCharsets.UTF_8));
|
||||||
|
assertInstanceOf(AESKey.class, factory.generatePrivateKey(new AESKeySpec(aes.getBytes(StandardCharsets.UTF_8))));
|
||||||
|
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
assertEquals(pair.getPrivate(), factory.generatePrivateKey(
|
||||||
|
new java.security.spec.PKCS8EncodedKeySpec(pair.getPrivate().getEncoded())));
|
||||||
|
assertEquals(pair.getPublic(), factory.generatePublicKey(
|
||||||
|
new java.security.spec.X509EncodedKeySpec(pair.getPublic().getEncoded())));
|
||||||
|
|
||||||
|
Path ssh = tempDir.resolve("public.ssh");
|
||||||
|
try (KeyFile file = new KeyFile(pair.getPublic(), "test", EncryptionType.SSH)) {
|
||||||
|
file.write(ssh.toString());
|
||||||
|
}
|
||||||
|
SSHEncodedKeySpec sshSpec = new SSHEncodedKeySpec(Files.readAllBytes(ssh));
|
||||||
|
assertNull(sshSpec.getFormat());
|
||||||
|
assertEquals(pair.getPublic(), factory.generatePublicKey(sshSpec));
|
||||||
|
assertEquals(pair.getPublic(), KeyFile.read(ssh.toString()).getKey());
|
||||||
|
assertThrows(InvalidKeySpecException.class,
|
||||||
|
() -> new SSHEncodedKeySpec("ssh-ed25519 bad".getBytes(StandardCharsets.UTF_8)).convertToRSAPubKeySpec());
|
||||||
|
assertThrows(InvalidKeySpecException.class,
|
||||||
|
() -> new SSHEncodedKeySpec("ssh-rsa !!!".getBytes(StandardCharsets.UTF_8)).convertToRSAPubKeySpec());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rsaGeneratesCalculatesEncryptsDecryptsAndRejectsOversizedMessages() {
|
||||||
|
assertNotNull(new RSA());
|
||||||
|
KeyPair defaultPair = RSA.generateKeyPair();
|
||||||
|
assertNotNull(defaultPair.getPrivate());
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
assertEquals(("hello".getBytes(StandardCharsets.UTF_8).length + 11) * 8,
|
||||||
|
RSA.calculateRequiredKeyLength("hello"));
|
||||||
|
|
||||||
|
String encrypted = RSA.encrypt(pair.getPublic(), "hello RSA");
|
||||||
|
assertEquals("hello RSA", RSA.decrypt(pair.getPrivate(), encrypted));
|
||||||
|
assertThrows(RuntimeException.class, () -> RSA.decrypt(pair.getPrivate(), "not base64"));
|
||||||
|
assertThrows(RuntimeException.class, () -> RSA.encrypt(pair.getPublic(), "x".repeat(200)));
|
||||||
|
assertThrows(RuntimeException.class, () -> RSA.generateKeyPair(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void keyFileWritesAesPemAndSshFormatsAndProvidesDescriptions() throws Exception {
|
||||||
|
AESKey aesKey = new AESKey("seed");
|
||||||
|
Path aesPath = tempDir.resolve("aes.key");
|
||||||
|
try (KeyFile file = new KeyFile(aesKey)) {
|
||||||
|
assertEquals("PRIVATE KEY", file.getDescription());
|
||||||
|
file.setDescription("AES KEY");
|
||||||
|
assertEquals("AES KEY", file.getDescription());
|
||||||
|
assertSame(aesKey, file.getKey());
|
||||||
|
file.write(aesPath.toString());
|
||||||
|
}
|
||||||
|
assertEquals("aes-seed c2VlZA==", Files.readString(aesPath));
|
||||||
|
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
Path privatePath = tempDir.resolve("private.pem");
|
||||||
|
try (KeyFile file = new KeyFile(pair.getPrivate())) {
|
||||||
|
file.write(privatePath.toString());
|
||||||
|
}
|
||||||
|
assertTrue(Files.readString(privatePath).contains("BEGIN RSA PRIVATE KEY"));
|
||||||
|
|
||||||
|
Path publicPath = tempDir.resolve("public.pem");
|
||||||
|
try (KeyFile file = new KeyFile(pair.getPublic(), "CUSTOM")) {
|
||||||
|
file.write(publicPath.toString());
|
||||||
|
}
|
||||||
|
assertTrue(Files.readString(publicPath).contains("BEGIN RSA CUSTOM"));
|
||||||
|
assertEquals("PUBLIC KEY", new KeyFile(pair.getPublic()).getDescription());
|
||||||
|
|
||||||
|
Path sshPath = tempDir.resolve("id.pub");
|
||||||
|
try (KeyFile file = new KeyFile(pair.getPublic(), "comment", EncryptionType.SSH)) {
|
||||||
|
file.write(sshPath.toString());
|
||||||
|
}
|
||||||
|
assertTrue(Files.readString(sshPath).startsWith("ssh-rsa "));
|
||||||
|
assertTrue(Files.readString(sshPath).endsWith(" comment"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void keyFileReadHandlesEmptyMissingRecognizedAndInvalidFiles() throws Exception {
|
||||||
|
assertNull(KeyFile.read(null).getKey());
|
||||||
|
RuntimeException missing = assertThrows(RuntimeException.class,
|
||||||
|
() -> KeyFile.read(tempDir.resolve("missing").toString()));
|
||||||
|
assertInstanceOf(IllegalArgumentException.class, missing.getCause());
|
||||||
|
|
||||||
|
Path aesPath = tempDir.resolve("recognized-aes.key");
|
||||||
|
new KeyFile(new AESKey("seed")).write(aesPath.toString());
|
||||||
|
assertArrayEquals("seed".getBytes(StandardCharsets.UTF_8), KeyFile.read(aesPath.toString()).getKey().getEncoded());
|
||||||
|
|
||||||
|
Path invalid = tempDir.resolve("invalid.key");
|
||||||
|
Files.writeString(invalid, "not a key");
|
||||||
|
assertThrows(RuntimeException.class, () -> KeyFile.read(invalid.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rsaWriteConvenienceOverloadsUseRequestedPaths() {
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
Path privatePath = tempDir.resolve("private.key");
|
||||||
|
Path publicPath = tempDir.resolve("public.key");
|
||||||
|
assertTrue(RSA.writePrivateKey(pair, privatePath.toString(), "PRIVATE KEY"));
|
||||||
|
assertTrue(RSA.writePublicKey(pair, publicPath.toString(), "PUBLIC KEY"));
|
||||||
|
assertTrue(Files.exists(privatePath));
|
||||||
|
assertTrue(Files.exists(publicPath));
|
||||||
|
|
||||||
|
Path sshPath = tempDir.resolve("rsa-ssh.pub");
|
||||||
|
assertTrue(RSA.writePublicKey(pair, sshPath.toString(), "comment", true));
|
||||||
|
|
||||||
|
assertTrue(RSA.generateAndWriteKeyPair(tempDir.resolve("generated").toString(), 1024));
|
||||||
|
assertNotNull(RSA.loadKeyPair(publicPath.toString(), privatePath.toString()));
|
||||||
|
assertNotNull(RSA.loadPublicKey(publicPath.toString()).getPublic());
|
||||||
|
assertNotNull(RSA.loadPrivateKey(privatePath.toString()).getPrivate());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void keyFileWrapsWritePemAndCloseFailures() throws Exception {
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
KeyFile invalidWrite = new KeyFile(pair.getPrivate());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> invalidWrite.write(tempDir.toString()));
|
||||||
|
|
||||||
|
KeyFile closeFailure = new KeyFile(pair.getPrivate());
|
||||||
|
Field writerField = KeyFile.class.getDeclaredField("writer");
|
||||||
|
writerField.setAccessible(true);
|
||||||
|
writerField.set(closeFailure, new Writer() {
|
||||||
|
@Override
|
||||||
|
public void write(char[] cbuf, int off, int len) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void flush() throws IOException {
|
||||||
|
throw new IOException("flush failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assertThrows(RuntimeException.class, closeFailure::close);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rsaConvenienceDelegatesAndShortCircuitPaths() {
|
||||||
|
KeyPair pair = RSA.generateKeyPair(1024);
|
||||||
|
try (MockedStatic<RSA> rsa = mockStatic(RSA.class, CALLS_REAL_METHODS)) {
|
||||||
|
rsa.when(RSA::generateKeyPair).thenReturn(pair);
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair)).thenReturn(true);
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, true)).thenReturn(true);
|
||||||
|
assertTrue(RSA.generateAndWriteSSHKeys());
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair)).thenReturn(false);
|
||||||
|
assertFalse(RSA.generateAndWriteSSHKeys());
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair)).thenReturn(true);
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, true)).thenReturn(false);
|
||||||
|
assertFalse(RSA.generateAndWriteSSHKeys());
|
||||||
|
|
||||||
|
rsa.when(() -> RSA.generateAndWriteKeyPair(2048)).thenReturn(true);
|
||||||
|
assertTrue(RSA.generateAndWriteKeyPair());
|
||||||
|
rsa.when(() -> RSA.generateAndWriteKeyPair("named", 2048)).thenReturn(true);
|
||||||
|
assertTrue(RSA.generateAndWriteKeyPair("named"));
|
||||||
|
rsa.when(() -> RSA.generateAndWriteKeyPair("id_rsa", 1024)).thenReturn(true);
|
||||||
|
assertTrue(RSA.generateAndWriteKeyPair(1024));
|
||||||
|
|
||||||
|
rsa.when(() -> RSA.generateKeyPair(512)).thenReturn(pair);
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair, "short", "PRIVATE KEY")).thenReturn(false);
|
||||||
|
assertFalse(RSA.generateAndWriteKeyPair("short", 512));
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair, "short", "PRIVATE KEY")).thenReturn(true);
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, "short.pub", "PUBLIC KEY")).thenReturn(false);
|
||||||
|
assertFalse(RSA.generateAndWriteKeyPair("short", 512));
|
||||||
|
|
||||||
|
rsa.when(() -> RSA.writePrivateKey(pair, "id_rsa", "PRIVATE KEY")).thenReturn(true);
|
||||||
|
assertTrue(RSA.writePrivateKey(pair));
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, false)).thenReturn(true);
|
||||||
|
assertTrue(RSA.writePublicKey(pair));
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, "id_rsa.pub", "PUBLIC KEY", true)).thenReturn(true);
|
||||||
|
rsa.when(() -> RSA.writePublicKey(pair, true)).thenCallRealMethod();
|
||||||
|
assertTrue(RSA.writePublicKey(pair, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package net.locusworks.common.exceptions;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
class ApplicationExceptionTest {
|
||||||
|
@Test
|
||||||
|
void factoryMethodsExposeExpectedCodesAndMessages() {
|
||||||
|
List<ApplicationException> exceptions = List.of(
|
||||||
|
ApplicationException.egregiousServer(), ApplicationException.invalidCreds(),
|
||||||
|
ApplicationException.notLoggedIn(), ApplicationException.invalidEmailAddress(),
|
||||||
|
ApplicationException.actionNotPermitted(), ApplicationException.actionNotPermitted("delete"),
|
||||||
|
ApplicationException.passwordsNotEqual(), ApplicationException.unAuthorized(),
|
||||||
|
ApplicationException.duplicateEntry("duplicate"), ApplicationException.duplicateEntry("duplicate %s", "item"),
|
||||||
|
ApplicationException.noEntryExists("missing"), ApplicationException.noEntryExists("missing %s", "item"),
|
||||||
|
ApplicationException.constraintViolation("constraint"), ApplicationException.constraintViolation("constraint %s", "x"),
|
||||||
|
ApplicationException.illegalArgument("illegal"), ApplicationException.generic("generic"));
|
||||||
|
|
||||||
|
assertTrue(exceptions.stream().noneMatch(ApplicationException::getSuccess));
|
||||||
|
assertTrue(exceptions.stream().allMatch(e -> e.getCode() != null && e.getMessage() != null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructorsAndThrowableFactoryPreserveCause() {
|
||||||
|
IllegalStateException cause = new IllegalStateException("failure");
|
||||||
|
ApplicationException fromCause = ApplicationException.fromException(cause);
|
||||||
|
assertEquals(9999, fromCause.getCode());
|
||||||
|
assertSame(cause, fromCause.getCause());
|
||||||
|
|
||||||
|
ApplicationException direct = new ApplicationException(42, cause);
|
||||||
|
assertEquals("failure", direct.getMessage());
|
||||||
|
assertSame(cause, direct.getCause());
|
||||||
|
|
||||||
|
ApplicationException explicit = new ApplicationException(43, "message", cause);
|
||||||
|
assertEquals(43, explicit.getCode());
|
||||||
|
assertSame(cause, explicit.getCause());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package net.locusworks.common.immutables;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
|
class ImmutablesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUnit() {
|
||||||
|
Unit<String> unit1 = new Unit<>();
|
||||||
|
unit1.setValue1("123");
|
||||||
|
|
||||||
|
Unit<String> unit2 = new Unit<>("123");
|
||||||
|
Unit<String> unit3 = new Unit<>("1234");
|
||||||
|
|
||||||
|
assertEquals(unit1, unit2);
|
||||||
|
|
||||||
|
assertNotEquals(null, unit1);
|
||||||
|
assertNotEquals(new Object(), unit1);
|
||||||
|
assertNotEquals(unit3, unit1);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue1("value"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testPair() {
|
||||||
|
Pair<String, String> unit1 = new Pair<>();
|
||||||
|
unit1.setValue2("value2");
|
||||||
|
unit1.setValue1("123");
|
||||||
|
|
||||||
|
Pair<String, String> unit2 = new Pair<>("123", "value2");
|
||||||
|
Pair<String, String> unit3 = new Pair<>("1234", "value2");
|
||||||
|
|
||||||
|
assertEquals(unit1, unit2);
|
||||||
|
|
||||||
|
assertNotEquals(null, unit1);
|
||||||
|
assertNotEquals(new Object(), unit1);
|
||||||
|
assertNotEquals(unit3, unit1);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue1("value"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue2("value"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testTriplet() {
|
||||||
|
Triplet<String, String, String> unit1 = new Triplet<>();
|
||||||
|
unit1.setValue3("value3");
|
||||||
|
unit1.setValue2("value2");
|
||||||
|
unit1.setValue1("123");
|
||||||
|
|
||||||
|
Triplet<String, String, String> unit2 = new Triplet<>("123", "value2", "value3");
|
||||||
|
Triplet<String, String, String> unit3 = new Triplet<>("1234", "value2", "value3");
|
||||||
|
|
||||||
|
assertEquals(unit1, unit2);
|
||||||
|
|
||||||
|
assertNotEquals(null, unit1);
|
||||||
|
assertNotEquals(new Object(), unit1);
|
||||||
|
assertNotEquals(unit3, unit1);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue1("value"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue2("value"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> unit1.setValue3("value"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
158
src/test/java/net/locusworks/common/io/IOUtilsTest.java
Normal file
158
src/test/java/net/locusworks/common/io/IOUtilsTest.java
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package net.locusworks.common.io;
|
||||||
|
|
||||||
|
import net.locusworks.common.Charsets;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
|
||||||
|
class IOUtilsTest {
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsLinesFromStreamsAndBothReaderKinds() throws Exception {
|
||||||
|
byte[] text = "first\nsecond\nthird".getBytes(StandardCharsets.UTF_8);
|
||||||
|
assertEquals(List.of("first", "second", "third"),
|
||||||
|
IOUtils.readLines(new ByteArrayInputStream(text), StandardCharsets.UTF_8));
|
||||||
|
assertEquals(List.of("first", "second", "third"), IOUtils.readLines(new StringReader(new String(text))));
|
||||||
|
|
||||||
|
BufferedReader buffered = new BufferedReader(new StringReader("line"));
|
||||||
|
assertSame(buffered, IOUtils.toBufferedReader(buffered));
|
||||||
|
assertNotNull(IOUtils.toBufferedReader(new StringReader("line")));
|
||||||
|
assertThrows(NullPointerException.class, () -> IOUtils.readLines((Reader) null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void convertsStreamsAndCopiesBytesThroughEveryOverload() throws Exception {
|
||||||
|
byte[] source = "some binary data".getBytes(StandardCharsets.UTF_8);
|
||||||
|
assertArrayEquals(source, IOUtils.toByteArray(new ByteArrayInputStream(source)));
|
||||||
|
|
||||||
|
ByteArrayOutputStream defaultCopy = new ByteArrayOutputStream();
|
||||||
|
assertEquals(source.length, IOUtils.copy(new ByteArrayInputStream(source), defaultCopy));
|
||||||
|
assertArrayEquals(source, defaultCopy.toByteArray());
|
||||||
|
|
||||||
|
ByteArrayOutputStream sizedCopy = new ByteArrayOutputStream();
|
||||||
|
assertEquals(source.length, IOUtils.copy(new ByteArrayInputStream(source), sizedCopy, 2));
|
||||||
|
assertArrayEquals(source, sizedCopy.toByteArray());
|
||||||
|
|
||||||
|
ByteArrayOutputStream bufferedCopy = new ByteArrayOutputStream();
|
||||||
|
assertEquals(source.length,
|
||||||
|
IOUtils.copyLarge(new ByteArrayInputStream(source), bufferedCopy, new byte[3]));
|
||||||
|
assertArrayEquals(source, bufferedCopy.toByteArray());
|
||||||
|
|
||||||
|
ByteArrayOutputStream largeCopy = new ByteArrayOutputStream();
|
||||||
|
assertEquals(source.length, IOUtils.copyLarge(new ByteArrayInputStream(source), largeCopy));
|
||||||
|
assertArrayEquals(source, largeCopy.toByteArray());
|
||||||
|
assertEquals(0, IOUtils.copyLarge(new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void copiesCharactersThroughEveryOverload() throws Exception {
|
||||||
|
String source = "characters-å";
|
||||||
|
StringWriter encoded = new StringWriter();
|
||||||
|
IOUtils.copy(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)), encoded,
|
||||||
|
StandardCharsets.UTF_8);
|
||||||
|
assertEquals(source, encoded.toString());
|
||||||
|
|
||||||
|
StringWriter regular = new StringWriter();
|
||||||
|
assertEquals(source.length(), IOUtils.copy(new StringReader(source), regular));
|
||||||
|
assertEquals(source, regular.toString());
|
||||||
|
|
||||||
|
StringWriter buffered = new StringWriter();
|
||||||
|
assertEquals(source.length(), IOUtils.copyLarge(new StringReader(source), buffered, new char[2]));
|
||||||
|
assertEquals(source, buffered.toString());
|
||||||
|
|
||||||
|
StringWriter large = new StringWriter();
|
||||||
|
assertEquals(source.length(), IOUtils.copyLarge(new StringReader(source), large));
|
||||||
|
assertEquals(source, large.toString());
|
||||||
|
assertEquals(0, IOUtils.copyLarge(new StringReader(""), new StringWriter()));
|
||||||
|
assertEquals(source, IOUtils.toString(
|
||||||
|
new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void integerCopyMethodsReturnEofMarkerForCountsOverIntegerMaximum() throws Exception {
|
||||||
|
try (MockedStatic<IOUtils> mocked = mockStatic(IOUtils.class, CALLS_REAL_METHODS)) {
|
||||||
|
mocked.when(() -> IOUtils.copyLarge(any(InputStream.class), any(OutputStream.class)))
|
||||||
|
.thenReturn((long) Integer.MAX_VALUE + 1);
|
||||||
|
assertEquals(IOUtils.EOF,
|
||||||
|
IOUtils.copy(new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream()));
|
||||||
|
|
||||||
|
mocked.when(() -> IOUtils.copyLarge(any(Reader.class), any(Writer.class)))
|
||||||
|
.thenReturn((long) Integer.MAX_VALUE + 1);
|
||||||
|
assertEquals(IOUtils.EOF, IOUtils.copy(new StringReader(""), new StringWriter()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
|
void writesFilesUsingEveryOverload() throws Exception {
|
||||||
|
Path byName = tempDir.resolve("name.txt");
|
||||||
|
IOUtils.writeStringToFile(byName.toString(), "default");
|
||||||
|
assertEquals("default", Files.readString(byName));
|
||||||
|
|
||||||
|
Path namedCharset = tempDir.resolve("name-charset.txt");
|
||||||
|
IOUtils.writeStringToFile(namedCharset.toString(), "named", StandardCharsets.UTF_16);
|
||||||
|
assertEquals("named", Files.readString(namedCharset, StandardCharsets.UTF_16));
|
||||||
|
|
||||||
|
Path byPath = tempDir.resolve("path.txt");
|
||||||
|
IOUtils.writeStringToFile(byPath, "path");
|
||||||
|
assertEquals("path", Files.readString(byPath, Charsets.UTF_8));
|
||||||
|
|
||||||
|
Path byFile = tempDir.resolve("file.txt");
|
||||||
|
IOUtils.writeStringToFile(byFile.toFile(), "file", StandardCharsets.UTF_8);
|
||||||
|
assertEquals("file", Files.readString(byFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
|
void deletesFilesUsingEveryOverloadAndWrapsIoFailures() throws Exception {
|
||||||
|
Path byName = Files.createFile(tempDir.resolve("name-delete.txt"));
|
||||||
|
IOUtils.deleteFile(byName.toString());
|
||||||
|
assertFalse(Files.exists(byName));
|
||||||
|
|
||||||
|
Path byFile = Files.createFile(tempDir.resolve("file-delete.txt"));
|
||||||
|
IOUtils.deleteFile(byFile.toFile());
|
||||||
|
assertFalse(Files.exists(byFile));
|
||||||
|
|
||||||
|
Path first = Files.createFile(tempDir.resolve("first.txt"));
|
||||||
|
Path second = Files.createFile(tempDir.resolve("second.txt"));
|
||||||
|
IOUtils.deleteFiles(first.toString(), second.toString());
|
||||||
|
assertFalse(Files.exists(first));
|
||||||
|
assertFalse(Files.exists(second));
|
||||||
|
|
||||||
|
Path nonEmptyDirectory = Files.createDirectory(tempDir.resolve("non-empty"));
|
||||||
|
Files.createFile(nonEmptyDirectory.resolve("child"));
|
||||||
|
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> IOUtils.deleteFile(nonEmptyDirectory));
|
||||||
|
assertInstanceOf(IOException.class, error.getCause());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructorAndInvalidInputsAreCovered() {
|
||||||
|
assertNotNull(new IOUtils());
|
||||||
|
assertThrows(NullPointerException.class, () -> IOUtils.toByteArray(null));
|
||||||
|
assertThrows(NegativeArraySizeException.class,
|
||||||
|
() -> IOUtils.copy(new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream(), -1));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package net.locusworks.common.migration;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
|
import org.flywaydb.core.api.MigrationInfo;
|
||||||
|
import org.flywaydb.core.api.MigrationInfoService;
|
||||||
|
import org.flywaydb.core.api.configuration.Configuration;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationItemTest {
|
||||||
|
private static Flyway flyway(MigrationInfo[] all, MigrationInfo[] pending) {
|
||||||
|
Flyway flyway = mock(Flyway.class);
|
||||||
|
MigrationInfoService info = mock(MigrationInfoService.class);
|
||||||
|
Configuration configuration = mock(Configuration.class);
|
||||||
|
when(flyway.info()).thenReturn(info);
|
||||||
|
when(info.all()).thenReturn(all);
|
||||||
|
when(info.pending()).thenReturn(pending);
|
||||||
|
when(flyway.getConfiguration()).thenReturn(configuration);
|
||||||
|
when(configuration.getSchemas()).thenReturn(new String[]{"first", "second"});
|
||||||
|
return flyway;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exposesSchemasPendingCountAndMigrationLog() {
|
||||||
|
Flyway flyway = flyway(new MigrationInfo[0], new MigrationInfo[]{mock(MigrationInfo.class)});
|
||||||
|
MigrationItem item = new MigrationItem(flyway);
|
||||||
|
assertArrayEquals(new String[]{"first", "second"}, item.getSchemas());
|
||||||
|
assertEquals(1, item.qtyPending());
|
||||||
|
assertNotNull(item.getAllMigrationsLog());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void repairAndMigrateInvokeCallbackAndFlyway() {
|
||||||
|
Flyway flyway = flyway(new MigrationInfo[0], new MigrationInfo[0]);
|
||||||
|
List<String> messages = new ArrayList<>();
|
||||||
|
MigrationItem item = new MigrationItem(flyway, messages::add);
|
||||||
|
item.repair();
|
||||||
|
item.migrate();
|
||||||
|
verify(flyway).repair();
|
||||||
|
verify(flyway).migrate();
|
||||||
|
assertEquals(2, messages.size());
|
||||||
|
assertTrue(messages.stream().allMatch(s -> s.contains("first, second")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void repairAndMigrateWrapFlywayFailures() {
|
||||||
|
Flyway repairFlyway = flyway(new MigrationInfo[0], new MigrationInfo[0]);
|
||||||
|
doThrow(new IllegalStateException("repair failed")).when(repairFlyway).repair();
|
||||||
|
RuntimeException repair = assertThrows(RuntimeException.class, () -> new MigrationItem(repairFlyway).repair());
|
||||||
|
assertTrue(repair.getMessage().contains("repair failed"));
|
||||||
|
|
||||||
|
Flyway migrateFlyway = flyway(new MigrationInfo[0], new MigrationInfo[0]);
|
||||||
|
doThrow(new IllegalStateException("migrate failed")).when(migrateFlyway).migrate();
|
||||||
|
RuntimeException migrate = assertThrows(RuntimeException.class, () -> new MigrationItem(migrateFlyway).migrate());
|
||||||
|
assertTrue(migrate.getMessage().contains("migrate failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void baseManagerInitializesMutableMigrationList() {
|
||||||
|
class Manager extends BaseMigrationManager {
|
||||||
|
@Override
|
||||||
|
public void migrate() {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Manager manager = new Manager();
|
||||||
|
assertNotNull(manager.migrations);
|
||||||
|
assertDoesNotThrow(manager::migrate);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package net.locusworks.common.net;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
|
class HttpClientHelperTest {
|
||||||
|
@Test
|
||||||
|
void schemaLookupHandlesBothProtocolsAndUnknownValue() {
|
||||||
|
assertEquals(HttpClientHelper.HttpSchema.HTTP, HttpClientHelper.HttpSchema.findEnum("http"));
|
||||||
|
assertEquals(HttpClientHelper.HttpSchema.HTTPS, HttpClientHelper.HttpSchema.findEnum("HtTpS"));
|
||||||
|
assertNull(HttpClientHelper.HttpSchema.findEnum("ftp"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructorRejectsUnknownProtocol() {
|
||||||
|
Exception error = assertThrows(Exception.class, () -> new HttpClientHelper("ftp", "localhost", "21"));
|
||||||
|
assertEquals("Unable to find http schema of ftp", error.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void executesHttpGetAndConsumesResponse() throws Exception {
|
||||||
|
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||||
|
server.createContext("/status", exchange -> {
|
||||||
|
byte[] body = "ok".getBytes();
|
||||||
|
exchange.sendResponseHeaders(202, body.length);
|
||||||
|
exchange.getResponseBody().write(body);
|
||||||
|
exchange.close();
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
try {
|
||||||
|
HttpClientHelper helper = new HttpClientHelper("http", "localhost", Integer.toString(server.getAddress().getPort()));
|
||||||
|
assertEquals(202, helper.getResponseCode("/status"));
|
||||||
|
assertNotNull(new HttpClientHelper("https", "localhost", "443"));
|
||||||
|
} finally {
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package net.locusworks.common.net.certmanagers;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import javax.net.ssl.TrustManager;
|
||||||
|
|
||||||
|
|
||||||
|
class TrustAllCertsManagerTest {
|
||||||
|
@Test
|
||||||
|
void trustsClientsAndServersAndBuildsTrustManagerArray() throws Exception {
|
||||||
|
TrustAllCertsManager manager = new TrustAllCertsManager();
|
||||||
|
assertDoesNotThrow(() -> manager.checkClientTrusted(null, null));
|
||||||
|
assertDoesNotThrow(() -> manager.checkServerTrusted(null, null));
|
||||||
|
assertNull(manager.getAcceptedIssuers());
|
||||||
|
|
||||||
|
TrustManager[] managers = TrustAllCertsManager.trustAllCerts();
|
||||||
|
assertEquals(1, managers.length);
|
||||||
|
assertInstanceOf(TrustAllCertsManager.class, managers[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package net.locusworks.common.net.hostverifiers;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class AllHostValidVerifierTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testVerify() {
|
||||||
|
AllHostValidVerifier verifier = new AllHostValidVerifier();
|
||||||
|
assertTrue(verifier.verify("localhost", null));
|
||||||
|
assertTrue(verifier.verify("127.0.0.1", null));
|
||||||
|
assertTrue(verifier.verify("::1", null));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package net.locusworks.common.net.ssl;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.security.KeyManagementException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
|
||||||
|
|
||||||
|
class SSLManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCreateSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
|
||||||
|
assertNotNull(SSLManager.getTrustAllTLSClient());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTLS() {
|
||||||
|
assertNotNull(SSLManager.TLS);
|
||||||
|
assertEquals(4, SSLManager.TLS.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package net.locusworks.common.objectmapper;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
|
||||||
|
class ObjectMapperCoverageTest {
|
||||||
|
static class Value {
|
||||||
|
public String name;
|
||||||
|
|
||||||
|
Value() {
|
||||||
|
}
|
||||||
|
|
||||||
|
Value(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class SelfReference {
|
||||||
|
SelfReference self = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
static class CyclicReference {
|
||||||
|
Object next;
|
||||||
|
}
|
||||||
|
|
||||||
|
static class ThrowingGetter {
|
||||||
|
String name = "field value";
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
throw new IllegalStateException("Jackson getter failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resultContainersSupportEveryConstructorMutationAndHandlerPath() {
|
||||||
|
RuntimeException error = new RuntimeException("bad json");
|
||||||
|
ObjectMapperResults<String> result = new ObjectMapperResults<>("value", null);
|
||||||
|
assertEquals("value", result.getResults());
|
||||||
|
assertFalse(result.hasError());
|
||||||
|
assertSame(result, result.withErrorHandler(e -> fail("handler must not run")));
|
||||||
|
|
||||||
|
result.setResults("changed");
|
||||||
|
result.setException(error);
|
||||||
|
AtomicReference<Throwable> handled = new AtomicReference<>();
|
||||||
|
assertSame(result, result.withErrorHandler(handled::set));
|
||||||
|
assertSame(error, handled.get());
|
||||||
|
assertSame(result, result.withErrorHandler(null));
|
||||||
|
|
||||||
|
assertEquals("simple", new ObjectMapperResults<>("simple").getResults());
|
||||||
|
assertSame(error, new ObjectMapperResults<String>(error).getException());
|
||||||
|
|
||||||
|
ObjectMapperListResults<List<String>> list = new ObjectMapperListResults<>(List.of("a"), null);
|
||||||
|
assertEquals(List.of("a"), list.getResults());
|
||||||
|
assertFalse(list.hasError());
|
||||||
|
assertSame(list, list.withErrorHandler(e -> fail("handler must not run")));
|
||||||
|
|
||||||
|
ObjectMapperListResults<List<String>> failed = new ObjectMapperListResults<>(error);
|
||||||
|
handled.set(null);
|
||||||
|
assertSame(failed, failed.withErrorHandler(handled::set));
|
||||||
|
assertSame(error, handled.get());
|
||||||
|
assertSame(failed, failed.withErrorHandler(null));
|
||||||
|
assertEquals(List.of("b"), new ObjectMapperListResults<>(List.of("b")).getResults());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsBytesStringsObjectsAndCollectionImplementations() {
|
||||||
|
Value fromBytes = ObjectMapperHelper.readValue("{\"name\":\"bytes\"}".getBytes(), Value.class).getResults();
|
||||||
|
assertEquals("bytes", fromBytes.name);
|
||||||
|
assertEquals("string", ObjectMapperHelper.readValue("{\"name\":\"string\"}", Value.class).getResults().name);
|
||||||
|
assertEquals("object", ObjectMapperHelper.readValue(new Value("object"), Value.class).getResults().name);
|
||||||
|
Object delegatedJson = "{\"name\":\"delegated\"}";
|
||||||
|
assertEquals("delegated", ObjectMapperHelper.readValue(delegatedJson, Value.class).getResults().name);
|
||||||
|
|
||||||
|
List<Value> values = List.of(new Value("one"), new Value("two"));
|
||||||
|
assertEquals(2, ObjectMapperHelper.readListValue(values, Value.class).getResults().size());
|
||||||
|
assertEquals(2, ObjectMapperHelper.readListValue("[{\"name\":\"one\"},{\"name\":\"two\"}]", Value.class, LinkedList.class).getResults().size());
|
||||||
|
assertInstanceOf(LinkedList.class,
|
||||||
|
ObjectMapperHelper.readListValue(values, Value.class, LinkedList.class).getResults());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void malformedInputReturnsErrorsForEveryReadOverload() {
|
||||||
|
assertTrue(ObjectMapperHelper.readValue(new byte[]{1, 2}, Value.class).hasError());
|
||||||
|
assertTrue(ObjectMapperHelper.readValue("not-json", Value.class).hasError());
|
||||||
|
assertTrue(ObjectMapperHelper.readValue(new Object(), Thread.class).hasError());
|
||||||
|
assertTrue(ObjectMapperHelper.readListValue("not-json", Value.class, ArrayList.class).hasError());
|
||||||
|
assertTrue(ObjectMapperHelper.readListValue(new Object(), Value.class, List.class).hasError());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void writeFallsBackWhenJacksonAndGsonRejectCircularObject() {
|
||||||
|
CyclicReference first = new CyclicReference();
|
||||||
|
CyclicReference second = new CyclicReference();
|
||||||
|
first.next = second;
|
||||||
|
second.next = first;
|
||||||
|
ObjectMapperResults<String> result = ObjectMapperHelper.writeValue(first);
|
||||||
|
assertTrue(result.hasError());
|
||||||
|
|
||||||
|
ObjectMapperResults<String> fallback = ObjectMapperHelper.writeValue(new ThrowingGetter());
|
||||||
|
assertFalse(fallback.hasError());
|
||||||
|
assertTrue(fallback.getResults().contains("field value"));
|
||||||
|
|
||||||
|
assertNotNull(new ObjectMapperHelper());
|
||||||
|
assertTrue(ObjectMapperHelper.readValue(new SelfReference(), Value.class).hasError());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package net.locusworks.common.properties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
|
||||||
|
class ImmutablePropertiesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testImmutableProperties() {
|
||||||
|
assertNotNull(new ImmutableProperties());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testImmutablePropertiesWithEmptyOrNullProperties() {
|
||||||
|
assertNotNull(new ImmutableProperties(new Properties()));
|
||||||
|
assertNotNull(new ImmutableProperties(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testImmutablePropertiesWthProperties() {
|
||||||
|
final Properties properties = new Properties();
|
||||||
|
properties.put("Hello", "World");
|
||||||
|
assertNotNull(new ImmutableProperties(properties));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSetProperties() {
|
||||||
|
final ImmutableProperties properties = new ImmutableProperties(new Properties());
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
assertEquals("World", properties.getProperty("Hello"));
|
||||||
|
|
||||||
|
assertThrows(RuntimeException.class, () -> properties.setProperty("Hello", "World"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package net.locusworks.common.properties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
class OrderedPropertiesCoverageTest {
|
||||||
|
@Test
|
||||||
|
void loadsAllPropertySyntaxFromReaderAndInputStream() throws Exception {
|
||||||
|
String source = "# comment\n! another\n" +
|
||||||
|
"simple=value\ncolon:value2\nspace value3\n" +
|
||||||
|
"spaced = spaced-value\n" +
|
||||||
|
"tabbed\t:\tvalue5\nform\f=\fvalue6\n" +
|
||||||
|
"slashes\\\\key:value4\n" +
|
||||||
|
"escaped\\:colon=value7\n" +
|
||||||
|
"escaped\\ key=escaped\\ value\n" +
|
||||||
|
"unicode=\\u0041\\tB\\nC\\rD\\fE\n" +
|
||||||
|
"continued=first\\\n second\n" +
|
||||||
|
"emptyKey\n=empty-key-value\n";
|
||||||
|
|
||||||
|
OrderedProperties readerProperties = new OrderedProperties();
|
||||||
|
readerProperties.load(new StringReader(source));
|
||||||
|
assertEquals("value", readerProperties.getProperty("simple"));
|
||||||
|
assertEquals("value2", readerProperties.getProperty("colon"));
|
||||||
|
assertEquals("value3", readerProperties.getProperty("space"));
|
||||||
|
assertEquals("spaced-value", readerProperties.getProperty("spaced"));
|
||||||
|
assertEquals("value4", readerProperties.getProperty("slashes\\key"));
|
||||||
|
assertEquals("value5", readerProperties.getProperty("tabbed"));
|
||||||
|
assertEquals("value6", readerProperties.getProperty("form"));
|
||||||
|
assertEquals("value7", readerProperties.getProperty("escaped:colon"));
|
||||||
|
assertEquals("escaped value", readerProperties.getProperty("escaped key"));
|
||||||
|
assertEquals("A\tB\nC\rD\fE", readerProperties.getProperty("unicode"));
|
||||||
|
assertEquals("firstsecond", readerProperties.getProperty("continued"));
|
||||||
|
assertEquals("", readerProperties.getProperty("emptyKey"));
|
||||||
|
assertEquals("empty-key-value", readerProperties.getProperty(""));
|
||||||
|
|
||||||
|
OrderedProperties streamProperties = new OrderedProperties();
|
||||||
|
streamProperties.load(new ByteArrayInputStream(source.getBytes(StandardCharsets.ISO_8859_1)));
|
||||||
|
assertEquals(readerProperties, streamProperties);
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> streamProperties.load(new StringReader("bad=\\u12G4")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void storesToWriterAndStreamWithCommentsUnicodeAndEscapes() throws Exception {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty(" leading:=#!", " value\t\n\r\f\\é");
|
||||||
|
|
||||||
|
StringWriter writer = new StringWriter();
|
||||||
|
properties.store(writer, "first\nsecond\rthird\r\nfourth\u0100");
|
||||||
|
String writerText = writer.toString();
|
||||||
|
assertTrue(writerText.contains("#first"));
|
||||||
|
assertTrue(writerText.contains("#second"));
|
||||||
|
assertTrue(writerText.contains("\\ leading\\:\\=\\#\\!"));
|
||||||
|
assertTrue(writerText.contains("é"));
|
||||||
|
|
||||||
|
StringWriter bufferedTarget = new StringWriter();
|
||||||
|
properties.store(new BufferedWriter(bufferedTarget), "\u0100first\rsolo\n#already\n!also\nlast\r\nend\r");
|
||||||
|
assertTrue(bufferedTarget.toString().contains("#already"));
|
||||||
|
|
||||||
|
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||||
|
properties.store(bytes, null);
|
||||||
|
String streamText = bytes.toString(StandardCharsets.ISO_8859_1);
|
||||||
|
assertTrue(streamText.contains("\\u00E9"));
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> properties.save(new OutputStream() {
|
||||||
|
@Override
|
||||||
|
public void write(int b) throws IOException {
|
||||||
|
throw new IOException("expected");
|
||||||
|
}
|
||||||
|
}, "ignored error"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultsEnumerationListingAndNonStringValuesAreHandled() {
|
||||||
|
OrderedProperties defaults = new OrderedProperties();
|
||||||
|
defaults.setProperty("default", "value");
|
||||||
|
defaults.put("nonStringDefault", 1);
|
||||||
|
OrderedProperties properties = new OrderedProperties(defaults);
|
||||||
|
properties.setProperty("local", "x".repeat(50));
|
||||||
|
properties.put("nonString", 2);
|
||||||
|
|
||||||
|
assertEquals("value", properties.getProperty("default"));
|
||||||
|
assertEquals("fallback", properties.getProperty("missing", "fallback"));
|
||||||
|
assertEquals("value", properties.getProperty("default", "fallback"));
|
||||||
|
Enumeration<?> names = properties.propertyNames();
|
||||||
|
assertTrue(java.util.Collections.list(names).containsAll(List.of("default", "local")));
|
||||||
|
properties.put(3, "nonStringKey");
|
||||||
|
assertTrue(properties.stringPropertyNames().containsAll(java.util.Set.of("default", "local")));
|
||||||
|
|
||||||
|
properties.remove("nonString");
|
||||||
|
properties.remove(3);
|
||||||
|
defaults.remove("nonStringDefault");
|
||||||
|
|
||||||
|
ByteArrayOutputStream printBytes = new ByteArrayOutputStream();
|
||||||
|
properties.list(new PrintStream(printBytes));
|
||||||
|
assertTrue(printBytes.toString().contains("..."));
|
||||||
|
StringWriter output = new StringWriter();
|
||||||
|
properties.list(new PrintWriter(output));
|
||||||
|
assertTrue(output.toString().contains("-- listing properties --"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lineReaderHandlesCommentsWhitespaceContinuationLongLinesAndEndings() throws Exception {
|
||||||
|
String longValue = "x".repeat(9000);
|
||||||
|
String input = " #comment\r\n\t!comment\n key=value\\\r\n continued\r" + longValue;
|
||||||
|
OrderedProperties.LineReader reader = new OrderedProperties.LineReader(new StringReader(input));
|
||||||
|
int length = reader.readLine();
|
||||||
|
assertEquals("key=valuecontinued", new String(reader.lineBuf, 0, length));
|
||||||
|
assertEquals(9000, reader.readLine());
|
||||||
|
|
||||||
|
OrderedProperties.LineReader stream = new OrderedProperties.LineReader(
|
||||||
|
new ByteArrayInputStream(("a=b\n" + longValue).getBytes(StandardCharsets.ISO_8859_1)));
|
||||||
|
assertEquals(3, stream.readLine());
|
||||||
|
assertEquals(9000, stream.readLine());
|
||||||
|
assertEquals(-1, stream.readLine());
|
||||||
|
|
||||||
|
OrderedProperties.LineReader trailingReader = new OrderedProperties.LineReader(new StringReader("key=value\\"));
|
||||||
|
assertEquals("key=value", new String(trailingReader.lineBuf, 0, trailingReader.readLine()));
|
||||||
|
OrderedProperties.LineReader trailingStream = new OrderedProperties.LineReader(
|
||||||
|
new ByteArrayInputStream("key=value\\\n".getBytes(StandardCharsets.ISO_8859_1)));
|
||||||
|
assertEquals("key=value", new String(trailingStream.lineBuf, 0, trailingStream.readLine()));
|
||||||
|
OrderedProperties.LineReader whiteContinuation = new OrderedProperties.LineReader(
|
||||||
|
new StringReader("key=value\\\n \t\fcontinued\n"));
|
||||||
|
int continuedLength = whiteContinuation.readLine();
|
||||||
|
assertEquals("key=valuecontinued", new String(whiteContinuation.lineBuf, 0, continuedLength));
|
||||||
|
assertEquals(-1, new OrderedProperties.LineReader(new StringReader("#comment without newline")).readLine());
|
||||||
|
|
||||||
|
OrderedProperties.LineReader crWithoutLf = new OrderedProperties.LineReader(new StringReader("a\\\rb\n"));
|
||||||
|
int crLength = crWithoutLf.readLine();
|
||||||
|
assertEquals("ab", new String(crWithoutLf.lineBuf, 0, crLength));
|
||||||
|
|
||||||
|
OrderedProperties.LineReader blankEndings = new OrderedProperties.LineReader(new StringReader("\n\r\nvalue\n"));
|
||||||
|
assertEquals("value", new String(blankEndings.lineBuf, 0, blankEndings.readLine()));
|
||||||
|
|
||||||
|
String boundaryInput = "z".repeat(8191) + "\nnext\n";
|
||||||
|
OrderedProperties.LineReader boundary = new OrderedProperties.LineReader(new StringReader(boundaryInput));
|
||||||
|
assertEquals(8191, boundary.readLine());
|
||||||
|
assertEquals(4, boundary.readLine());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void privateConversionHelpersCoverEveryEscapeAndHexPath() throws Exception {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
Method load = OrderedProperties.class.getDeclaredMethod("loadConvert", char[].class, int.class, int.class, char[].class);
|
||||||
|
Method save = OrderedProperties.class.getDeclaredMethod("saveConvert", String.class, boolean.class, boolean.class);
|
||||||
|
Method hex = OrderedProperties.class.getDeclaredMethod("toHex", int.class);
|
||||||
|
load.setAccessible(true);
|
||||||
|
save.setAccessible(true);
|
||||||
|
hex.setAccessible(true);
|
||||||
|
|
||||||
|
String escaped = "a\\tb\\nc\\rd\\fe\\\\f\\ g\\:h\\=i\\#j\\!k\\u0041";
|
||||||
|
assertEquals("a\tb\nc\rd\fe\\f g:h=i#j!kA",
|
||||||
|
load.invoke(properties, escaped.toCharArray(), 0, escaped.length(), new char[1]));
|
||||||
|
String hexCases = "\\u00af\\u00AF";
|
||||||
|
assertEquals("¯¯", load.invoke(properties, hexCases.toCharArray(), 0, hexCases.length(), new char[1]));
|
||||||
|
assertEquals("\\ a\\:\\=\\#\\!\\t\\n\\r\\f\\\\\\u0100",
|
||||||
|
save.invoke(properties, " a:=#!\t\n\r\f\\\u0100", true, true));
|
||||||
|
assertEquals("\\ a\\:\\=\\#\\!\\t\\n\\r\\f\\\\\u0100",
|
||||||
|
save.invoke(properties, " a:=#!\t\n\r\f\\\u0100", false, false));
|
||||||
|
assertEquals("a\\ b", save.invoke(properties, "a b", true, false));
|
||||||
|
assertEquals("a b", save.invoke(properties, "a b", false, false));
|
||||||
|
assertEquals("\\u0001", save.invoke(properties, "\u0001", false, true));
|
||||||
|
assertEquals("\u0001", save.invoke(properties, "\u0001", false, false));
|
||||||
|
assertEquals("0", save.invoke(properties, "0", false, true));
|
||||||
|
assertEquals('0', hex.invoke(null, 0));
|
||||||
|
assertEquals('F', hex.invoke(null, 15));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void immutablePropertiesCopiesValuesAndRejectsReplacement() {
|
||||||
|
Properties source = new Properties();
|
||||||
|
source.setProperty("key", "value");
|
||||||
|
ImmutableProperties immutable = new ImmutableProperties(source);
|
||||||
|
assertEquals("value", immutable.getProperty("key"));
|
||||||
|
assertThrows(RuntimeException.class, () -> immutable.setProperty("key", "changed"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package net.locusworks.common.properties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
|
||||||
|
class OrderedPropertiesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSetProperty() {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
assertEquals("World", properties.getProperty("Hello"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testLoad() throws IOException {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.load(new ByteArrayInputStream("Hello=World".getBytes()));
|
||||||
|
assertEquals("World", properties.getProperty("Hello"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSave() {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
properties.save(new ByteArrayOutputStream(), "");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStore() {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
try {
|
||||||
|
properties.store(new ByteArrayOutputStream(), "");
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail("IOException should not be thrown");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetProperty() {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
assertEquals("World", properties.getProperty("Hello"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testPropertyNames() {
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
var propertyNames = properties.stringPropertyNames();
|
||||||
|
assertFalse(propertyNames.isEmpty());
|
||||||
|
assertTrue(propertyNames.contains("Hello"));
|
||||||
|
assertEquals(1, propertyNames.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testList() {
|
||||||
|
PrintStream ps = new PrintStream(new ByteArrayOutputStream());
|
||||||
|
OrderedProperties properties = new OrderedProperties();
|
||||||
|
properties.setProperty("Hello", "World");
|
||||||
|
properties.list(ps);
|
||||||
|
ps.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/test/java/net/locusworks/common/utils/ChecksTest.java
Normal file
28
src/test/java/net/locusworks/common/utils/ChecksTest.java
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
|
class ChecksTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCheckArgument() {
|
||||||
|
Throwable ex = assertThrows(IllegalArgumentException.class, () -> Checks.checkArguments(false, "One does not equal 2"));
|
||||||
|
assertEquals("One does not equal 2", ex.getMessage());
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> Checks.checkArguments(true, "One does not equal 2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCheckState() {
|
||||||
|
Throwable ex = assertThrows(IllegalStateException.class, () -> Checks.checkState(false, "One does not equal 2"));
|
||||||
|
assertEquals("One does not equal 2", ex.getMessage());
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> Checks.checkState(true, "One does not equal 2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.ObjectIdGenerator;
|
||||||
|
import com.fasterxml.jackson.core.Base64Variant;
|
||||||
|
import com.fasterxml.jackson.core.JsonGenerator;
|
||||||
|
import com.fasterxml.jackson.core.JsonStreamContext;
|
||||||
|
import com.fasterxml.jackson.core.ObjectCodec;
|
||||||
|
import com.fasterxml.jackson.core.SerializableString;
|
||||||
|
import com.fasterxml.jackson.core.TreeNode;
|
||||||
|
import com.fasterxml.jackson.core.Version;
|
||||||
|
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;
|
||||||
|
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
275
src/test/java/net/locusworks/common/utils/FileReaderTest.java
Normal file
275
src/test/java/net/locusworks/common/utils/FileReaderTest.java
Normal file
@@ -0,0 +1,275 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import net.locusworks.common.interfaces.AutoCloseableIterator;
|
||||||
|
import net.locusworks.common.utils.FileReader.LineInfo;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
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.NoSuchElementException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
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<>();
|
||||||
|
private BufferedReader testBufferedReader;
|
||||||
|
|
||||||
|
private static final String[] TEST_CONTENT = new String[]{
|
||||||
|
"Line 1",
|
||||||
|
"Line 2",
|
||||||
|
"Line 3"
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void setUpBeforeClass() throws Exception {
|
||||||
|
File testFile = new File(TEST_FILE);
|
||||||
|
FileOutputStream fos = new FileOutputStream(testFile);
|
||||||
|
|
||||||
|
for (int i = 1; i <= TEST_CONTENT.length; i++) {
|
||||||
|
String randomString = TEST_CONTENT[i - 1] + "\n";
|
||||||
|
numLines.put(i, randomString.length());
|
||||||
|
fos.write(randomString.getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
fos.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws FileNotFoundException {
|
||||||
|
testBufferedReader = new BufferedReader(new java.io.FileReader(TEST_FILE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
try {
|
||||||
|
if (testBufferedReader != null) {
|
||||||
|
testBufferedReader.close();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void tearDownAfterClass() {
|
||||||
|
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
|
||||||
|
void testDeprecatedConstructor() {
|
||||||
|
try (FileReader fr = new FileReader(new File(TEST_FILE))) {
|
||||||
|
assertNotNull(fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testInit() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderWithBufferedReader() {
|
||||||
|
try (FileReader fileReader = new FileReader(testBufferedReader)) {
|
||||||
|
Iterator<FileReader.LineInfo> iterator = fileReader.iterator();
|
||||||
|
|
||||||
|
assertTrue(iterator.hasNext());
|
||||||
|
FileReader.LineInfo lineInfo = iterator.next();
|
||||||
|
assertEquals(1, lineInfo.getLineNumber());
|
||||||
|
assertEquals("Line 1", lineInfo.getLine());
|
||||||
|
|
||||||
|
assertTrue(iterator.hasNext());
|
||||||
|
lineInfo = iterator.next();
|
||||||
|
assertEquals(2, lineInfo.getLineNumber());
|
||||||
|
assertEquals("Line 2", lineInfo.getLine());
|
||||||
|
|
||||||
|
assertTrue(iterator.hasNext());
|
||||||
|
lineInfo = iterator.next();
|
||||||
|
assertEquals(3, lineInfo.getLineNumber());
|
||||||
|
assertEquals("Line 3", lineInfo.getLine());
|
||||||
|
|
||||||
|
assertFalse(iterator.hasNext());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderWithFile() {
|
||||||
|
try (FileReader fileReader = new FileReader(TEST_FILE)) {
|
||||||
|
// Add assertions based on the content of the file
|
||||||
|
Iterator<FileReader.LineInfo> iterator = fileReader.iterator();
|
||||||
|
|
||||||
|
assertTrue(iterator.hasNext());
|
||||||
|
FileReader.LineInfo lineInfo = iterator.next();
|
||||||
|
assertNotNull(lineInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderWithNonexistentFile() {
|
||||||
|
// Provide the path to a nonexistent file for testing
|
||||||
|
String filePath = "path/to/nonexistent/file.txt";
|
||||||
|
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException
|
||||||
|
assertThrows(NullPointerException.class, () -> new FileReader(filePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNullFile() {
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException with a null file
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((String) null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNullBufferedReader() {
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException with a null BufferedReader
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((BufferedReader) null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNonexistentResource() {
|
||||||
|
// Provide the name of a nonexistent resource for testing
|
||||||
|
String resourceName = "nonexistent_resource.txt";
|
||||||
|
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException
|
||||||
|
assertThrows(NullPointerException.class, () -> new FileReader(resourceName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithInvalidResource() {
|
||||||
|
// Provide the name of an invalid resource for testing
|
||||||
|
String resourceName = "invalid_resource.txt";
|
||||||
|
|
||||||
|
// Ensure that the constructor throws a RuntimeException
|
||||||
|
assertThrows(RuntimeException.class, () -> new FileReader(resourceName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNullPath() {
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException with a null path
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((Path) null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNonexistentPath() {
|
||||||
|
// Provide a nonexistent path for testing
|
||||||
|
Path path = Paths.get("nonexistent_path.txt");
|
||||||
|
|
||||||
|
// Ensure that the constructor throws a RuntimeException
|
||||||
|
assertThrows(RuntimeException.class, () -> new FileReader(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderInitWithNonRegularFile() {
|
||||||
|
// Provide the path to a non-regular file for testing
|
||||||
|
Path path = Paths.get("path/to/non_regular_file");
|
||||||
|
|
||||||
|
// Ensure that the constructor throws an IllegalArgumentException
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderHasNextIOException() {
|
||||||
|
// Provide a BufferedReader that throws an IOException when reading
|
||||||
|
BufferedReader bufferedReader = new BufferedReader(new StringReader(TEST_FILE)) {
|
||||||
|
@Override
|
||||||
|
public String readLine() throws IOException {
|
||||||
|
throw new IOException("Simulated IOException");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try (FileReader fileReader = new FileReader(bufferedReader)) {
|
||||||
|
Iterator<FileReader.LineInfo> iterator = fileReader.iterator();
|
||||||
|
|
||||||
|
assertThrows(RuntimeException.class, iterator::hasNext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileReaderNextNoMoreElements() {
|
||||||
|
// Provide a BufferedReader with no more elements for testing
|
||||||
|
BufferedReader bufferedReader = new BufferedReader(new StringReader(""));
|
||||||
|
|
||||||
|
try (FileReader fileReader = new FileReader(bufferedReader)) {
|
||||||
|
Iterator<FileReader.LineInfo> iterator = fileReader.iterator();
|
||||||
|
|
||||||
|
assertThrows(NoSuchElementException.class, iterator::next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/test/java/net/locusworks/common/utils/HashUtilsTest.java
Normal file
36
src/test/java/net/locusworks/common/utils/HashUtilsTest.java
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class HashUtilsTest {
|
||||||
|
|
||||||
|
private static final String TEST_STRING = "Hello World";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMD5() {
|
||||||
|
String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes());
|
||||||
|
String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING);
|
||||||
|
|
||||||
|
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSHA1() {
|
||||||
|
String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes());
|
||||||
|
String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING);
|
||||||
|
|
||||||
|
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSHA512() {
|
||||||
|
String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes());
|
||||||
|
String hashUtilsMD5 = HashUtils.hash("SHA-512", TEST_STRING);
|
||||||
|
|
||||||
|
assertEquals(digestUtilsMD5, hashUtilsMD5);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import static net.locusworks.common.utils.ObjectUtils.performIfNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
class ObjectUtilsTest {
|
||||||
|
|
||||||
|
private static final String TEST_FILE = "object-utils-test.txt";
|
||||||
|
private static Path testFile;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void setUpBeforeClass() throws Exception {
|
||||||
|
Path classpathRoot = Paths.get(Objects.requireNonNull(ObjectUtilsTest.class.getResource("/")).toURI());
|
||||||
|
testFile = classpathRoot.resolve(TEST_FILE);
|
||||||
|
Files.writeString(testFile, "test resource");
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void tearDownAfterClass() throws Exception {
|
||||||
|
Files.deleteIfExists(testFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testNullObject() {
|
||||||
|
performIfNotNull(null, str -> fail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testNotNullObject() {
|
||||||
|
String str = "hello world";
|
||||||
|
performIfNotNull(str, obj -> assertEquals(str, obj));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getResourceStream_whenResourceExists_ReturnsInputStream() throws Exception {
|
||||||
|
try (InputStream result = ObjectUtils.getResourceStream("/" + TEST_FILE)) {
|
||||||
|
assertNotNull(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getResourceStream_whenResourceDoesNotExist_ThrowsException() {
|
||||||
|
// Arrange
|
||||||
|
String resourceName = "nonexistent.txt";
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
assertThrows(NullPointerException.class,
|
||||||
|
() -> ObjectUtils.getResourceStream(resourceName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getResourceStream_whenResourceExistsInClassLoader_ReturnsInputStream() throws Exception {
|
||||||
|
try (InputStream result = ObjectUtils.getResourceStream(TEST_FILE)) {
|
||||||
|
assertNotNull(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getResourceStream_whenResourceDoesNotExistInClassLoader_ThrowsException() {
|
||||||
|
// Arrange
|
||||||
|
String resourceName = "nonexistent.txt";
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
assertThrows(NullPointerException.class,
|
||||||
|
() -> ObjectUtils.getResourceStream(resourceName));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
83
src/test/java/net/locusworks/common/utils/SplitterTest.java
Normal file
83
src/test/java/net/locusworks/common/utils/SplitterTest.java
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
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.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
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.assertEquals;
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class UtilityWrappersTest {
|
||||||
|
@Test
|
||||||
|
void successFactoriesAndConstructorExposeBodyAndStatus() {
|
||||||
|
assertTrue(Success.success().getSuccess());
|
||||||
|
assertEquals(true, Success.success().getBody());
|
||||||
|
assertFalse(Success.fail().getSuccess());
|
||||||
|
assertEquals(false, Success.fail().getBody());
|
||||||
|
Success value = new Success(true, "body");
|
||||||
|
assertEquals("body", value.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void dataOutputStreamConvertsAndClosesByteArrayOutput() throws Exception {
|
||||||
|
DataOutputStreamHelper stream = new DataOutputStreamHelper();
|
||||||
|
stream.write("hello".getBytes(StandardCharsets.UTF_8));
|
||||||
|
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), stream.toByteArray());
|
||||||
|
assertEquals("hello", stream.toString());
|
||||||
|
assertEquals("aGVsbG8=", stream.base64Encoded());
|
||||||
|
stream.close();
|
||||||
|
assertArrayEquals(new byte[0], stream.toByteArray());
|
||||||
|
assertDoesNotThrow(stream::close);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void dataOutputStreamSupportsOtherOutputsAndSwallowsCloseFailure() throws Exception {
|
||||||
|
OutputStream custom = new OutputStream() {
|
||||||
|
@Override
|
||||||
|
public void write(int b) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "custom";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
throw new IllegalStateException("expected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
DataOutputStreamHelper stream = new DataOutputStreamHelper(custom);
|
||||||
|
assertEquals("custom", stream.toString());
|
||||||
|
assertDoesNotThrow(stream::close);
|
||||||
|
|
||||||
|
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||||
|
try (DataOutputStreamHelper explicit = new DataOutputStreamHelper(bytes)) {
|
||||||
|
explicit.writeByte(1);
|
||||||
|
assertArrayEquals(new byte[]{1}, explicit.toByteArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
import static org.mockito.Mockito.CALLS_REAL_METHODS;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
class UtilsPackageCoverageTest {
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
private static java.util.Date deserialize(String value) throws Exception {
|
||||||
|
JsonParser parser = mock(JsonParser.class);
|
||||||
|
when(parser.getText()).thenReturn(value);
|
||||||
|
return new DateTimeStampDeserializer().deserialize(parser, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void dateDeserializerHandlesEpochBuiltInCustomAndInvalidFormats() throws Exception {
|
||||||
|
assertEquals(1234L, deserialize("1234").getTime());
|
||||||
|
|
||||||
|
Locale original = Locale.getDefault();
|
||||||
|
Locale.setDefault(Locale.US);
|
||||||
|
try {
|
||||||
|
assertNotNull(deserialize("January 1, 2020"));
|
||||||
|
assertNotNull(deserialize("12/31/2020"));
|
||||||
|
assertNotNull(deserialize("Dec 31, 2020 1:02:03 PM"));
|
||||||
|
assertNull(deserialize("definitely-not-a-date"));
|
||||||
|
|
||||||
|
Field stylesField = DateTimeStampDeserializer.class.getDeclaredField("styles");
|
||||||
|
stylesField.setAccessible(true);
|
||||||
|
Integer[] styles = (Integer[]) stylesField.get(null);
|
||||||
|
Integer[] originalStyles = styles.clone();
|
||||||
|
java.util.Arrays.fill(styles, -1);
|
||||||
|
try {
|
||||||
|
assertNotNull(deserialize("12/31/2020"));
|
||||||
|
} finally {
|
||||||
|
System.arraycopy(originalStyles, 0, styles, 0, styles.length);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
Locale.setDefault(original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
@Test
|
||||||
|
void hashUtilsCoversEveryInputOverloadCaseAndFailure() throws Exception {
|
||||||
|
String expected = HashUtils.hash("SHA-256", "content");
|
||||||
|
byte[] bytes = "content".getBytes(StandardCharsets.UTF_8);
|
||||||
|
Path path = tempDir.resolve("hash.txt");
|
||||||
|
Files.write(path, bytes);
|
||||||
|
File file = path.toFile();
|
||||||
|
|
||||||
|
assertEquals(expected, HashUtils.hash("SHA-256", bytes));
|
||||||
|
assertEquals(expected, HashUtils.hash("SHA-256", path));
|
||||||
|
assertEquals(expected, HashUtils.hash("SHA-256", file));
|
||||||
|
assertEquals(expected.toUpperCase(Locale.ROOT), HashUtils.hash("SHA-256", file, false));
|
||||||
|
assertEquals(expected.toUpperCase(Locale.ROOT), HashUtils.hash("SHA-256", path, false));
|
||||||
|
assertEquals(expected, HashUtils.hash(new ByteArrayInputStream(bytes), "SHA-256"));
|
||||||
|
assertEquals(expected.toUpperCase(Locale.ROOT),
|
||||||
|
HashUtils.hash(new ByteArrayInputStream(bytes), "SHA-256", false));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> HashUtils.hash("SHA-256", tempDir.resolve("missing")));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> HashUtils.hash(new ByteArrayInputStream(bytes), "not-an-algorithm"));
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> HashUtils.hash(new java.io.InputStream() {
|
||||||
|
@Override public int read() throws IOException { throw new IOException("read failed"); }
|
||||||
|
}, "SHA-256"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fileReaderCoversResourceValidationIterationMutationAndFailures() throws Exception {
|
||||||
|
try (FileReader resource = new FileReader("test.properties")) {
|
||||||
|
assertTrue(resource.hasNext());
|
||||||
|
assertSame(resource, resource.iterator());
|
||||||
|
assertNotNull(resource.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((String) null));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((Path) null));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader(tempDir.resolve("missing")));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader(tempDir));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new FileReader((BufferedReader) null));
|
||||||
|
|
||||||
|
BufferedReader readFailure = new BufferedReader(new StringReader("")) {
|
||||||
|
@Override public String readLine() throws IOException { throw new IOException("read failed"); }
|
||||||
|
};
|
||||||
|
assertThrows(RuntimeException.class, () -> new FileReader(readFailure).hasNext());
|
||||||
|
|
||||||
|
BufferedReader closeFailure = new BufferedReader(new StringReader("")) {
|
||||||
|
@Override public void close() throws IOException { throw new IOException("close failed"); }
|
||||||
|
};
|
||||||
|
assertThrows(RuntimeException.class, () -> new FileReader(closeFailure).close());
|
||||||
|
|
||||||
|
FileReader nullReader = new FileReader(new BufferedReader(new StringReader("")));
|
||||||
|
Field readerField = FileReader.class.getDeclaredField("reader");
|
||||||
|
readerField.setAccessible(true);
|
||||||
|
readerField.set(nullReader, null);
|
||||||
|
assertDoesNotThrow(nullReader::close);
|
||||||
|
|
||||||
|
Path simulated = tempDir.resolve("simulated.txt");
|
||||||
|
try (MockedStatic<Files> files = mockStatic(Files.class, CALLS_REAL_METHODS)) {
|
||||||
|
files.when(() -> Files.notExists(simulated)).thenReturn(false);
|
||||||
|
files.when(() -> Files.isRegularFile(simulated)).thenReturn(true);
|
||||||
|
files.when(() -> Files.newBufferedReader(simulated)).thenThrow(new IOException("open failed"));
|
||||||
|
assertThrows(RuntimeException.class, () -> new FileReader(simulated));
|
||||||
|
}
|
||||||
|
|
||||||
|
FileReader.LineInfo info = new FileReader.LineInfo(1, "line");
|
||||||
|
info.setLineNumber(2);
|
||||||
|
info.setLineLength(10);
|
||||||
|
info.setLine("changed");
|
||||||
|
assertEquals(2, info.getLineNumber());
|
||||||
|
assertEquals(10, info.getLineLength());
|
||||||
|
assertEquals("changed", info.getLine());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singletonAndUtilityClassConstructorsAreCovered() throws Exception {
|
||||||
|
Field instance = RandomString.class.getDeclaredField("instance");
|
||||||
|
instance.setAccessible(true);
|
||||||
|
instance.set(null, null);
|
||||||
|
assertNotNull(RandomString.getInstance());
|
||||||
|
|
||||||
|
assertNotNull(new HashUtils());
|
||||||
|
assertNotNull(new Checks());
|
||||||
|
assertNotNull(new Utils());
|
||||||
|
assertNotNull(new Constants());
|
||||||
|
assertNotNull(new ObjectUtils());
|
||||||
|
assertNotNull(new StreamUtils());
|
||||||
|
assertNotNull(ObjectUtils.getResourceStream("/test.properties"));
|
||||||
|
|
||||||
|
assertEquals(List.of("a", "b"), StreamUtils.asStream(List.of("a", "b"), true).toList());
|
||||||
|
assertTrue(StreamUtils.asStream(new String[]{"a"}, true).isParallel());
|
||||||
|
}
|
||||||
|
}
|
||||||
520
src/test/java/net/locusworks/common/utils/UtilsTest.java
Normal file
520
src/test/java/net/locusworks/common/utils/UtilsTest.java
Normal file
@@ -0,0 +1,520 @@
|
|||||||
|
package net.locusworks.common.utils;
|
||||||
|
|
||||||
|
import net.locusworks.common.annotations.MapValue;
|
||||||
|
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.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.Set;
|
||||||
|
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);
|
||||||
|
java.util.Set<Object> 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() {
|
||||||
|
java.util.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,13 @@
|
|||||||
package net.locusworks.test;
|
package net.locusworks.test;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import org.junit.Test;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
import net.locusworks.common.crypto.AES;
|
import net.locusworks.common.crypto.AES;
|
||||||
import net.locusworks.common.utils.Utils;
|
import net.locusworks.common.utils.Utils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
public class AESEncryptionTest {
|
public class AESEncryptionTest {
|
||||||
|
|
||||||
@@ -12,29 +15,29 @@ public class AESEncryptionTest {
|
|||||||
public void testEncryption() {
|
public void testEncryption() {
|
||||||
try {
|
try {
|
||||||
String encrypted = AES.createInstance().encrypt("hello world");
|
String encrypted = AES.createInstance().encrypt("hello world");
|
||||||
Assert.assertTrue(String.format("Encrypted String is not blank? :%s", encrypted), !Utils.isEmptyString(encrypted));
|
assertFalse(Utils.isEmptyString(encrypted), String.format("Encrypted String is not blank? :%s", encrypted));
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
ex.printStackTrace(System.err);
|
ex.printStackTrace(System.err);
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDecryption() {
|
public void testDecryption() {
|
||||||
String testString ="hello world";
|
String testString = "hello world";
|
||||||
try {
|
try {
|
||||||
AES aes = AES.createInstance();
|
AES aes = AES.createInstance();
|
||||||
String encrypted = aes.encrypt(testString);
|
String encrypted = aes.encrypt(testString);
|
||||||
Assert.assertTrue(String.format("Encrypted String is not blank? :%s", encrypted), !Utils.isEmptyString(encrypted));
|
assertFalse(Utils.isEmptyString(encrypted), String.format("Encrypted String is not blank? :%s", encrypted));
|
||||||
|
|
||||||
String decrypted = aes.decrypt(encrypted);
|
String decrypted = aes.decrypt(encrypted);
|
||||||
Assert.assertTrue(String.format("Decrypted String is not blank? :%s", decrypted), !Utils.isEmptyString(encrypted));
|
assertFalse(Utils.isEmptyString(encrypted), String.format("Decrypted String is not blank? :%s", decrypted));
|
||||||
|
|
||||||
Assert.assertTrue("Test String and Original String the same? :%s", testString.equals(decrypted));
|
assertEquals(testString, decrypted, "Test String and Original String the same? :%s");
|
||||||
|
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
ex.printStackTrace(System.err);
|
ex.printStackTrace(System.err);
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
package net.locusworks.test;
|
|
||||||
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Suite;
|
|
||||||
import org.junit.runners.Suite.SuiteClasses;
|
|
||||||
|
|
||||||
@RunWith(Suite.class)
|
|
||||||
@SuiteClasses({ AESEncryptionTest.class, FileReaderTest.class, HashSaltTest.class, RandomStringTest.class })
|
|
||||||
public class AllTests {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -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,24 @@
|
|||||||
package net.locusworks.test;
|
package net.locusworks.test;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import org.junit.Test;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
import net.locusworks.common.crypto.HashSalt;
|
import net.locusworks.common.crypto.HashSalt;
|
||||||
import net.locusworks.common.utils.Utils;
|
import net.locusworks.common.utils.Utils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class HashSaltTest {
|
public class HashSaltTest {
|
||||||
|
|
||||||
private static String samplePassword="Hello World";
|
private static final String samplePassword = "Hello World";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testEncryption() {
|
public void testEncryption() {
|
||||||
try {
|
try {
|
||||||
String hashSalt = HashSalt.createHash(samplePassword);
|
String hashSalt = HashSalt.createHash(samplePassword);
|
||||||
Assert.assertTrue(String.format("Encrypted String is not blank? :%s", hashSalt), !Utils.isEmptyString(hashSalt));
|
assertFalse(Utils.isEmptyString(hashSalt), String.format("Encrypted String is not blank? :%s", hashSalt));
|
||||||
} catch(Exception ex) {
|
} catch (Exception ex) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,9 +27,9 @@ public class HashSaltTest {
|
|||||||
try {
|
try {
|
||||||
String hashSalt = HashSalt.createHash(samplePassword);
|
String hashSalt = HashSalt.createHash(samplePassword);
|
||||||
boolean decrypted = HashSalt.validatePassword(samplePassword, hashSalt);
|
boolean decrypted = HashSalt.validatePassword(samplePassword, hashSalt);
|
||||||
Assert.assertTrue("Test String and Original String the same? :%s", decrypted);
|
assertTrue(decrypted, "Test String and Original String the same? :%s");
|
||||||
} catch(Exception ex) {
|
} catch (Exception ex) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
package net.locusworks.test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import org.apache.commons.codec.digest.DigestUtils;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import net.locusworks.common.utils.HashUtils;
|
|
||||||
|
|
||||||
public class HashUtilsTest {
|
|
||||||
|
|
||||||
private static final String TEST_STRING = "Hello World";
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testMD5() throws Exception {
|
|
||||||
String digestUtilsMD5 = DigestUtils.md5Hex(TEST_STRING.getBytes());
|
|
||||||
String hashUtilsMD5 = HashUtils.hash("MD5", TEST_STRING);
|
|
||||||
|
|
||||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testSHA1() throws Exception {
|
|
||||||
String digestUtilsMD5 = DigestUtils.sha1Hex(TEST_STRING.getBytes());
|
|
||||||
String hashUtilsMD5 = HashUtils.hash("SHA-1", TEST_STRING);
|
|
||||||
|
|
||||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testSHA512() throws Exception {
|
|
||||||
String digestUtilsMD5 = DigestUtils.sha512Hex(TEST_STRING.getBytes());
|
|
||||||
String hashUtilsMD5 = HashUtils.hash("SHA-512", TEST_STRING);
|
|
||||||
|
|
||||||
assertTrue(digestUtilsMD5.equals(hashUtilsMD5));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,45 +1,63 @@
|
|||||||
package net.locusworks.test;
|
package net.locusworks.test;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import net.locusworks.common.immutables.Pair;
|
import net.locusworks.common.immutables.Pair;
|
||||||
import net.locusworks.common.immutables.Triplet;
|
import net.locusworks.common.immutables.Triplet;
|
||||||
import net.locusworks.common.immutables.Unit;
|
import net.locusworks.common.immutables.Unit;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
public class ImmutablesTest {
|
public class ImmutablesTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testUnit() {
|
public void testUnit() {
|
||||||
Unit<String> unit = new Unit<>("Hello World");
|
Unit<String> unit1 = new Unit<>("Hello World");
|
||||||
assertTrue(unit.getValue1().equals("Hello World"));
|
Unit<String> unit3 = new Unit<>("Hello World");
|
||||||
|
assertEquals("Hello World", unit1.getValue1());
|
||||||
|
|
||||||
Unit<Integer> unit2 = new Unit<>(2);
|
Unit<Integer> unit2 = new Unit<>(2);
|
||||||
assertTrue(unit2.getValue1().equals(2));
|
assertEquals(2, (int) unit2.getValue1());
|
||||||
|
|
||||||
|
assertEquals(unit1, unit3);
|
||||||
|
assertNotEquals(unit1, unit2);
|
||||||
|
assertNotEquals(unit1, new Object());
|
||||||
|
assertNotEquals(unit1, null);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testPair() {
|
public void testPair() {
|
||||||
Pair<String, String> pair1 = new Pair<>("Hello", "World");
|
Pair<String, String> pair1 = new Pair<>("Hello", "World");
|
||||||
assertTrue(pair1.getValue1().equals("Hello"));
|
Pair<String, String> pair2 = new Pair<>("Hello", "World");
|
||||||
assertTrue(pair1.getValue2().equals("World"));
|
Pair<String, String> pair3 = new Pair<>("Hello", "World2");
|
||||||
|
assertEquals("Hello", pair1.getValue1());
|
||||||
|
assertEquals("World", pair1.getValue2());
|
||||||
|
assertEquals(pair1, pair2);
|
||||||
|
|
||||||
Pair<String, Integer> pair2 = new Pair<>("Foo", 25);
|
assertNotEquals(pair1, pair3);
|
||||||
assertTrue(pair2.getValue1().equals("Foo"));
|
assertNotEquals(pair1, new Object());
|
||||||
assertTrue(pair2.getValue2().equals(25));
|
assertNotEquals(pair1, null);
|
||||||
|
|
||||||
Pair<Integer, Integer> pair3 = new Pair<>(1, 23);
|
|
||||||
assertTrue(pair3.getValue1().equals(1));
|
|
||||||
assertTrue(pair3.getValue2().equals(23));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testTriplet() {
|
public void testTriplet() {
|
||||||
Triplet<String, Integer, String> triplet1 = new Triplet<>("Hello", 24, "World");
|
Triplet<String, Integer, String> triplet1 = new Triplet<>("Hello", 24, "World");
|
||||||
assertTrue(triplet1.getValue1().equals("Hello"));
|
Triplet<String, Integer, String> triplet2 = new Triplet<>("Hello", 25, "World");
|
||||||
assertTrue(triplet1.getValue2().equals(24));
|
Triplet<String, Integer, String> triplet3 = new Triplet<>("Hello", 24, "World2");
|
||||||
assertTrue(triplet1.getValue3().equals("World"));
|
Triplet<String, Integer, String> triplet4 = new Triplet<>("Hello", 24, "World");
|
||||||
|
|
||||||
|
assertEquals("Hello", triplet1.getValue1());
|
||||||
|
assertEquals(24, (int) triplet1.getValue2());
|
||||||
|
assertEquals("World", triplet1.getValue3());
|
||||||
|
assertEquals(triplet1, triplet4);
|
||||||
|
|
||||||
|
assertNotEquals(triplet1, triplet2);
|
||||||
|
assertNotEquals(triplet1, triplet3);
|
||||||
|
assertNotEquals(triplet1, new Object());
|
||||||
|
assertNotEquals(triplet1, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,20 +3,20 @@
|
|||||||
*/
|
*/
|
||||||
package net.locusworks.test;
|
package net.locusworks.test;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.AfterClass;
|
|
||||||
import org.junit.BeforeClass;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import net.locusworks.common.immutables.Triplet;
|
import net.locusworks.common.immutables.Triplet;
|
||||||
import net.locusworks.common.objectmapper.ObjectMapperHelper;
|
import net.locusworks.common.objectmapper.ObjectMapperHelper;
|
||||||
import net.locusworks.common.utils.Utils;
|
import net.locusworks.common.utils.Utils;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import static net.locusworks.common.utils.Constants.JUNIT_TEST_CHECK;
|
import static net.locusworks.common.utils.Constants.JUNIT_TEST_CHECK;
|
||||||
import static net.locusworks.common.utils.Constants.LOG4J_CONFIG_PROPERTY;
|
import static net.locusworks.common.utils.Constants.LOG4J_CONFIG_PROPERTY;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test cases to test ObjectMapperHelper.class
|
* Test cases to test ObjectMapperHelper.class
|
||||||
@@ -31,14 +31,14 @@ public class ObjectMapperHelperTest {
|
|||||||
/**
|
/**
|
||||||
* @throws java.lang.Exception exception
|
* @throws java.lang.Exception exception
|
||||||
*/
|
*/
|
||||||
@BeforeClass
|
@BeforeAll
|
||||||
public static void setUpBeforeClass() throws Exception {
|
public static void setUpBeforeClass() throws Exception {
|
||||||
System.setProperty(LOG4J_CONFIG_PROPERTY, "log4j2-test.xml");
|
System.setProperty(LOG4J_CONFIG_PROPERTY, "log4j2-test.xml");
|
||||||
System.setProperty(JUNIT_TEST_CHECK, "true");
|
System.setProperty(JUNIT_TEST_CHECK, "true");
|
||||||
test = new Triplet<String, Integer, String>("Hello", 24, "World");
|
test = new Triplet<String, Integer, String>("Hello", 24, "World");
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterClass
|
@AfterAll
|
||||||
public static void tearDownAfterClass() throws Exception {
|
public static void tearDownAfterClass() throws Exception {
|
||||||
System.clearProperty(LOG4J_CONFIG_PROPERTY);
|
System.clearProperty(LOG4J_CONFIG_PROPERTY);
|
||||||
System.clearProperty(JUNIT_TEST_CHECK);
|
System.clearProperty(JUNIT_TEST_CHECK);
|
||||||
@@ -56,8 +56,8 @@ public class ObjectMapperHelperTest {
|
|||||||
assertTrue(value != null && !value.trim().isEmpty());
|
assertTrue(value != null && !value.trim().isEmpty());
|
||||||
|
|
||||||
Triplet<?, ?, ?> tmp = ObjectMapperHelper.readValue(value, Triplet.class).getResults();
|
Triplet<?, ?, ?> tmp = ObjectMapperHelper.readValue(value, Triplet.class).getResults();
|
||||||
assertTrue(tmp != null);
|
assertNotNull(tmp);
|
||||||
assertTrue(tmp.equals(test));
|
assertEquals(tmp, test);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
@@ -67,7 +67,7 @@ public class ObjectMapperHelperTest {
|
|||||||
String value = ObjectMapperHelper.writeValue(htrList).getResults();
|
String value = ObjectMapperHelper.writeValue(htrList).getResults();
|
||||||
assertTrue(value != null && !value.trim().isEmpty());
|
assertTrue(value != null && !value.trim().isEmpty());
|
||||||
List<Triplet> tmpList = ObjectMapperHelper.readListValue(value, Triplet.class).getResults();
|
List<Triplet> tmpList = ObjectMapperHelper.readListValue(value, Triplet.class).getResults();
|
||||||
assertTrue(tmpList != null && tmpList.size() > 0);
|
assertTrue(tmpList != null && !tmpList.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package net.locusworks.test;
|
package net.locusworks.test;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -8,13 +11,13 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import org.junit.AfterClass;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import net.locusworks.common.configuration.PropertiesManager;
|
import net.locusworks.common.configuration.PropertiesManager;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test cases for the properties manager class
|
* Test cases for the properties manager class
|
||||||
|
*
|
||||||
* @author Isaac Parenteau
|
* @author Isaac Parenteau
|
||||||
* @since 1.0.0-RELEASE
|
* @since 1.0.0-RELEASE
|
||||||
*
|
*
|
||||||
@@ -25,13 +28,13 @@ public class PropertiesManagerTest {
|
|||||||
private static final String TMP_PROPS = "temp.properties";
|
private static final String TMP_PROPS = "temp.properties";
|
||||||
private static final int ENTRY_SIZE = 4;
|
private static final int ENTRY_SIZE = 4;
|
||||||
|
|
||||||
public static enum Configuration {
|
public enum Configuration {
|
||||||
DB_HOST("dbHost"),
|
DB_HOST("dbHost"),
|
||||||
DB_PORT("dbPort"),
|
DB_PORT("dbPort"),
|
||||||
USER_EXPIRATION_DAYS("userExpirationDays"),
|
USER_EXPIRATION_DAYS("userExpirationDays"),
|
||||||
LOG_LEVEL("logLevel");
|
LOG_LEVEL("logLevel");
|
||||||
|
|
||||||
private String value;
|
private final String value;
|
||||||
|
|
||||||
private Configuration(String value) {
|
private Configuration(String value) {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
@@ -39,6 +42,7 @@ public class PropertiesManagerTest {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the current value of the enumeration
|
* Get the current value of the enumeration
|
||||||
|
*
|
||||||
* @return value
|
* @return value
|
||||||
*/
|
*/
|
||||||
public String getValue() {
|
public String getValue() {
|
||||||
@@ -51,7 +55,7 @@ public class PropertiesManagerTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterClass
|
@AfterAll
|
||||||
public static void removeSavedProps() {
|
public static void removeSavedProps() {
|
||||||
File tmp = new File(TMP_PROPS);
|
File tmp = new File(TMP_PROPS);
|
||||||
if (tmp.exists()) {
|
if (tmp.exists()) {
|
||||||
@@ -63,7 +67,7 @@ public class PropertiesManagerTest {
|
|||||||
public void testPropertiesLoad() {
|
public void testPropertiesLoad() {
|
||||||
try {
|
try {
|
||||||
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
||||||
assertTrue(props != null);
|
assertNotNull(props);
|
||||||
assertTrue(props.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
assertTrue(props.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
||||||
assertTrue(props.containsKey(Configuration.DB_HOST.toString()));
|
assertTrue(props.containsKey(Configuration.DB_HOST.toString()));
|
||||||
assertTrue(props.containsKey(Configuration.DB_PORT.toString()));
|
assertTrue(props.containsKey(Configuration.DB_PORT.toString()));
|
||||||
@@ -78,9 +82,9 @@ public class PropertiesManagerTest {
|
|||||||
try {
|
try {
|
||||||
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
||||||
Properties tmp = new Properties();
|
Properties tmp = new Properties();
|
||||||
assertTrue(tmp.keySet().size() == 0);
|
assertEquals(0, tmp.size());
|
||||||
PropertiesManager.addConfiguration(tmp, props);
|
PropertiesManager.addConfiguration(tmp, props);
|
||||||
assertTrue(tmp.keySet().size() == ENTRY_SIZE);
|
assertEquals(ENTRY_SIZE, tmp.size());
|
||||||
assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
||||||
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
|
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
|
||||||
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));
|
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));
|
||||||
@@ -95,11 +99,12 @@ public class PropertiesManagerTest {
|
|||||||
try {
|
try {
|
||||||
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
Properties props = PropertiesManager.loadConfiguration(this.getClass(), PROPERTIES_FILE);
|
||||||
Properties tmp = new Properties();
|
Properties tmp = new Properties();
|
||||||
assertTrue(props.keySet().size() == ENTRY_SIZE);
|
assert props != null;
|
||||||
assertTrue(tmp.keySet().size() == 0);
|
assertEquals(ENTRY_SIZE, props.size());
|
||||||
|
assertEquals(0, tmp.size());
|
||||||
PropertiesManager.removeConfiguration(props, tmp);
|
PropertiesManager.removeConfiguration(props, tmp);
|
||||||
assertTrue(props.keySet().size() == 0);
|
assertEquals(0, props.size());
|
||||||
assertTrue(tmp.keySet().size() == 0);
|
assertEquals(0, tmp.size());
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
fail(e.getMessage());
|
fail(e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -112,7 +117,7 @@ public class PropertiesManagerTest {
|
|||||||
Path tmpFile = Paths.get(TMP_PROPS);
|
Path tmpFile = Paths.get(TMP_PROPS);
|
||||||
PropertiesManager.saveConfiguration(props, tmpFile, "test propertis");
|
PropertiesManager.saveConfiguration(props, tmpFile, "test propertis");
|
||||||
Properties tmp = PropertiesManager.loadConfiguration(tmpFile);
|
Properties tmp = PropertiesManager.loadConfiguration(tmpFile);
|
||||||
assertTrue(tmp.keySet().size() == ENTRY_SIZE);
|
assertEquals(ENTRY_SIZE, tmp.size());
|
||||||
assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
assertTrue(tmp.containsKey(Configuration.USER_EXPIRATION_DAYS.toString()));
|
||||||
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
|
assertTrue(tmp.containsKey(Configuration.DB_HOST.toString()));
|
||||||
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));
|
assertTrue(tmp.containsKey(Configuration.DB_PORT.toString()));
|
||||||
|
|||||||
@@ -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