added finalguard Javac plugin
All checks were successful
CI / build (push) Successful in 38s

This commit is contained in:
2025-11-19 01:34:14 +08:00
parent c5e4690856
commit 3f2666fe7e
86 changed files with 1022 additions and 1000 deletions

View File

@@ -1,9 +1,22 @@
import javax.tools.Diagnostic
plugins { plugins {
id 'java-library' id 'java-library'
id 'maven-publish' id 'maven-publish'
id 'jacoco' id 'jacoco'
alias(catalog.plugins.lombok) alias(catalog.plugins.lombok)
alias(catalog.plugins.sambal) alias(catalog.plugins.sambal)
alias(catalog.plugins.finalguard)
}
finalGuard {
// defaultLevel = Diagnostic.Kind.ERROR
methodParameterLevel = Diagnostic.Kind.ERROR
// lambdaParameterLevel = Diagnostic.Kind.ERROR
tryWithResourceLevel = Diagnostic.Kind.ERROR
catchParameterLevel = Diagnostic.Kind.ERROR
forLoopParameterLevel = Diagnostic.Kind.ERROR
localVariableLevel = Diagnostic.Kind.ERROR
} }
allprojects { allprojects {
@@ -11,6 +24,11 @@ allprojects {
version = getProperty('jwo.version') version = getProperty('jwo.version')
repositories { repositories {
mavenLocal {
content {
includeGroup 'net.woggioni.finalguard'
}
}
maven { maven {
url = getProperty('gitea.maven.url') url = getProperty('gitea.maven.url')
} }
@@ -31,6 +49,7 @@ allprojects {
testImplementation catalog.junit.jupiter.api testImplementation catalog.junit.jupiter.api
testImplementation catalog.junit.jupiter.params testImplementation catalog.junit.jupiter.params
testRuntimeOnly catalog.junit.jupiter.engine testRuntimeOnly catalog.junit.jupiter.engine
testRuntimeOnly catalog.junit.platform.launcher
} }
test { test {

View File

@@ -3,6 +3,6 @@ org.gradle.parallel=true
org.gradle.caching=true org.gradle.caching=true
gitea.maven.url = https://gitea.woggioni.net/api/packages/woggioni/maven gitea.maven.url = https://gitea.woggioni.net/api/packages/woggioni/maven
jwo.version = 2025.06.10 jwo.version = 2025.11.19
lys.version = 2025.06.03 lys.version = 2025.11.19
guice.version = 5.0.1 guice.version = 5.0.1

View File

@@ -31,11 +31,11 @@ public class Application {
private static final String MAC_FOLDER_LIBRARY = "Library"; private static final String MAC_FOLDER_LIBRARY = "Library";
private static final String MAC_FOLDER_APPLICATION_SUPPORT = "Application Support"; private static final String MAC_FOLDER_APPLICATION_SUPPORT = "Application Support";
public static Builder builder(String name) { public static Builder builder(final String name) {
return new Builder().name(name); return new Builder().name(name);
} }
private static boolean validateDirectory(Path candidate, boolean writable) { private static boolean validateDirectory(final Path candidate, final boolean writable) {
try { try {
if (!Files.exists(candidate)) { if (!Files.exists(candidate)) {
Files.createDirectories(candidate); Files.createDirectories(candidate);
@@ -51,7 +51,7 @@ public class Application {
log.trace("Selected existing directory '{}'", candidate); log.trace("Selected existing directory '{}'", candidate);
return true; return true;
} }
} catch (Exception ioe) { } catch (final Exception ioe) {
log.trace( log.trace(
String.format("Directory '%s' discarded: %s", candidate.toString(), ioe.getMessage()), String.format("Directory '%s' discarded: %s", candidate.toString(), ioe.getMessage()),
ioe ioe
@@ -61,7 +61,7 @@ public class Application {
} }
@SneakyThrows @SneakyThrows
private Path selectDirectory(Stream<Path> candidates, boolean writable, String successMessage, String errorMessage) { private Path selectDirectory(final Stream<Path> candidates, final boolean writable, final String successMessage, final String errorMessage) {
return candidates return candidates
.filter(p -> validateDirectory(p, writable)) .filter(p -> validateDirectory(p, writable))
.peek(p -> log.debug(successMessage, p)) .peek(p -> log.debug(successMessage, p))
@@ -71,7 +71,7 @@ public class Application {
@SneakyThrows @SneakyThrows
public Path computeCacheDirectory() { public Path computeCacheDirectory() {
Stream<Path> commonCandidates = optional2Stream( final Stream<Path> commonCandidates = optional2Stream(
Optional.ofNullable(cacheDirectoryPropertyKey).map(System::getProperty).map(Paths::get), Optional.ofNullable(cacheDirectoryPropertyKey).map(System::getProperty).map(Paths::get),
Optional.ofNullable(cacheDirectoryEnvVar).map(System::getenv).map(Paths::get) Optional.ofNullable(cacheDirectoryEnvVar).map(System::getenv).map(Paths::get)
); );
@@ -107,7 +107,7 @@ public class Application {
@SneakyThrows @SneakyThrows
public Path computeDataDirectory() { public Path computeDataDirectory() {
Stream<Path> commonCandidates = optional2Stream( final Stream<Path> commonCandidates = optional2Stream(
Optional.ofNullable(dataDirectoryPropertyKey).map(System::getProperty).map(Paths::get), Optional.ofNullable(dataDirectoryPropertyKey).map(System::getProperty).map(Paths::get),
Optional.ofNullable(dataDirectoryEnvVar).map(System::getenv).map(Paths::get) Optional.ofNullable(dataDirectoryEnvVar).map(System::getenv).map(Paths::get)
); );
@@ -142,8 +142,8 @@ public class Application {
} }
@SneakyThrows @SneakyThrows
public Path computeConfigurationDirectory(boolean writable) { public Path computeConfigurationDirectory(final boolean writable) {
Stream<Path> commonCandidates = optional2Stream( final Stream<Path> commonCandidates = optional2Stream(
Optional.ofNullable(configurationDirectoryPropertyKey).map(System::getProperty).map(Paths::get), Optional.ofNullable(configurationDirectoryPropertyKey).map(System::getProperty).map(Paths::get),
Optional.ofNullable(configurationDirectoryEnvVar).map(System::getenv).map(Paths::get) Optional.ofNullable(configurationDirectoryEnvVar).map(System::getenv).map(Paths::get)
); );

View File

@@ -8,9 +8,9 @@ import java.util.function.BiConsumer;
public interface BiCon<T, U> extends BiConsumer<T, U> { public interface BiCon<T, U> extends BiConsumer<T, U> {
@Override @Override
@SneakyThrows @SneakyThrows
default void accept(T t, U u) { default void accept(final T t, final U u) {
exec(t, u); exec(t, u);
} }
void exec(T t, U u) throws Throwable; void exec(final T t, final U u) throws Throwable;
} }

View File

@@ -8,9 +8,9 @@ import java.util.function.BiFunction;
public interface BiFun<T, U, V> extends BiFunction<T, U, V> { public interface BiFun<T, U, V> extends BiFunction<T, U, V> {
@Override @Override
@SneakyThrows @SneakyThrows
default V apply(T t, U u) { default V apply(final T t, final U u) {
return exec(t, u); return exec(t, u);
} }
V exec(T t, U u) throws Throwable; V exec(final T t, final U u) throws Throwable;
} }

View File

@@ -19,7 +19,7 @@ public interface Bucket {
* @return false if the bucket did not contain enough token for the operation to complete, * @return false if the bucket did not contain enough token for the operation to complete,
* true otherwise (in the latter case nTokens are actually consumed) * true otherwise (in the latter case nTokens are actually consumed)
*/ */
default boolean removeTokens(long nTokens) { default boolean removeTokens(final long nTokens) {
return removeTokens(nTokens, System.nanoTime()); return removeTokens(nTokens, System.nanoTime());
} }
@@ -32,7 +32,7 @@ public interface Bucket {
* @return false if the bucket did not contain enough token for the operation to complete, * @return false if the bucket did not contain enough token for the operation to complete,
* true otherwise (in the latter case nTokens are actually consumed) * true otherwise (in the latter case nTokens are actually consumed)
*/ */
boolean removeTokens(long nTokens, long currentTimestamp); boolean removeTokens(final long nTokens, final long currentTimestamp);
/** /**
* Tries to consume nTokens from the bucket, returning -1 if the operation was successful or the amount of time * Tries to consume nTokens from the bucket, returning -1 if the operation was successful or the amount of time
@@ -44,7 +44,7 @@ public interface Bucket {
* {@link #removeTokensWithEstimate(long)} or {@link #removeTokens(long)} invocation with the same {@param nTokens} parameter * {@link #removeTokensWithEstimate(long)} or {@link #removeTokens(long)} invocation with the same {@param nTokens} parameter
* will succeed * will succeed
*/ */
default long removeTokensWithEstimate(long nTokens) { default long removeTokensWithEstimate(final long nTokens) {
return removeTokensWithEstimate(nTokens, System.nanoTime()); return removeTokensWithEstimate(nTokens, System.nanoTime());
} }
@@ -59,13 +59,13 @@ public interface Bucket {
* {@link #removeTokensWithEstimate(long)} or {@link #removeTokens(long)} invocation with the same {@param nTokens} parameter * {@link #removeTokensWithEstimate(long)} or {@link #removeTokens(long)} invocation with the same {@param nTokens} parameter
* will succeed * will succeed
*/ */
long removeTokensWithEstimate(long nTokens, long currentTimestamp); long removeTokensWithEstimate(final long nTokens, final long currentTimestamp);
static Bucket local(long maxCapacity, long fillAmount, Duration fillPeriod) { static Bucket local(final long maxCapacity, final long fillAmount, final Duration fillPeriod) {
return local(maxCapacity, fillAmount, fillPeriod, maxCapacity); return local(maxCapacity, fillAmount, fillPeriod, maxCapacity);
} }
static Bucket local(long maxCapacity, long fillAmount, Duration fillPeriod, long initialAmount) { static Bucket local(final long maxCapacity, final long fillAmount, final Duration fillPeriod, final long initialAmount) {
return new LocalBucket(maxCapacity, fillAmount, fillPeriod.toNanos(), initialAmount); return new LocalBucket(maxCapacity, fillAmount, fillPeriod.toNanos(), initialAmount);
} }
} }

View File

@@ -13,15 +13,15 @@ public enum CPU {
private final String value; private final String value;
CPU(String value) { CPU(final String value) {
this.value = value; this.value = value;
} }
public static CPU current; public static CPU current;
static { static {
String archName = System.getProperty("os.arch").toLowerCase(); final String archName = System.getProperty("os.arch").toLowerCase();
for(CPU cpu : values()) { for(final CPU cpu : values()) {
if(archName.startsWith(cpu.value)) { if(archName.startsWith(cpu.value)) {
current = cpu; current = cpu;
} }

View File

@@ -15,14 +15,13 @@ public class ChannerWriter extends Writer {
private final Charset charset; private final Charset charset;
@Override @Override
public void write(char[] cbuf, int off, int len) throws IOException { public void write(final char[] cbuf, final int off, final int len) throws IOException {
write(new String(cbuf, off, len)); write(new String(cbuf, off, len));
} }
@Override @Override
public void write(String str) throws IOException { public void write(final String str) throws IOException {
ch.write(ByteBuffer.wrap(str.getBytes(charset))); ch.write(ByteBuffer.wrap(str.getBytes(charset)));
} }
@@ -34,3 +33,5 @@ public class ChannerWriter extends Writer {
ch.close(); ch.close();
} }
} }

View File

@@ -18,7 +18,7 @@ public class Chronometer {
public final long nanoseconds; public final long nanoseconds;
UnitOfMeasure(long nanoseconds) { UnitOfMeasure(final long nanoseconds) {
this.nanoseconds = nanoseconds; this.nanoseconds = nanoseconds;
} }
} }
@@ -38,7 +38,7 @@ public class Chronometer {
return System.nanoTime() - start; return System.nanoTime() - start;
} }
public double elapsed(UnitOfMeasure unitOfMeasure) { public double elapsed(final UnitOfMeasure unitOfMeasure) {
return ((double) (System.nanoTime() - start)) / unitOfMeasure.nanoseconds; return ((double) (System.nanoTime() - start)) / unitOfMeasure.nanoseconds;
} }
} }

View File

@@ -10,7 +10,7 @@ public class CircularBuffer {
private Reader reader; private Reader reader;
private int delta = 0, cursor = 0; private int delta = 0, cursor = 0;
public CircularBuffer(Reader reader, int size) { public CircularBuffer(final Reader reader, final int size) {
this.reader = reader; this.reader = reader;
buffer = new int[size]; buffer = new int[size];
} }
@@ -20,7 +20,7 @@ public class CircularBuffer {
if (delta < 0) if (delta < 0)
return buffer[Math.floorMod(cursor + delta++, buffer.length)]; return buffer[Math.floorMod(cursor + delta++, buffer.length)];
else { else {
int result = reader.read(); final int result = reader.read();
if (result < 0) return result; if (result < 0) return result;
buffer[cursor] = result; buffer[cursor] = result;
cursor = (cursor + 1) % buffer.length; cursor = (cursor + 1) % buffer.length;

View File

@@ -11,7 +11,7 @@ public class CircularInputStream extends InputStream {
int loops = 0; int loops = 0;
int cursor = 0; int cursor = 0;
public CircularInputStream(byte[] monomer) { public CircularInputStream(final byte[] monomer) {
this(monomer, -1); this(monomer, -1);
} }
@@ -20,18 +20,18 @@ public class CircularInputStream extends InputStream {
if (cursor < 0) { if (cursor < 0) {
return cursor; return cursor;
} else { } else {
int result = monomer[cursor]; final int result = monomer[cursor];
incrementCursor(); incrementCursor();
return result; return result;
} }
} }
@Override @Override
public int read(byte[] b, int off, int len) { public int read(final byte[] b, final int off, final int len) {
int read = 0; int read = 0;
while (read < len) { while (read < len) {
if(cursor < 0) break; if(cursor < 0) break;
int toBeRead = Math.min(monomer.length - cursor, len - read); final int toBeRead = Math.min(monomer.length - cursor, len - read);
System.arraycopy(monomer, cursor, b, off + read, toBeRead); System.arraycopy(monomer, cursor, b, off + read, toBeRead);
incrementCursor(toBeRead); incrementCursor(toBeRead);
read += toBeRead; read += toBeRead;
@@ -43,7 +43,7 @@ public class CircularInputStream extends InputStream {
return incrementCursor(1); return incrementCursor(1);
} }
int incrementCursor(int increment) { int incrementCursor(final int increment) {
loops = (loops * monomer.length + increment) / monomer.length; loops = (loops * monomer.length + increment) / monomer.length;
if (maxLoops < 0 || loops < maxLoops) { if (maxLoops < 0 || loops < maxLoops) {
cursor = (cursor + increment) % monomer.length; cursor = (cursor + increment) % monomer.length;

View File

@@ -30,7 +30,7 @@ public class CollectionUtils {
} }
@SafeVarargs @SafeVarargs
public static <T> ArrayList<T> newArrayList(T... args) { public static <T> ArrayList<T> newArrayList(final T... args) {
return new ArrayList<>(Arrays.asList(args)); return new ArrayList<>(Arrays.asList(args));
} }
@@ -46,7 +46,7 @@ public class CollectionUtils {
} }
@SafeVarargs @SafeVarargs
public static <T> List<T> immutableList(T... elements) { public static <T> List<T> immutableList(final T... elements) {
return Stream.of(elements).collect(toUnmodifiableList()); return Stream.of(elements).collect(toUnmodifiableList());
} }
@@ -62,12 +62,12 @@ public class CollectionUtils {
} }
@SafeVarargs @SafeVarargs
public static <T> Set<T> immutableSet(T... elements) { public static <T> Set<T> immutableSet(final T... elements) {
return Stream.of(elements).collect(toUnmodifiableSet()); return Stream.of(elements).collect(toUnmodifiableSet());
} }
private static <T> Collector<T, ?, NavigableSet<T>> private static <T> Collector<T, ?, NavigableSet<T>>
createTreeSetCollector(Function<NavigableSet<T>, NavigableSet<T>> finalizer, Comparator<? super T> comparator) { createTreeSetCollector(final Function<NavigableSet<T>, NavigableSet<T>> finalizer, final Comparator<? super T> comparator) {
return Collector.of( return Collector.of(
() -> new TreeSet<>(comparator), () -> new TreeSet<>(comparator),
Set::add, Set::add,
@@ -79,7 +79,7 @@ public class CollectionUtils {
} }
private static <T extends Comparable<T>> Collector<T, ?, NavigableSet<T>> private static <T extends Comparable<T>> Collector<T, ?, NavigableSet<T>>
createTreeSetCollector(Function<NavigableSet<T>, NavigableSet<T>> finalizer) { createTreeSetCollector(final Function<NavigableSet<T>, NavigableSet<T>> finalizer) {
return Collector.of( return Collector.of(
TreeSet::new, TreeSet::new,
Set::add, Set::add,
@@ -94,11 +94,11 @@ public class CollectionUtils {
return createTreeSetCollector(Function.identity()); return createTreeSetCollector(Function.identity());
} }
public static <T> Collector<T, ?, NavigableSet<T>> toTreeSet(Comparator<? super T> comparator) { public static <T> Collector<T, ?, NavigableSet<T>> toTreeSet(final Comparator<? super T> comparator) {
return createTreeSetCollector(Function.identity(), comparator); return createTreeSetCollector(Function.identity(), comparator);
} }
public static <T> Collector<T, ?, NavigableSet<T>> toUnmodifiableTreeSet(Comparator<? super T> comparator) { public static <T> Collector<T, ?, NavigableSet<T>> toUnmodifiableTreeSet(final Comparator<? super T> comparator) {
return createTreeSetCollector(Collections::unmodifiableNavigableSet, comparator); return createTreeSetCollector(Collections::unmodifiableNavigableSet, comparator);
} }
@@ -107,21 +107,21 @@ public class CollectionUtils {
} }
@SafeVarargs @SafeVarargs
public static <T> NavigableSet<T> immutableTreeSet(Comparator<? super T> comparator, T... elements) { public static <T> NavigableSet<T> immutableTreeSet(final Comparator<? super T> comparator, final T... elements) {
return Stream.of(elements).collect(toUnmodifiableTreeSet(comparator)); return Stream.of(elements).collect(toUnmodifiableTreeSet(comparator));
} }
@SafeVarargs @SafeVarargs
public static <T extends Comparable<T>> NavigableSet<T> immutableTreeSet(T... elements) { public static <T extends Comparable<T>> NavigableSet<T> immutableTreeSet(final T... elements) {
return Stream.of(elements).collect(toUnmodifiableTreeSet()); return Stream.of(elements).collect(toUnmodifiableTreeSet());
} }
private static <K, V, M extends Map<K, V>> BinaryOperator<M> mapMerger(BinaryOperator<V> var0) { private static <K, V, M extends Map<K, V>> BinaryOperator<M> mapMerger(final BinaryOperator<V> var0) {
return (m1, m2) -> { return (m1, m2) -> {
Iterator<Map.Entry<K, V>> it = m2.entrySet().iterator(); final Iterator<Map.Entry<K, V>> it = m2.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry<K, V> entry = it.next(); final Map.Entry<K, V> entry = it.next();
m1.merge(entry.getKey(), entry.getValue(), var0); m1.merge(entry.getKey(), entry.getValue(), var0);
} }
@@ -142,7 +142,7 @@ public class CollectionUtils {
return (v1, v2) -> v1; return (v1, v2) -> v1;
} }
private static <T> BinaryOperator<T> getMerger(MapMergeStrategy mapMergeStrategy) { private static <T> BinaryOperator<T> getMerger(final MapMergeStrategy mapMergeStrategy) {
BinaryOperator<T> result; BinaryOperator<T> result;
switch (mapMergeStrategy) { switch (mapMergeStrategy) {
case KEEP: case KEEP:
@@ -161,74 +161,74 @@ public class CollectionUtils {
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableHashMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableHashMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
return toUnmodifiableMap(HashMap::new, keyExtractor, valueExtractor, mapMergeStrategy); return toUnmodifiableMap(HashMap::new, keyExtractor, valueExtractor, mapMergeStrategy);
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableHashMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableHashMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toUnmodifiableMap(HashMap::new, keyExtractor, valueExtractor); return toUnmodifiableMap(HashMap::new, keyExtractor, valueExtractor);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toUnmodifiableNavigableMap(TreeMap::new, keyExtractor, valueExtractor); return toUnmodifiableNavigableMap(TreeMap::new, keyExtractor, valueExtractor);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
return toUnmodifiableNavigableMap(TreeMap::new, keyExtractor, valueExtractor, mapMergeStrategy); return toUnmodifiableNavigableMap(TreeMap::new, keyExtractor, valueExtractor, mapMergeStrategy);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
Comparator<K> comparator, final Comparator<K> comparator,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
return toUnmodifiableNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor, mapMergeStrategy); return toUnmodifiableNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor, mapMergeStrategy);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
Comparator<K> comparator) { final Comparator<K> comparator) {
return toUnmodifiableNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor); return toUnmodifiableNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
return toNavigableMap(TreeMap::new, keyExtractor, valueExtractor, mapMergeStrategy); return toNavigableMap(TreeMap::new, keyExtractor, valueExtractor, mapMergeStrategy);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toNavigableMap(TreeMap::new, keyExtractor, valueExtractor); return toNavigableMap(TreeMap::new, keyExtractor, valueExtractor);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
Comparator<K> comparator) { final Comparator<K> comparator) {
return toNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor); return toNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor);
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toTreeMap(
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
Comparator<K> comparator, final Comparator<K> comparator,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
return toNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor, mapMergeStrategy); return toNavigableMap(() -> new TreeMap<>(comparator), keyExtractor, valueExtractor, mapMergeStrategy);
} }
public static <T, K, V, MAP_TYPE extends NavigableMap<K, V>> Collector<T, ?, MAP_TYPE> toNavigableMap( public static <T, K, V, MAP_TYPE extends NavigableMap<K, V>> Collector<T, ?, MAP_TYPE> toNavigableMap(
Supplier<MAP_TYPE> constructor, final Supplier<MAP_TYPE> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toNavigableMap( return toNavigableMap(
constructor, constructor,
keyExtractor, keyExtractor,
@@ -238,12 +238,12 @@ public class CollectionUtils {
} }
public static <T, K, V, MAP_TYPE extends NavigableMap<K, V>> Collector<T, ?, MAP_TYPE> toNavigableMap( public static <T, K, V, MAP_TYPE extends NavigableMap<K, V>> Collector<T, ?, MAP_TYPE> toNavigableMap(
Supplier<MAP_TYPE> constructor, final Supplier<MAP_TYPE> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy); final BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy);
BiConsumer<MAP_TYPE, T> accumulator = (map, streamElement) -> { final BiConsumer<MAP_TYPE, T> accumulator = (map, streamElement) -> {
map.merge(keyExtractor.apply(streamElement), valueExtractor.apply(streamElement), map.merge(keyExtractor.apply(streamElement), valueExtractor.apply(streamElement),
valueMerger valueMerger
); );
@@ -256,19 +256,19 @@ public class CollectionUtils {
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toMap(
Supplier<Map<K, V>> constructor, final Supplier<Map<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW); return toMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW);
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toMap(
Supplier<Map<K, V>> constructor, final Supplier<Map<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy); final BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy);
BiConsumer<Map<K, V>, T> accumulator = (map, streamElement) -> { final BiConsumer<Map<K, V>, T> accumulator = (map, streamElement) -> {
map.merge(keyExtractor.apply(streamElement), valueExtractor.apply(streamElement), map.merge(keyExtractor.apply(streamElement), valueExtractor.apply(streamElement),
valueMerger valueMerger
); );
@@ -281,18 +281,18 @@ public class CollectionUtils {
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableMap(
Supplier<Map<K, V>> constructor, final Supplier<Map<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toUnmodifiableMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW); return toUnmodifiableMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW);
} }
public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableMap( public static <T, K, V> Collector<T, ?, Map<K, V>> toUnmodifiableMap(
Supplier<Map<K, V>> constructor, final Supplier<Map<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy) { final MapMergeStrategy mapMergeStrategy) {
BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy); final BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy);
BiConsumer<Map<K, V>, T> accumulator = (map, streamElement) -> { final BiConsumer<Map<K, V>, T> accumulator = (map, streamElement) -> {
map.merge(keyExtractor.apply(streamElement), map.merge(keyExtractor.apply(streamElement),
valueExtractor.apply(streamElement), valueExtractor.apply(streamElement),
valueMerger valueMerger
@@ -307,13 +307,13 @@ public class CollectionUtils {
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableNavigableMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableNavigableMap(
Supplier<NavigableMap<K, V>> constructor, final Supplier<NavigableMap<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor, final Function<T, V> valueExtractor,
MapMergeStrategy mapMergeStrategy final MapMergeStrategy mapMergeStrategy
) { ) {
BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy); final BinaryOperator<V> valueMerger = getMerger(mapMergeStrategy);
BiConsumer<NavigableMap<K, V>, T> accumulator = (map, streamElement) -> { final BiConsumer<NavigableMap<K, V>, T> accumulator = (map, streamElement) -> {
map.merge( map.merge(
keyExtractor.apply(streamElement), keyExtractor.apply(streamElement),
valueExtractor.apply(streamElement), valueExtractor.apply(streamElement),
@@ -328,19 +328,19 @@ public class CollectionUtils {
); );
} }
public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableNavigableMap( public static <T, K, V> Collector<T, ?, NavigableMap<K, V>> toUnmodifiableNavigableMap(
Supplier<NavigableMap<K, V>> constructor, final Supplier<NavigableMap<K, V>> constructor,
Function<T, K> keyExtractor, final Function<T, K> keyExtractor,
Function<T, V> valueExtractor) { final Function<T, V> valueExtractor) {
return toUnmodifiableNavigableMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW); return toUnmodifiableNavigableMap(constructor, keyExtractor, valueExtractor, MapMergeStrategy.THROW);
} }
public static <K, V, U> Stream<Map.Entry<K, U>> mapValues(Map<K, V> map, Fun<V, U> xform) { public static <K, V, U> Stream<Map.Entry<K, U>> mapValues(final Map<K, V> map, final Fun<V, U> xform) {
return map return map
.entrySet() .entrySet()
.stream() .stream()
.map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(), xform.apply(entry.getValue()))); .map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(), xform.apply(entry.getValue())));
} }
public static <T> Iterator<T> reverseIterator(List<T> list) { public static <T> Iterator<T> reverseIterator(final List<T> list) {
return new Iterator<T>() { return new Iterator<T>() {
private final ListIterator<T> it = list.listIterator(list.size()); private final ListIterator<T> it = list.listIterator(list.size());
@Override @Override
@@ -355,10 +355,10 @@ public class CollectionUtils {
}; };
} }
public static <T> Iterator<T> reverseIterator(NavigableSet<T> set) { public static <T> Iterator<T> reverseIterator(final NavigableSet<T> set) {
return set.descendingIterator(); return set.descendingIterator();
} }
public static <K, V> Iterator<Map.Entry<K, V>> reverseIterator(NavigableMap<K, V> map) { public static <K, V> Iterator<Map.Entry<K, V>> reverseIterator(final NavigableMap<K, V> map) {
return map.descendingMap().entrySet().iterator(); return map.descendingMap().entrySet().iterator();
} }
} }

View File

@@ -8,9 +8,9 @@ import java.util.function.Consumer;
public interface Con<T> extends Consumer<T> { public interface Con<T> extends Consumer<T> {
@Override @Override
@SneakyThrows @SneakyThrows
default void accept(T t) { default void accept(final T t) {
exec(t); exec(t);
} }
void exec(T t) throws Throwable; void exec(final T t) throws Throwable;
} }

View File

@@ -10,7 +10,7 @@ import static net.woggioni.jwo.JWO.streamCat;
public class DelegatingMap<K,V> extends UnmodifiableDelegatingMap<K, V> { public class DelegatingMap<K,V> extends UnmodifiableDelegatingMap<K, V> {
private final Map<K,V> thisMap; private final Map<K,V> thisMap;
public DelegatingMap(Supplier<Map<K,V>> mapFactory, List<Map<K,V>> delegates) { public DelegatingMap(final Supplier<Map<K,V>> mapFactory, final List<Map<K,V>> delegates) {
super(mapFactory, delegates); super(mapFactory, delegates);
thisMap = mapFactory.get(); thisMap = mapFactory.get();
} }
@@ -27,36 +27,36 @@ public class DelegatingMap<K,V> extends UnmodifiableDelegatingMap<K, V> {
} }
@Override @Override
public boolean containsKey(Object key) { public boolean containsKey(final Object key) {
if(thisMap.containsKey(key)) return true; if(thisMap.containsKey(key)) return true;
return super.containsKey(key); return super.containsKey(key);
} }
@Override @Override
public boolean containsValue(Object value) { public boolean containsValue(final Object value) {
if(thisMap.containsValue(value)) return true; if(thisMap.containsValue(value)) return true;
return super.containsValue(value); return super.containsValue(value);
} }
@Override @Override
public V get(Object key) { public V get(final Object key) {
return Optional.ofNullable(thisMap.get(key)).orElseGet( return Optional.ofNullable(thisMap.get(key)).orElseGet(
() -> super.get(key) () -> super.get(key)
); );
} }
@Override @Override
public V put(K key, V value) { public V put(final K key, final V value) {
return thisMap.put(key, value); return thisMap.put(key, value);
} }
@Override @Override
public V remove(Object key) { public V remove(final Object key) {
return thisMap.remove(key); return thisMap.remove(key);
} }
@Override @Override
public void putAll(Map<? extends K, ? extends V> m) { public void putAll(final Map<? extends K, ? extends V> m) {
this.thisMap.putAll(m); this.thisMap.putAll(m);
} }

View File

@@ -8,9 +8,9 @@ import java.util.function.Function;
public interface Fun<T, U> extends Function<T, U> { public interface Fun<T, U> extends Function<T, U> {
@Override @Override
@SneakyThrows @SneakyThrows
default U apply(T t) { default U apply(final T t) {
return exec(t); return exec(t);
} }
U exec(T t) throws Throwable; U exec(final T t) throws Throwable;
} }

View File

@@ -34,11 +34,11 @@ public class Hash {
return MessageDigest.getInstance(key); return MessageDigest.getInstance(key);
} }
@SneakyThrows @SneakyThrows
public DigestOutputStream newOutputStream(OutputStream delegate) { public DigestOutputStream newOutputStream(final OutputStream delegate) {
return new DigestOutputStream(delegate, MessageDigest.getInstance(key)); return new DigestOutputStream(delegate, MessageDigest.getInstance(key));
} }
@SneakyThrows @SneakyThrows
public DigestInputStream newInputStream(InputStream delegate) { public DigestInputStream newInputStream(final InputStream delegate) {
return new DigestInputStream(delegate, MessageDigest.getInstance(key)); return new DigestInputStream(delegate, MessageDigest.getInstance(key));
} }
} }
@@ -50,8 +50,8 @@ public class Hash {
private final byte[] bytes; private final byte[] bytes;
@SneakyThrows @SneakyThrows
public static Hash hash(Algorithm algo, InputStream is, byte[] buffer) { public static Hash hash(final Algorithm algo, final InputStream is, final byte[] buffer) {
MessageDigest md = MessageDigest.getInstance(algo.key); final MessageDigest md = MessageDigest.getInstance(algo.key);
int read; int read;
while((read = is.read(buffer, 0, buffer.length)) >= 0) { while((read = is.read(buffer, 0, buffer.length)) >= 0) {
md.update(buffer, 0, read); md.update(buffer, 0, read);
@@ -60,37 +60,37 @@ public class Hash {
} }
@SneakyThrows @SneakyThrows
public static Hash hash(Algorithm algo, InputStream is) { public static Hash hash(final Algorithm algo, final InputStream is) {
return hash(algo, is, new byte[0x1000]); return hash(algo, is, new byte[0x1000]);
} }
@SneakyThrows @SneakyThrows
public static Hash md5(InputStream is) { public static Hash md5(final InputStream is) {
return md5(is, new byte[0x1000]); return md5(is, new byte[0x1000]);
} }
@SneakyThrows @SneakyThrows
public static Hash md5(InputStream is, byte[] buffer) { public static Hash md5(final InputStream is, final byte[] buffer) {
return hash(Algorithm.MD5, is, buffer); return hash(Algorithm.MD5, is, buffer);
} }
public static String md5String(InputStream is) { public static String md5String(final InputStream is) {
return bytesToHex(md5(is).bytes); return bytesToHex(md5(is).bytes);
} }
final private static char[] hexArray = "0123456789ABCDEF".toCharArray(); final private static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) { public static String bytesToHex(final byte[] bytes) {
char[] hexChars = new char[bytes.length * 2]; final char[] hexChars = new char[bytes.length * 2];
for(int j = 0; j < bytes.length; j++) { for(int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF; final int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; hexChars[j * 2 + 1] = hexArray[v & 0x0F];
} }
return new String(hexChars); return new String(hexChars);
} }
private static int charToInt(char c) { private static int charToInt(final char c) {
if (c >= '0' && c <= '9') { if (c >= '0' && c <= '9') {
return c - '0'; return c - '0';
} else if(c >= 'a' && c <= 'f') { } else if(c >= 'a' && c <= 'f') {
@@ -102,14 +102,14 @@ public class Hash {
} }
} }
public static byte[] hexToBytes(String hexString) { public static byte[] hexToBytes(final String hexString) {
if (hexString.length() % 2 != 0) { if (hexString.length() % 2 != 0) {
throw newThrowable(IllegalArgumentException.class, "Hex string length must be even," + throw newThrowable(IllegalArgumentException.class, "Hex string length must be even," +
" string has length '%d' instead", hexString.length()); " string has length '%d' instead", hexString.length());
} }
byte[] result = new byte[hexString.length() / 2]; final byte[] result = new byte[hexString.length() / 2];
for(int i = 0; i < hexString.length(); i++) { for(int i = 0; i < hexString.length(); i++) {
int value = charToInt(hexString.charAt(i)); final int value = charToInt(hexString.charAt(i));
if (i % 2 == 0) { if (i % 2 == 0) {
result[i / 2] += (byte) (value << 4); result[i / 2] += (byte) (value << 4);
} else { } else {
@@ -119,13 +119,13 @@ public class Hash {
return result; return result;
} }
public static byte[] hexToBytes2(String hexString) { public static byte[] hexToBytes2(final String hexString) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (hexString.length() % 2 != 0) { if (hexString.length() % 2 != 0) {
throw newThrowable(IllegalArgumentException.class, "Hex string length must be even," + throw newThrowable(IllegalArgumentException.class, "Hex string length must be even," +
" string has length '%d' instead", hexString.length()); " string has length '%d' instead", hexString.length());
} }
int lim = hexString.length() / 2; final int lim = hexString.length() / 2;
for(int i = 0; i < lim; i++) { for(int i = 0; i < lim; i++) {
int tmp = 0; int tmp = 0;
for (int j = 0; j < 2; j++) { for (int j = 0; j < 2; j++) {

View File

@@ -45,8 +45,8 @@ public class HttpClient {
} }
@SneakyThrows @SneakyThrows
public HttpURLConnection call(HttpRequest httpRequest) { public HttpURLConnection call(final HttpRequest httpRequest) {
HttpURLConnection conn = (HttpURLConnection) httpRequest.url.openConnection(); final HttpURLConnection conn = (HttpURLConnection) httpRequest.url.openConnection();
if (socketFactory != null && conn instanceof HttpsURLConnection) { if (socketFactory != null && conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory); ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);
@@ -60,7 +60,7 @@ public class HttpClient {
entry.getValue() entry.getValue()
.forEach(headerValue -> .forEach(headerValue ->
conn.addRequestProperty(entry.getKey(), headerValue))); conn.addRequestProperty(entry.getKey(), headerValue)));
List<HttpCookie> cookies = cookieStore.get(httpRequest.getUrl().toURI()); final List<HttpCookie> cookies = cookieStore.get(httpRequest.getUrl().toURI());
if (!cookies.isEmpty()) { if (!cookies.isEmpty()) {
conn.setRequestProperty("Cookie", conn.setRequestProperty("Cookie",
cookies.stream() cookies.stream()
@@ -74,10 +74,10 @@ public class HttpClient {
case DELETE: case DELETE:
if (httpRequest.body != null) { if (httpRequest.body != null) {
conn.setDoOutput(true); conn.setDoOutput(true);
byte[] buffer = new byte[1024]; final byte[] buffer = new byte[1024];
OutputStream os = conn.getOutputStream(); final OutputStream os = conn.getOutputStream();
while (true) { while (true) {
int read = httpRequest.body.read(buffer, 0, buffer.length); final int read = httpRequest.body.read(buffer, 0, buffer.length);
if (read < 0) break; if (read < 0) break;
os.write(buffer, 0, read); os.write(buffer, 0, read);
} }
@@ -89,10 +89,10 @@ public class HttpClient {
break; break;
} }
conn.getResponseCode(); conn.getResponseCode();
Map<String, List<String>> headerFields = conn.getHeaderFields(); final Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER); final List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) { if (cookiesHeader != null) {
for (String cookie : cookiesHeader) { for (final String cookie : cookiesHeader) {
cookieStore.add(httpRequest.url.toURI(), HttpCookie.parse(cookie).get(0)); cookieStore.add(httpRequest.url.toURI(), HttpCookie.parse(cookie).get(0));
} }
} }
@@ -109,7 +109,7 @@ public class HttpClient {
public final String text; public final String text;
HttpMethod(String text) { HttpMethod(final String text) {
this.text = text; this.text = text;
} }
} }
@@ -130,11 +130,11 @@ public class HttpClient {
public final int code; public final int code;
HttpStatus(int code) { HttpStatus(final int code) {
this.code = code; this.code = code;
} }
public static HttpStatus of(int code) { public static HttpStatus of(final int code) {
return Arrays.stream(values()) return Arrays.stream(values())
.filter(it -> it.code == code) .filter(it -> it.code == code)
.findFirst() .findFirst()
@@ -161,7 +161,7 @@ public class HttpClient {
@Builder.Default @Builder.Default
private final InputStream body = null; private final InputStream body = null;
public static HttpRequestBuilder builder(URL url) { public static HttpRequestBuilder builder(final URL url) {
return HttpRequest.privateBuilder().url(url); return HttpRequest.privateBuilder().url(url);
} }
} }

View File

@@ -6,7 +6,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IntegerMath { public class IntegerMath {
public static int ceilDiv(int a, int b) { public static int ceilDiv(final int a, final int b) {
if(a <= 0) throw new IllegalArgumentException("a must be positive"); if(a <= 0) throw new IllegalArgumentException("a must be positive");
return 1 + (a - 1) / b; return 1 + (a - 1) / b;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -18,16 +18,16 @@ public class JarExtractorInputStream extends JarInputStream {
private final Path destination; private final Path destination;
private OutputStream currentFile = null; private OutputStream currentFile = null;
public JarExtractorInputStream(InputStream source, public JarExtractorInputStream(final InputStream source,
Path destination, final Path destination,
boolean verify, final boolean verify,
String sourceLocation) throws IOException { final String sourceLocation) throws IOException {
super(source, verify); super(source, verify);
this.destination = destination; this.destination = destination;
Path newFileSystemLocation = destination.resolve(JarFile.MANIFEST_NAME); final Path newFileSystemLocation = destination.resolve(JarFile.MANIFEST_NAME);
Files.createDirectories(newFileSystemLocation.getParent()); Files.createDirectories(newFileSystemLocation.getParent());
try(OutputStream outputStream = Files.newOutputStream(newFileSystemLocation)) { try(final OutputStream outputStream = Files.newOutputStream(newFileSystemLocation)) {
Manifest manifest = getManifest(); final Manifest manifest = getManifest();
if(manifest == null) { if(manifest == null) {
String location; String location;
if(sourceLocation == null) { if(sourceLocation == null) {
@@ -44,9 +44,9 @@ public class JarExtractorInputStream extends JarInputStream {
@Override @Override
public ZipEntry getNextEntry() throws IOException { public ZipEntry getNextEntry() throws IOException {
ZipEntry entry = super.getNextEntry(); final ZipEntry entry = super.getNextEntry();
if(entry != null) { if(entry != null) {
Path newFileSystemLocation = destination.resolve(entry.getName()); final Path newFileSystemLocation = destination.resolve(entry.getName());
if(entry.isDirectory()) { if(entry.isDirectory()) {
Files.createDirectories(newFileSystemLocation); Files.createDirectories(newFileSystemLocation);
} else { } else {
@@ -59,14 +59,14 @@ public class JarExtractorInputStream extends JarInputStream {
@Override @Override
public int read() throws IOException { public int read() throws IOException {
int result = super.read(); final int result = super.read();
if(result != -1 && currentFile != null) currentFile.write(result); if(result != -1 && currentFile != null) currentFile.write(result);
return result; return result;
} }
@Override @Override
public int read(byte[] b, int off, int len) throws IOException { public int read(final byte[] b, final int off, final int len) throws IOException {
int read = super.read(b, off, len); final int read = super.read(b, off, len);
if(read != -1 && currentFile != null) currentFile.write(b, off, read); if(read != -1 && currentFile != null) currentFile.write(b, off, read);
return read; return read;
} }

View File

@@ -65,11 +65,11 @@ public class JavaProcessBuilder {
* @param strings list of command line arguments to be passed to the spawned JVM * @param strings list of command line arguments to be passed to the spawned JVM
* @return the Java argument file content as a string * @return the Java argument file content as a string
*/ */
static String generateArgumentFileString(List<String> strings) { static String generateArgumentFileString(final List<String> strings) {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
int i = 0; int i = 0;
while(i < strings.size()) { while(i < strings.size()) {
CharacterIterator it = new StringCharacterIterator(strings.get(i)); final CharacterIterator it = new StringCharacterIterator(strings.get(i));
sb.append('"'); sb.append('"');
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
switch (c) { switch (c) {
@@ -103,20 +103,20 @@ public class JavaProcessBuilder {
@SneakyThrows @SneakyThrows
public ProcessBuilder build() { public ProcessBuilder build() {
ArrayList<String> cmd = new ArrayList<>(); final ArrayList<String> cmd = new ArrayList<>();
Path javaBin = Paths.get(javaHome, "bin", "java"); final Path javaBin = Paths.get(javaHome, "bin", "java");
cmd.add(javaBin.toString()); cmd.add(javaBin.toString());
cmd.addAll(jvmArgs); cmd.addAll(jvmArgs);
if(!classpath.isEmpty()) { if(!classpath.isEmpty()) {
cmd.add("-cp"); cmd.add("-cp");
cmd.add(String.join(PATH_SEPARATOR, classpath)); cmd.add(String.join(PATH_SEPARATOR, classpath));
} }
for(Map.Entry<Object, Object> entry : properties.entrySet()) { for(final Map.Entry<Object, Object> entry : properties.entrySet()) {
cmd.add(String.format("-D%s=%s", entry.getKey(), entry.getValue())); cmd.add(String.format("-D%s=%s", entry.getKey(), entry.getValue()));
} }
for(JavaAgent javaAgent : javaAgents) { for(final JavaAgent javaAgent : javaAgents) {
StringBuilder sb = new StringBuilder("-javaagent:").append(javaAgent.jar.toString()); final StringBuilder sb = new StringBuilder("-javaagent:").append(javaAgent.jar.toString());
String agentArguments = javaAgent.args; final String agentArguments = javaAgent.args;
if(agentArguments != null) { if(agentArguments != null) {
sb.append('='); sb.append('=');
sb.append(agentArguments); sb.append(agentArguments);
@@ -135,7 +135,7 @@ public class JavaProcessBuilder {
cmd.addAll(cliArgs); cmd.addAll(cliArgs);
int cmdLength = 0; int cmdLength = 0;
for(String part : cmd) { for(final String part : cmd) {
cmdLength += part.length(); cmdLength += part.length();
} }
//Add space between arguments //Add space between arguments
@@ -145,20 +145,20 @@ public class JavaProcessBuilder {
log.debug("Spawning new process with command line: [{}]", log.debug("Spawning new process with command line: [{}]",
cmd.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(", "))); cmd.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(", ")));
} }
int jvmVersion = Integer.parseInt(System.getProperty("java.vm.specification.version")); final int jvmVersion = Integer.parseInt(System.getProperty("java.vm.specification.version"));
if(jvmVersion < 9 /* Java versions 8 and earlier do not support argument files */ || cmdLength < COMMAND_LINE_MAX_SIZE || cmd.size() == 1) { if(jvmVersion < 9 /* Java versions 8 and earlier do not support argument files */ || cmdLength < COMMAND_LINE_MAX_SIZE || cmd.size() == 1) {
return new ProcessBuilder(cmd); return new ProcessBuilder(cmd);
} else { } else {
Path argumentFile = Files.createTempFile(PROCESS_BUILDER_PREFIX, ".arg"); final Path argumentFile = Files.createTempFile(PROCESS_BUILDER_PREFIX, ".arg");
Runtime.getRuntime().addShutdownHook(new Thread(() -> { Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try { try {
Files.delete(argumentFile); Files.delete(argumentFile);
} catch (IOException ioe) { } catch (final IOException ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
} }
})); }));
log.trace("Using Java argument file '{}'", argumentFile); log.trace("Using Java argument file '{}'", argumentFile);
try(Writer writer = Files.newBufferedWriter(argumentFile)) { try(final Writer writer = Files.newBufferedWriter(argumentFile)) {
writer.write(generateArgumentFileString(cmd.subList(1, cmd.size()))); writer.write(generateArgumentFileString(cmd.subList(1, cmd.size())));
} }
return new ProcessBuilder(cmd.get(0), "@" + argumentFile); return new ProcessBuilder(cmd.get(0), "@" + argumentFile);

View File

@@ -101,7 +101,7 @@ public enum JavaVersion {
* @return The version, or null if the provided value is null. * @return The version, or null if the provided value is null.
* @throws IllegalArgumentException when the provided value cannot be converted. * @throws IllegalArgumentException when the provided value cannot be converted.
*/ */
public static JavaVersion toVersion(Object value) throws IllegalArgumentException { public static JavaVersion toVersion(final Object value) throws IllegalArgumentException {
if (value == null) { if (value == null) {
return null; return null;
} }
@@ -112,12 +112,12 @@ public enum JavaVersion {
return getVersionForMajor((Integer) value); return getVersionForMajor((Integer) value);
} }
String name = value.toString(); final String name = value.toString();
int firstNonVersionCharIndex = findFirstNonVersionCharIndex(name); final int firstNonVersionCharIndex = findFirstNonVersionCharIndex(name);
String[] versionStrings = name.substring(0, firstNonVersionCharIndex).split("\\."); final String[] versionStrings = name.substring(0, firstNonVersionCharIndex).split("\\.");
List<Integer> versions = convertToNumber(name, versionStrings); final List<Integer> versions = convertToNumber(name, versionStrings);
if (isLegacyVersion(versions)) { if (isLegacyVersion(versions)) {
assertTrue(name, versions.get(1) > 0); assertTrue(name, versions.get(1) > 0);
@@ -140,11 +140,11 @@ public enum JavaVersion {
currentJavaVersion = null; currentJavaVersion = null;
} }
public static JavaVersion forClassVersion(int classVersion) { public static JavaVersion forClassVersion(final int classVersion) {
return getVersionForMajor(classVersion - 44); //class file versions: 1.1 == 45, 1.2 == 46... return getVersionForMajor(classVersion - 44); //class file versions: 1.1 == 45, 1.2 == 46...
} }
public static JavaVersion forClass(byte[] classData) { public static JavaVersion forClass(final byte[] classData) {
if (classData.length < 8) { if (classData.length < 8) {
throw new IllegalArgumentException("Invalid class format. Should contain at least 8 bytes"); throw new IllegalArgumentException("Invalid class format. Should contain at least 8 bytes");
} }
@@ -156,7 +156,7 @@ public enum JavaVersion {
* *
* @since 6.0 * @since 6.0
*/ */
public boolean isCompatibleWith(JavaVersion otherVersion) { public boolean isCompatibleWith(final JavaVersion otherVersion) {
return this.compareTo(otherVersion) >= 0; return this.compareTo(otherVersion) >= 0;
} }
@@ -169,27 +169,27 @@ public enum JavaVersion {
return String.valueOf(ordinal() + 1); return String.valueOf(ordinal() + 1);
} }
private static JavaVersion getVersionForMajor(int major) { private static JavaVersion getVersionForMajor(final int major) {
return major >= values().length ? JavaVersion.VERSION_HIGHER : values()[major - 1]; return major >= values().length ? JavaVersion.VERSION_HIGHER : values()[major - 1];
} }
private static void assertTrue(String value, boolean condition) { private static void assertTrue(final String value, final boolean condition) {
if (!condition) { if (!condition) {
throw new IllegalArgumentException("Could not determine java version from '" + value + "'."); throw new IllegalArgumentException("Could not determine java version from '" + value + "'.");
} }
} }
private static boolean isLegacyVersion(List<Integer> versions) { private static boolean isLegacyVersion(final List<Integer> versions) {
return 1 == versions.get(0) && versions.size() > 1; return 1 == versions.get(0) && versions.size() > 1;
} }
private static List<Integer> convertToNumber(String value, String[] versionStrs) { private static List<Integer> convertToNumber(final String value, final String[] versionStrs) {
List<Integer> result = new ArrayList<>(); final List<Integer> result = new ArrayList<>();
for (String s : versionStrs) { for (final String s : versionStrs) {
assertTrue(value, !isNumberStartingWithZero(s)); assertTrue(value, !isNumberStartingWithZero(s));
try { try {
result.add(Integer.parseInt(s)); result.add(Integer.parseInt(s));
} catch (NumberFormatException e) { } catch (final NumberFormatException e) {
assertTrue(value, false); assertTrue(value, false);
} }
} }
@@ -197,11 +197,11 @@ public enum JavaVersion {
return result; return result;
} }
private static boolean isNumberStartingWithZero(String number) { private static boolean isNumberStartingWithZero(final String number) {
return number.length() > 1 && number.startsWith("0"); return number.length() > 1 && number.startsWith("0");
} }
private static int findFirstNonVersionCharIndex(String s) { private static int findFirstNonVersionCharIndex(final String s) {
assertTrue(s, s.length() != 0); assertTrue(s, s.length() != 0);
for (int i = 0; i < s.length(); ++i) { for (int i = 0; i < s.length(); ++i) {
@@ -214,7 +214,7 @@ public enum JavaVersion {
return s.length(); return s.length();
} }
private static boolean isDigitOrPeriod(char c) { private static boolean isDigitOrPeriod(final char c) {
return (c >= '0' && c <= '9') || c == '.'; return (c >= '0' && c <= '9') || c == '.';
} }
} }

View File

@@ -8,12 +8,12 @@ public class LRUCache {
public static <K, V> Map<K, V> of(final long maxSize, final Function<K, V> loader, Class<K> cls) { public static <K, V> Map<K, V> of(final long maxSize, final Function<K, V> loader, Class<K> cls) {
return new LinkedHashMap<K, V>() { return new LinkedHashMap<K, V>() {
@Override @Override
protected boolean removeEldestEntry(Map.Entry eldest) { protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() >= maxSize; return size() >= maxSize;
} }
@Override @Override
public V get(Object key) { public V get(final Object key) {
if(cls.isInstance(key)) { if(cls.isInstance(key)) {
return computeIfAbsent((K) key, loader); return computeIfAbsent((K) key, loader);
} else { } else {
@@ -22,17 +22,17 @@ public class LRUCache {
} }
@Override @Override
public void putAll(Map<? extends K, ? extends V> m) { public void putAll(final Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public V put(K key, V value) { public V put(final K key, final V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public V putIfAbsent(K key, V value) { public V putIfAbsent(final K key, final V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
}; };

View File

@@ -15,14 +15,14 @@ public class LazyOptional<T> {
private final Supplier<T> producer; private final Supplier<T> producer;
private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false); private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false);
public static <U> LazyOptional<U> of(Supplier<U> producer) { public static <U> LazyOptional<U> of(final Supplier<U> producer) {
return new LazyOptional<>(producer); return new LazyOptional<>(producer);
} }
public static <U> LazyOptional<U> or(LazyOptional<U>... opts) { public static <U> LazyOptional<U> or(final LazyOptional<U>... opts) {
return LazyOptional.of(() -> { return LazyOptional.of(() -> {
for (LazyOptional<U> opt : opts) { for (final LazyOptional<U> opt : opts) {
U value = opt.get(); final U value = opt.get();
if (value != null) return value; if (value != null) return value;
} }
return null; return null;
@@ -34,17 +34,17 @@ public class LazyOptional<T> {
return (LazyOptional<U>) empty; return (LazyOptional<U>) empty;
} }
public <U> LazyOptional<U> map(Function<T, U> mapping) { public <U> LazyOptional<U> map(final Function<T, U> mapping) {
return LazyOptional.of(() -> { return LazyOptional.of(() -> {
T prevValue = producer.get(); final T prevValue = producer.get();
if (prevValue == null) return null; if (prevValue == null) return null;
else return mapping.apply(prevValue); else return mapping.apply(prevValue);
}); });
} }
public LazyOptional<T> filter(Predicate<T> predicate) { public LazyOptional<T> filter(final Predicate<T> predicate) {
return LazyOptional.of(() -> { return LazyOptional.of(() -> {
T prevValue = producer.get(); final T prevValue = producer.get();
if (predicate.test(prevValue)) return prevValue; if (predicate.test(prevValue)) return prevValue;
else return null; else return null;
}); });
@@ -55,7 +55,7 @@ public class LazyOptional<T> {
synchronized (instance) { synchronized (instance) {
if (instance.get_2()) return instance.get_1(); if (instance.get_2()) return instance.get_1();
else { else {
T value = producer.get(); final T value = producer.get();
instance.set_1(value); instance.set_1(value);
instance.set_2(true); instance.set_2(true);
return value; return value;
@@ -63,9 +63,9 @@ public class LazyOptional<T> {
} }
} }
public <U> LazyOptional<U> flatMap(Function<T, LazyOptional<U>> mapping) { public <U> LazyOptional<U> flatMap(final Function<T, LazyOptional<U>> mapping) {
return new LazyOptional<>(() -> { return new LazyOptional<>(() -> {
T prevValue = producer.get(); final T prevValue = producer.get();
if (prevValue == null) return null; if (prevValue == null) return null;
else return mapping.apply(prevValue).get(); else return mapping.apply(prevValue).get();
}); });

View File

@@ -19,9 +19,9 @@ public interface LazyValue<T> {
T get(); T get();
<U> LazyValue<U> handle(BiFunction<T, Throwable, U> bifun); <U> LazyValue<U> handle(final BiFunction<T, Throwable, U> bifun);
<U> LazyValue<U> map(Function<T, U> fun); <U> LazyValue<U> map(final Function<T, U> fun);
Stream<T> stream(); Stream<T> stream();
@@ -32,7 +32,7 @@ public interface LazyValue<T> {
*/ */
Optional<T> close(); Optional<T> close();
static <T> LazyValue<T> of(Supplier<T> supplier, ThreadSafetyMode locking, Consumer<T> finalizer) { static <T> LazyValue<T> of(final Supplier<T> supplier, final ThreadSafetyMode locking, final Consumer<T> finalizer) {
LazyValue<T> result; LazyValue<T> result;
switch (locking) { switch (locking) {
case SYNCHRONIZED: case SYNCHRONIZED:
@@ -47,7 +47,7 @@ public interface LazyValue<T> {
return result; return result;
} }
static <T> LazyValue<T> of(Supplier<T> supplier, ThreadSafetyMode locking) { static <T> LazyValue<T> of(final Supplier<T> supplier, final ThreadSafetyMode locking) {
return of(supplier, locking, null); return of(supplier, locking, null);
} }
} }

View File

@@ -9,21 +9,21 @@ import java.io.OutputStream;
public class Leb128 { public class Leb128 {
public static long reverse(long n) { public static long reverse(final long n) {
long res = 0; long res = 0;
for(int i = 0; i < 8; i++) { for(int i = 0; i < 8; i++) {
long b = (n & (0xFFL << (i * 8))) >>> (i * 8); final long b = (n & (0xFFL << (i * 8))) >>> (i * 8);
res |= b << ((7 - i) * 8); res |= b << ((7 - i) * 8);
} }
return res; return res;
} }
public static int encode(OutputStream os, double input) { public static int encode(final OutputStream os, final double input) {
return encode(os, reverse(Double.doubleToLongBits(input))); return encode(os, reverse(Double.doubleToLongBits(input)));
} }
@SneakyThrows @SneakyThrows
public static int encode(OutputStream os, long input) { public static int encode(final OutputStream os, final long input) {
int bytes_written = 0; int bytes_written = 0;
long number = input >= 0 ? (input << 1) : (-(input + 1)) << 1 | 1; long number = input >= 0 ? (input << 1) : (-(input + 1)) << 1 | 1;
while((number & 127L) != number) { while((number & 127L) != number) {
@@ -62,7 +62,7 @@ public class Leb128 {
public long decode() { public long decode() {
long res = 0; long res = 0;
for(int i = 0; i < (8 * 8 + 6) / 7; i++) { for(int i = 0; i < (8 * 8 + 6) / 7; i++) {
int c = is.read(); final int c = is.read();
bytesRead++; bytesRead++;
if(c < 0) { if(c < 0) {
throw new IllegalArgumentException("Unexpected end of file"); throw new IllegalArgumentException("Unexpected end of file");

View File

@@ -13,7 +13,7 @@ public class LexicographicIterableComparator<T> implements Comparator<Iterable<T
} }
@Override @Override
public int compare(Iterable<T> iterable1, Iterable<T> iterable2) { public int compare(final Iterable<T> iterable1, final Iterable<T> iterable2) {
final Iterator<T> it1 = iterable1.iterator(), it2 = iterable2.iterator(); final Iterator<T> it1 = iterable1.iterator(), it2 = iterable2.iterator();
while (it1.hasNext() && it2.hasNext()) { while (it1.hasNext() && it2.hasNext()) {
final int cmp = elementComparator.compare(it1.next(),it2.next()); final int cmp = elementComparator.compare(it1.next(),it2.next());
@@ -24,7 +24,7 @@ public class LexicographicIterableComparator<T> implements Comparator<Iterable<T
return 0; return 0;
} }
public static <S extends Comparable<S>> LexicographicIterableComparator<S> forClass(Class<S> cls) { public static <S extends Comparable<S>> LexicographicIterableComparator<S> forClass(final Class<S> cls) {
return new LexicographicIterableComparator<S>(Comparator.naturalOrder()); return new LexicographicIterableComparator<S>(Comparator.naturalOrder());
} }
} }

View File

@@ -17,7 +17,7 @@ public class ListView<T> implements List<T> {
private final int start; private final int start;
private final int end; private final int end;
public ListView(List<T> delegate, int start) { public ListView(final List<T> delegate, final int start) {
this(delegate, start, -1); this(delegate, start, -1);
} }
@@ -32,8 +32,8 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public boolean contains(Object o) { public boolean contains(final Object o) {
Iterator<T> it = iterator(); final Iterator<T> it = iterator();
while (it.hasNext()) { while (it.hasNext()) {
if(Objects.equals(o, it.next())) { if(Objects.equals(o, it.next())) {
return true; return true;
@@ -60,8 +60,8 @@ public class ListView<T> implements List<T> {
@Override @Override
public Object[] toArray() { public Object[] toArray() {
int size = size(); final int size = size();
Object[] result = new Object[size]; final Object[] result = new Object[size];
for(int i = 0; i < size; i++) { for(int i = 0; i < size; i++) {
result[i] = get(i); result[i] = get(i);
} }
@@ -69,9 +69,9 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public <T1> T1[] toArray(T1[] t1s) { public <T1> T1[] toArray(final T1[] t1s) {
int size = size(); final int size = size();
T1[] result = Arrays.copyOf(t1s, size); final T1[] result = Arrays.copyOf(t1s, size);
for(int i = 0; i < size; i++) { for(int i = 0; i < size; i++) {
result[i] = (T1) get(i); result[i] = (T1) get(i);
} }
@@ -79,37 +79,37 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public boolean add(T t) { public boolean add(final T t) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean remove(Object o) { public boolean remove(final Object o) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean containsAll(Collection<?> collection) { public boolean containsAll(final Collection<?> collection) {
return false; return false;
} }
@Override @Override
public boolean addAll(Collection<? extends T> collection) { public boolean addAll(final Collection<? extends T> collection) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean addAll(int i, Collection<? extends T> collection) { public boolean addAll(final int i, final Collection<? extends T> collection) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean removeAll(Collection<?> collection) { public boolean removeAll(final Collection<?> collection) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public boolean retainAll(Collection<?> collection) { public boolean retainAll(final Collection<?> collection) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@@ -119,8 +119,8 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public T get(int i) { public T get(final int i) {
int index = start + i; final int index = start + i;
if(end >= 0 && index < end) { if(end >= 0 && index < end) {
throw new IndexOutOfBoundsException(Integer.toString(i)); throw new IndexOutOfBoundsException(Integer.toString(i));
} }
@@ -128,23 +128,23 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public T set(int i, T t) { public T set(final int i, final T t) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public void add(int i, T t) { public void add(final int i, final T t) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public T remove(int i) { public T remove(final int i) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public int indexOf(Object o) { public int indexOf(final Object o) {
int size = size(); final int size = size();
for(int i = 0; i < size; i++) { for(int i = 0; i < size; i++) {
if(Objects.equals(o, get(i))) { if(Objects.equals(o, get(i))) {
return i; return i;
@@ -154,8 +154,8 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public int lastIndexOf(Object o) { public int lastIndexOf(final Object o) {
int size = size(); final int size = size();
for(int i = size - 1; i >= 0; i--) { for(int i = size - 1; i >= 0; i--) {
if(Objects.equals(o, get(i))) { if(Objects.equals(o, get(i))) {
return i; return i;
@@ -170,7 +170,7 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public ListIterator<T> listIterator(int i) { public ListIterator<T> listIterator(final int i) {
if(i < 0 || i > size()) { if(i < 0 || i > size()) {
throw new IndexOutOfBoundsException(Integer.toString(0)); throw new IndexOutOfBoundsException(Integer.toString(0));
} else { } else {
@@ -179,7 +179,7 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public List<T> subList(int i, int i1) { public List<T> subList(final int i, final int i1) {
if(i < 0) { if(i < 0) {
throw new IndexOutOfBoundsException(Integer.toString(0)); throw new IndexOutOfBoundsException(Integer.toString(0));
} else if(i1 > size()) { } else if(i1 > size()) {
@@ -195,7 +195,7 @@ public class ListView<T> implements List<T> {
int size; int size;
int i; int i;
public ListViewIterator(ListView<T> listView, int start) { public ListViewIterator(final ListView<T> listView, final int start) {
this.listView = listView; this.listView = listView;
size = listView.size(); size = listView.size();
i = start; i = start;
@@ -237,12 +237,12 @@ public class ListView<T> implements List<T> {
} }
@Override @Override
public void set(T t) { public void set(final T t) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public void add(T t) { public void add(final T t) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@@ -31,7 +31,7 @@ public abstract class LockFile implements AutoCloseable {
@Setter @Setter
private FileLock fileLock; private FileLock fileLock;
public LockFileMapValue(Path path) { public LockFileMapValue(final Path path) {
threadLock = new ReentrantReadWriteLock(); threadLock = new ReentrantReadWriteLock();
readerCount = new AtomicInteger(0); readerCount = new AtomicInteger(0);
fileLock = null; fileLock = null;
@@ -40,7 +40,7 @@ public abstract class LockFile implements AutoCloseable {
private static Map<Path, LockFileMapValue> map = Collections.synchronizedMap(new HashMap<>()); private static Map<Path, LockFileMapValue> map = Collections.synchronizedMap(new HashMap<>());
private static FileChannel openFileChannel(Path path) throws IOException { private static FileChannel openFileChannel(final Path path) throws IOException {
Files.createDirectories(path.getParent()); Files.createDirectories(path.getParent());
return FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE)); return FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE));
} }
@@ -72,9 +72,9 @@ public abstract class LockFile implements AutoCloseable {
return new LockFile() { return new LockFile() {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
int remainingReaders = lockFileMapValue.getReaderCount().decrementAndGet(); final int remainingReaders = lockFileMapValue.getReaderCount().decrementAndGet();
if(remainingReaders == 0) { if(remainingReaders == 0) {
FileLock fileLock = lockFileMapValue.getFileLock(); final FileLock fileLock = lockFileMapValue.getFileLock();
fileLock.release(); fileLock.release();
fileLock.channel().close(); fileLock.channel().close();
lockFileMapValue.setFileLock(null); lockFileMapValue.setFileLock(null);
@@ -116,11 +116,11 @@ public abstract class LockFile implements AutoCloseable {
} }
} }
public static LockFile tryAcquire(Path path, boolean shared) throws IOException { public static LockFile tryAcquire(final Path path, final boolean shared) throws IOException {
return acquireInternal(path, shared, false); return acquireInternal(path, shared, false);
} }
public static LockFile acquire(Path path, boolean shared) throws IOException { public static LockFile acquire(final Path path, final boolean shared) throws IOException {
return acquireInternal(path, shared, true); return acquireInternal(path, shared, true);
} }
} }

View File

@@ -22,13 +22,13 @@ public class LoggerController {
private static final Queue<SubstituteLoggingEvent> eventQueue = new LinkedBlockingQueue<>(); private static final Queue<SubstituteLoggingEvent> eventQueue = new LinkedBlockingQueue<>();
private static final List<SubstituteLogger> substituteLoggers = new ArrayList<>(); private static final List<SubstituteLogger> substituteLoggers = new ArrayList<>();
public static Logger lazyLogger(String className) { public static Logger lazyLogger(final String className) {
synchronized (lock) { synchronized (lock) {
Logger result; Logger result;
if (initialized) { if (initialized) {
result = LoggerFactory.getLogger(className); result = LoggerFactory.getLogger(className);
} else { } else {
SubstituteLogger substituteLogger = new SubstituteLogger(className, eventQueue, false); final SubstituteLogger substituteLogger = new SubstituteLogger(className, eventQueue, false);
substituteLoggers.add(substituteLogger); substituteLoggers.add(substituteLogger);
result = substituteLogger; result = substituteLogger;
} }
@@ -36,20 +36,20 @@ public class LoggerController {
} }
} }
public static Logger lazyLogger(Class<?> cls) { public static Logger lazyLogger(final Class<?> cls) {
return lazyLogger(cls.getName()); return lazyLogger(cls.getName());
} }
public static void initializeLoggers() { public static void initializeLoggers() {
synchronized (lock) { synchronized (lock) {
SubstituteLogger firstLogger = null; SubstituteLogger firstLogger = null;
for (SubstituteLogger log : substituteLoggers) { for (final SubstituteLogger log : substituteLoggers) {
if (firstLogger == null) firstLogger = log; if (firstLogger == null) firstLogger = log;
Logger realLogger = LoggerFactory.getLogger(log.getName()); final Logger realLogger = LoggerFactory.getLogger(log.getName());
log.setDelegate(realLogger); log.setDelegate(realLogger);
} }
if (firstLogger != null) { if (firstLogger != null) {
for (LoggingEvent evt : eventQueue) { for (final LoggingEvent evt : eventQueue) {
firstLogger.log(evt); firstLogger.log(evt);
} }
} }

View File

@@ -6,7 +6,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LongMath { public class LongMath {
public static long ceilDiv(long a, long b) { public static long ceilDiv(final long a, final long b) {
if(a <= 0) throw new IllegalArgumentException("a must be positive"); if(a <= 0) throw new IllegalArgumentException("a must be positive");
return 1 + (a - 1) / b; return 1 + (a - 1) / b;
} }

View File

@@ -12,7 +12,7 @@ public class LookAheadInputStream extends InputStream {
private int cursor = -1; private int cursor = -1;
private int currentByte; private int currentByte;
public LookAheadInputStream(InputStream stream) { public LookAheadInputStream(final InputStream stream) {
this.stream = stream; this.stream = stream;
} }

View File

@@ -14,7 +14,7 @@ public class LookAheadTextInputStream extends InputStream {
private int currentChar; private int currentChar;
public LookAheadTextInputStream(Reader reader) { public LookAheadTextInputStream(final Reader reader) {
this.reader = reader; this.reader = reader;
} }

View File

@@ -23,19 +23,19 @@ public class LruCache<K, V> implements Map<K, V> {
private final Chronometer chronometer = new Chronometer(); private final Chronometer chronometer = new Chronometer();
public LruCache(int maxSize) { public LruCache(final int maxSize) {
this(maxSize, false); this(maxSize, false);
} }
public LruCache(int maxSize, boolean threadSafe) { public LruCache(final int maxSize, final boolean threadSafe) {
this(maxSize, threadSafe, null, null); this(maxSize, threadSafe, null, null);
} }
public LruCache(int maxSize, boolean threadSafe, Function<? super K, ? extends V> loader) { public LruCache(final int maxSize, final boolean threadSafe, final Function<? super K, ? extends V> loader) {
this(maxSize, threadSafe, loader, null); this(maxSize, threadSafe, loader, null);
} }
public LruCache(int maxSize, boolean threadSafe, Function<? super K, ? extends V> loader, Map<K,V> fallback) { public LruCache(final int maxSize, final boolean threadSafe, final Function<? super K, ? extends V> loader, final Map<K,V> fallback) {
this.linkedHashMap = new LinkedHashMap<>(); this.linkedHashMap = new LinkedHashMap<>();
this.mtx = threadSafe ? linkedHashMap : null; this.mtx = threadSafe ? linkedHashMap : null;
this.maxSize = maxSize; this.maxSize = maxSize;
@@ -48,7 +48,7 @@ public class LruCache<K, V> implements Map<K, V> {
} else { } else {
this.loader = (K key) -> { this.loader = (K key) -> {
this.stats.miss++; this.stats.miss++;
V value = fallback.get(key); final V value = fallback.get(key);
if (value == null) { if (value == null) {
return loader.apply(key); return loader.apply(key);
} else { } else {
@@ -62,7 +62,7 @@ public class LruCache<K, V> implements Map<K, V> {
this.fallback = fallback; this.fallback = fallback;
} }
private <T> T withMutex(Supplier<T> supplier) { private <T> T withMutex(final Supplier<T> supplier) {
if(mtx != null) { if(mtx != null) {
synchronized (mtx) { synchronized (mtx) {
return supplier.get(); return supplier.get();
@@ -87,11 +87,11 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public boolean containsKey(Object key) { public boolean containsKey(final Object key) {
K k; K k;
try { try {
k = (K) key; k = (K) key;
} catch (ClassCastException cce) { } catch (final ClassCastException cce) {
return false; return false;
} }
return withMutex(() -> { return withMutex(() -> {
@@ -104,7 +104,7 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public boolean containsValue(Object value) { public boolean containsValue(final Object value) {
return withMutex(() -> { return withMutex(() -> {
boolean result = linkedHashMap.containsValue(value); boolean result = linkedHashMap.containsValue(value);
if(!result && fallback != null) { if(!result && fallback != null) {
@@ -114,7 +114,7 @@ public class LruCache<K, V> implements Map<K, V> {
}); });
} }
private V getOrFallback(K key) { private V getOrFallback(final K key) {
V value = linkedHashMap.get(key); V value = linkedHashMap.get(key);
if(value == null) { if(value == null) {
stats.miss++; stats.miss++;
@@ -129,11 +129,11 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public V get(Object key) { public V get(final Object key) {
K k; K k;
try { try {
k = (K) key; k = (K) key;
} catch (ClassCastException cce) { } catch (final ClassCastException cce) {
return null; return null;
} }
return withMutex(() -> { return withMutex(() -> {
@@ -141,7 +141,7 @@ public class LruCache<K, V> implements Map<K, V> {
if (loader != null) { if (loader != null) {
try { try {
chronometer.reset(); chronometer.reset();
V result = getOrFallback(k); final V result = getOrFallback(k);
if (result == null) { if (result == null) {
V newValue; V newValue;
if ((newValue = loader.apply(k)) != null) { if ((newValue = loader.apply(k)) != null) {
@@ -151,7 +151,7 @@ public class LruCache<K, V> implements Map<K, V> {
} }
stats.loadingTime += chronometer.elapsed(); stats.loadingTime += chronometer.elapsed();
return result; return result;
} catch (Exception e) { } catch (final Exception e) {
stats.exceptions++; stats.exceptions++;
throw e; throw e;
} }
@@ -162,12 +162,12 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public V put(K k, V v) { public V put(final K k, final V v) {
return withMutex(() -> { return withMutex(() -> {
if (linkedHashMap.size() == maxSize) { if (linkedHashMap.size() == maxSize) {
Iterator<Entry<K, V>> it = linkedHashMap.entrySet().iterator(); final Iterator<Entry<K, V>> it = linkedHashMap.entrySet().iterator();
if (it.hasNext()) { if (it.hasNext()) {
Map.Entry<K, V> entry = it.next(); final Map.Entry<K, V> entry = it.next();
remove(entry.getKey()); remove(entry.getKey());
stats.evictions++; stats.evictions++;
} }
@@ -181,10 +181,10 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public V remove(Object key) { public V remove(final Object key) {
return withMutex( () -> { return withMutex( () -> {
if(fallback != null) { if(fallback != null) {
V result = fallback.remove(key); final V result = fallback.remove(key);
if(result != null) { if(result != null) {
linkedHashMap.remove(key); linkedHashMap.remove(key);
} }
@@ -196,8 +196,8 @@ public class LruCache<K, V> implements Map<K, V> {
} }
@Override @Override
public void putAll(Map<? extends K, ? extends V> map) { public void putAll(final Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) { for (final Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue()); put(entry.getKey(), entry.getValue());
} }
} }
@@ -280,11 +280,11 @@ public class LruCache<K, V> implements Map<K, V> {
return (calls - miss) / (float) calls; return (calls - miss) / (float) calls;
} }
public float getAverageLoadingTime(Chronometer.UnitOfMeasure unitOfMeasure) { public float getAverageLoadingTime(final Chronometer.UnitOfMeasure unitOfMeasure) {
return (float) stats.loadingTime / calls / unitOfMeasure.nanoseconds; return (float) stats.loadingTime / calls / unitOfMeasure.nanoseconds;
} }
public float getTotalLoadingTime(Chronometer.UnitOfMeasure unitOfMeasure) { public float getTotalLoadingTime(final Chronometer.UnitOfMeasure unitOfMeasure) {
return (float) stats.loadingTime / unitOfMeasure.nanoseconds; return (float) stats.loadingTime / unitOfMeasure.nanoseconds;
} }

View File

@@ -10,14 +10,14 @@ import java.util.stream.Stream;
public class MapBuilder<K,V> { public class MapBuilder<K,V> {
private final List<Map.Entry<K, V>> entries = new ArrayList<>(); private final List<Map.Entry<K, V>> entries = new ArrayList<>();
public MapBuilder<K, V> entry(K key, V value) { public MapBuilder<K, V> entry(final K key, final V value) {
entries.add(new AbstractMap.SimpleEntry<>(key, value)); entries.add(new AbstractMap.SimpleEntry<>(key, value));
return this; return this;
} }
public <T> T build(Sup<Map<K,V>> factory, Function<Map<K,V>, T> finalizer) { public <T> T build(final Sup<Map<K,V>> factory, final Function<Map<K,V>, T> finalizer) {
Map<K, V> result = factory.get(); final Map<K, V> result = factory.get();
for(Map.Entry<K, V> entry : entries) { for(final Map.Entry<K, V> entry : entries) {
result.put(entry.getKey(), entry.getValue()); result.put(entry.getKey(), entry.getValue());
} }
return finalizer.apply(result); return finalizer.apply(result);
@@ -27,11 +27,11 @@ public class MapBuilder<K,V> {
return entries.stream(); return entries.stream();
} }
public Map<K,V> build(Sup<Map<K,V>> factory) { public Map<K,V> build(final Sup<Map<K,V>> factory) {
return build(factory, Function.identity()); return build(factory, Function.identity());
} }
public static <K, V> MapBuilder<K, V> with(K key, V value) { public static <K, V> MapBuilder<K, V> with(final K key, final V value) {
return new MapBuilder<K, V>().entry(key, value); return new MapBuilder<K, V>().entry(key, value);
} }
} }

View File

@@ -63,7 +63,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
int STRING_ITEM = 1; int STRING_ITEM = 1;
int LIST_ITEM = 2; int LIST_ITEM = 2;
int compareTo(Item item); int compareTo(final Item item);
int getType(); int getType();
@@ -82,7 +82,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
this.value = 0; this.value = 0;
} }
IntItem(String str) { IntItem(final String str) {
this.value = Integer.parseInt(str); this.value = Integer.parseInt(str);
} }
@@ -97,14 +97,14 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(final Item item) {
if (item == null) { if (item == null) {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
switch (item.getType()) { switch (item.getType()) {
case INT_ITEM: case INT_ITEM:
int itemValue = ((IntItem) item).value; final int itemValue = ((IntItem) item).value;
return Integer.compare(value, itemValue); return Integer.compare(value, itemValue);
case LONG_ITEM: case LONG_ITEM:
case BIGINTEGER_ITEM: case BIGINTEGER_ITEM:
@@ -122,7 +122,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@@ -130,7 +130,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
return false; return false;
} }
IntItem intItem = (IntItem) o; final IntItem intItem = (IntItem) o;
return value == intItem.value; return value == intItem.value;
} }
@@ -152,7 +152,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
private static class LongItem implements Item { private static class LongItem implements Item {
private final long value; private final long value;
LongItem(String str) { LongItem(final String str) {
this.value = Long.parseLong(str); this.value = Long.parseLong(str);
} }
@@ -167,7 +167,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(final Item item) {
if (item == null) { if (item == null) {
return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
@@ -176,7 +176,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
case INT_ITEM: case INT_ITEM:
return 1; return 1;
case LONG_ITEM: case LONG_ITEM:
long itemValue = ((LongItem) item).value; final long itemValue = ((LongItem) item).value;
return Long.compare(value, itemValue); return Long.compare(value, itemValue);
case BIGINTEGER_ITEM: case BIGINTEGER_ITEM:
return -1; return -1;
@@ -193,7 +193,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@@ -201,7 +201,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
return false; return false;
} }
LongItem longItem = (LongItem) o; final LongItem longItem = (LongItem) o;
return value == longItem.value; return value == longItem.value;
} }
@@ -223,7 +223,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
private static class BigIntegerItem implements Item { private static class BigIntegerItem implements Item {
private final BigInteger value; private final BigInteger value;
BigIntegerItem(String str) { BigIntegerItem(final String str) {
this.value = new BigInteger(str); this.value = new BigInteger(str);
} }
@@ -238,7 +238,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(final Item item) {
if (item == null) { if (item == null) {
return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return BigInteger.ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
@@ -263,7 +263,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@@ -271,7 +271,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
return false; return false;
} }
BigIntegerItem that = (BigIntegerItem) o; final BigIntegerItem that = (BigIntegerItem) o;
return value.equals(that.value); return value.equals(that.value);
} }
@@ -310,7 +310,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
private final String value; private final String value;
StringItem(String value, boolean followedByDigit) { StringItem(String value, final boolean followedByDigit) {
if (followedByDigit && value.length() == 1) { if (followedByDigit && value.length() == 1) {
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1 // a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch (value.charAt(0)) { switch (value.charAt(0)) {
@@ -352,14 +352,14 @@ public class MavenVersion implements Comparable<MavenVersion> {
* @param qualifier * @param qualifier
* @return an equivalent value that can be used with lexical comparison * @return an equivalent value that can be used with lexical comparison
*/ */
public static String comparableQualifier(String qualifier) { public static String comparableQualifier(final String qualifier) {
int i = QUALIFIERS.indexOf(qualifier); final int i = QUALIFIERS.indexOf(qualifier);
return i == -1 ? (QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i); return i == -1 ? (QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i);
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(final Item item) {
if (item == null) { if (item == null) {
// 1-rc < 1, 1-ga > 1 // 1-rc < 1, 1-ga > 1
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
@@ -382,7 +382,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@@ -390,7 +390,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
return false; return false;
} }
StringItem that = (StringItem) o; final StringItem that = (StringItem) o;
return value.equals(that.value); return value.equals(that.value);
} }
@@ -422,7 +422,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
void normalize() { void normalize() {
for (int i = size() - 1; i >= 0; i--) { for (int i = size() - 1; i >= 0; i--) {
Item lastItem = get(i); final Item lastItem = get(i);
if (lastItem.isNull()) { if (lastItem.isNull()) {
// remove null trailing items: 0, "", empty list // remove null trailing items: 0, "", empty list
@@ -434,14 +434,14 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(final Item item) {
if (item == null) { if (item == null) {
if (size() == 0) { if (size() == 0) {
return 0; // 1-0 = 1- (normalize) = 1 return 0; // 1-0 = 1- (normalize) = 1
} }
// Compare the entire list of items with null - not just the first one, MNG-6964 // Compare the entire list of items with null - not just the first one, MNG-6964
for (Item i : this) { for (final Item i : this) {
int result = i.compareTo(null); final int result = i.compareTo(null);
if (result != 0) { if (result != 0) {
return result; return result;
} }
@@ -458,15 +458,15 @@ public class MavenVersion implements Comparable<MavenVersion> {
return 1; // 1-1 > 1-sp return 1; // 1-1 > 1-sp
case LIST_ITEM: case LIST_ITEM:
Iterator<Item> left = iterator(); final Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator(); final Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) { while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null; final Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null; final Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with -1 // if this is shorter, then invert the compare and mul with -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r); final int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
if (result != 0) { if (result != 0) {
return result; return result;
@@ -482,8 +482,8 @@ public class MavenVersion implements Comparable<MavenVersion> {
@Override @Override
public String toString() { public String toString() {
StringBuilder buffer = new StringBuilder(); final StringBuilder buffer = new StringBuilder();
for (Item item : this) { for (final Item item : this) {
if (buffer.length() > 0) { if (buffer.length() > 0) {
buffer.append((item instanceof ListItem) ? '-' : '.'); buffer.append((item instanceof ListItem) ? '-' : '.');
} }
@@ -496,9 +496,9 @@ public class MavenVersion implements Comparable<MavenVersion> {
* Return the contents in the same format that is used when you call toString() on a List. * Return the contents in the same format that is used when you call toString() on a List.
*/ */
private String toListString() { private String toListString() {
StringBuilder buffer = new StringBuilder(); final StringBuilder buffer = new StringBuilder();
buffer.append("["); buffer.append("[");
for (Item item : this) { for (final Item item : this) {
if (buffer.length() > 1) { if (buffer.length() > 1) {
buffer.append(", "); buffer.append(", ");
} }
@@ -513,7 +513,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
} }
public MavenVersion(String version) { public MavenVersion(final String version) {
parseVersion(version); parseVersion(version);
} }
@@ -527,7 +527,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
ListItem list = items; ListItem list = items;
Deque<Item> stack = new ArrayDeque<>(); final Deque<Item> stack = new ArrayDeque<>();
stack.push(list); stack.push(list);
boolean isDigit = false; boolean isDigit = false;
@@ -535,7 +535,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
int startIndex = 0; int startIndex = 0;
for (int i = 0; i < version.length(); i++) { for (int i = 0; i < version.length(); i++) {
char c = version.charAt(i); final char c = version.charAt(i);
if (c == '.') { if (c == '.') {
if (i == startIndex) { if (i == startIndex) {
@@ -601,7 +601,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
} }
private static Item parseItem(boolean isDigit, String buf) { private static Item parseItem(final boolean isDigit, String buf) {
if (isDigit) { if (isDigit) {
buf = stripLeadingZeroes(buf); buf = stripLeadingZeroes(buf);
if (buf.length() <= MAX_INTITEM_LENGTH) { if (buf.length() <= MAX_INTITEM_LENGTH) {
@@ -616,12 +616,12 @@ public class MavenVersion implements Comparable<MavenVersion> {
return new StringItem(buf, false); return new StringItem(buf, false);
} }
private static String stripLeadingZeroes(String buf) { private static String stripLeadingZeroes(final String buf) {
if (buf == null || buf.isEmpty()) { if (buf == null || buf.isEmpty()) {
return "0"; return "0";
} }
for (int i = 0; i < buf.length(); ++i) { for (int i = 0; i < buf.length(); ++i) {
char c = buf.charAt(i); final char c = buf.charAt(i);
if (c != '0') { if (c != '0') {
return buf.substring(i); return buf.substring(i);
} }
@@ -630,7 +630,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public int compareTo(MavenVersion o) { public int compareTo(final MavenVersion o) {
return items.compareTo(o.items); return items.compareTo(o.items);
} }
@@ -647,7 +647,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
return (o instanceof MavenVersion) && items.equals(((MavenVersion) o).items); return (o instanceof MavenVersion) && items.equals(((MavenVersion) o).items);
} }
@@ -674,7 +674,7 @@ public class MavenVersion implements Comparable<MavenVersion> {
* two adjacent will be compared * two adjacent will be compared
*/ */
// CHECKSTYLE_ON: LineLength // CHECKSTYLE_ON: LineLength
public static void main(String... args) { public static void main(final String... args) {
System.out.println("Display parameters as parsed by Maven (in canonical form and as a list of tokens) and" System.out.println("Display parameters as parsed by Maven (in canonical form and as a list of tokens) and"
+ " comparison result:"); + " comparison result:");
if (args.length == 0) { if (args.length == 0) {
@@ -683,11 +683,11 @@ public class MavenVersion implements Comparable<MavenVersion> {
MavenVersion prev = null; MavenVersion prev = null;
int i = 1; int i = 1;
for (String version : args) { for (final String version : args) {
MavenVersion c = new MavenVersion(version); final MavenVersion c = new MavenVersion(version);
if (prev != null) { if (prev != null) {
int compare = prev.compareTo(c); final int compare = prev.compareTo(c);
System.out.println(" " + prev.toString() + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) System.out.println(" " + prev.toString() + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">"))
+ ' ' + version); + ' ' + version);
} }

View File

@@ -3,10 +3,10 @@ package net.woggioni.jwo;
import net.woggioni.jwo.internal.MutableTuple2Impl; import net.woggioni.jwo.internal.MutableTuple2Impl;
public interface MutableTuple2<T, U> extends Tuple2<T, U> { public interface MutableTuple2<T, U> extends Tuple2<T, U> {
void set_1(T value); void set_1(final T value);
void set_2(U value); void set_2(final U value);
static <T,U> MutableTuple2<T, U> newInstance(T x, U y) { static <T,U> MutableTuple2<T, U> newInstance(final T x, final U y) {
return new MutableTuple2Impl<T, U>(x, y); return new MutableTuple2Impl<T, U>(x, y);
} }
} }

View File

@@ -3,11 +3,11 @@ package net.woggioni.jwo;
import net.woggioni.jwo.internal.MutableTuple3Impl; import net.woggioni.jwo.internal.MutableTuple3Impl;
public interface MutableTuple3<T, U, V> extends Tuple3<T, U , V> { public interface MutableTuple3<T, U, V> extends Tuple3<T, U , V> {
void set_1(T value); void set_1(final T value);
void set_2(U value); void set_2(final U value);
void set_3(V value); void set_3(final V value);
static <T, U, V> MutableTuple3<T, U, V> newInstance(T x, U y, V z) { static <T, U, V> MutableTuple3<T, U, V> newInstance(final T x, final U y, final V z) {
return new MutableTuple3Impl<>(x, y, z); return new MutableTuple3Impl<>(x, y, z);
} }
} }

View File

@@ -4,8 +4,8 @@ import java.io.OutputStream;
public class NullOutputStream extends OutputStream { public class NullOutputStream extends OutputStream {
@Override @Override
public void write(int i) {} public void write(final int i) {}
@Override @Override
public void write(byte[] bytes) {} public void write(final byte[] bytes) {}
} }

View File

@@ -5,7 +5,7 @@ import java.io.Reader;
public class NullReader extends Reader { public class NullReader extends Reader {
@Override @Override
public int read(char[] cbuf, int off, int len) throws IOException { public int read(final char[] cbuf, final int off, final int len) throws IOException {
return -1; return -1;
} }

View File

@@ -5,7 +5,7 @@ import java.io.Writer;
public class NullWriter extends Writer { public class NullWriter extends Writer {
@Override @Override
public void write(char[] cbuf, int off, int len) throws IOException { public void write(final char[] cbuf, final int off, final int len) throws IOException {
} }
@Override @Override

View File

@@ -17,7 +17,7 @@ public enum OS {
private final String value; private final String value;
OS(String value) { OS(final String value) {
this.value = value; this.value = value;
} }

View File

@@ -34,26 +34,26 @@ public final class PathClassLoader extends ClassLoader {
registerAsParallelCapable(); registerAsParallelCapable();
} }
public PathClassLoader(Path ...path) { public PathClassLoader(final Path ...path) {
this(Arrays.asList(path), null); this(Arrays.asList(path), null);
} }
public PathClassLoader(Iterable<Path> paths) { public PathClassLoader(final Iterable<Path> paths) {
this(paths, null); this(paths, null);
} }
public PathClassLoader(Iterable<Path> paths, ClassLoader parent) { public PathClassLoader(final Iterable<Path> paths, final ClassLoader parent) {
super(parent); super(parent);
this.paths = paths; this.paths = paths;
} }
@Override @Override
@SneakyThrows @SneakyThrows
protected Class<?> findClass(String name) { protected Class<?> findClass(final String name) {
for(Path path : paths) { for(final Path path : paths) {
Path classPath = path.resolve(name.replace('.', '/').concat(".class")); final Path classPath = path.resolve(name.replace('.', '/').concat(".class"));
if (Files.exists(classPath)) { if (Files.exists(classPath)) {
byte[] byteCode = Files.readAllBytes(classPath); final byte[] byteCode = Files.readAllBytes(classPath);
return defineClass(name, byteCode, 0, byteCode.length); return defineClass(name, byteCode, 0, byteCode.length);
} }
} }
@@ -62,9 +62,9 @@ public final class PathClassLoader extends ClassLoader {
@Override @Override
@SneakyThrows @SneakyThrows
protected URL findResource(String name) { protected URL findResource(final String name) {
for(Path path : paths) { for(final Path path : paths) {
Path resolved = path.resolve(name); final Path resolved = path.resolve(name);
if (Files.exists(resolved)) { if (Files.exists(resolved)) {
return toURL(resolved); return toURL(resolved);
} }
@@ -75,10 +75,10 @@ public final class PathClassLoader extends ClassLoader {
@Override @Override
protected Enumeration<URL> findResources(final String name) throws IOException { protected Enumeration<URL> findResources(final String name) throws IOException {
final List<URL> resources = new ArrayList<>(1); final List<URL> resources = new ArrayList<>(1);
for(Path path : paths) { for(final Path path : paths) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() { Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if (!name.isEmpty()) { if (!name.isEmpty()) {
this.addIfMatches(resources, file); this.addIfMatches(resources, file);
} }
@@ -86,14 +86,14 @@ public final class PathClassLoader extends ClassLoader {
} }
@Override @Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
if (!name.isEmpty() || path.equals(dir)) { if (!name.isEmpty() || path.equals(dir)) {
this.addIfMatches(resources, dir); this.addIfMatches(resources, dir);
} }
return super.preVisitDirectory(dir, attrs); return super.preVisitDirectory(dir, attrs);
} }
void addIfMatches(List<URL> resources, Path file) throws IOException { void addIfMatches(final List<URL> resources, final Path file) throws IOException {
if (path.relativize(file).toString().equals(name)) { if (path.relativize(file).toString().equals(name)) {
resources.add(toURL(file)); resources.add(toURL(file));
} }
@@ -103,7 +103,7 @@ public final class PathClassLoader extends ClassLoader {
return Collections.enumeration(resources); return Collections.enumeration(resources);
} }
private static URL toURL(Path path) throws IOException { private static URL toURL(final Path path) throws IOException {
return new URL(null, path.toUri().toString(), PathURLStreamHandler.INSTANCE); return new URL(null, path.toUri().toString(), PathURLStreamHandler.INSTANCE);
} }
@@ -111,7 +111,7 @@ public final class PathClassLoader extends ClassLoader {
private final Path path; private final Path path;
PathURLConnection(URL url, Path path) { PathURLConnection(final URL url, final Path path) {
super(url); super(url);
this.path = path; this.path = path;
} }
@@ -123,7 +123,7 @@ public final class PathClassLoader extends ClassLoader {
public long getContentLengthLong() { public long getContentLengthLong() {
try { try {
return Files.size(this.path); return Files.size(this.path);
} catch (IOException e) { } catch (final IOException e) {
throw new RuntimeException("could not get size of: " + this.path, e); throw new RuntimeException("could not get size of: " + this.path, e);
} }
} }
@@ -147,7 +147,7 @@ public final class PathClassLoader extends ClassLoader {
@Override @Override
@SneakyThrows @SneakyThrows
public long getLastModified() { public long getLastModified() {
BasicFileAttributes attributes = Files.readAttributes(this.path, BasicFileAttributes.class); final BasicFileAttributes attributes = Files.readAttributes(this.path, BasicFileAttributes.class);
return attributes.lastModifiedTime().toMillis(); return attributes.lastModifiedTime().toMillis();
} }
} }
@@ -159,9 +159,9 @@ public final class PathClassLoader extends ClassLoader {
@Override @Override
@SneakyThrows @SneakyThrows
protected URLConnection openConnection(URL url) { protected URLConnection openConnection(final URL url) {
URI uri = url.toURI(); final URI uri = url.toURI();
Path path = Paths.get(uri); final Path path = Paths.get(uri);
return new PathURLConnection(url, path); return new PathURLConnection(url, path);
} }
} }

View File

@@ -8,9 +8,9 @@ import java.util.function.Predicate;
public interface Pre<T> extends Predicate<T> { public interface Pre<T> extends Predicate<T> {
@Override @Override
@SneakyThrows @SneakyThrows
default boolean test(T t) { default boolean test(final T t) {
return exec(t); return exec(t);
} }
boolean exec(T t) throws Throwable; boolean exec(final T t) throws Throwable;
} }

View File

@@ -12,12 +12,12 @@ import static net.woggioni.jwo.JWO.newThrowable;
public class Requirement { public class Requirement {
private final Supplier<Boolean> booleanSupplier; private final Supplier<Boolean> booleanSupplier;
public static Requirement require(Supplier<Boolean> booleanSupplier) { public static Requirement require(final Supplier<Boolean> booleanSupplier) {
return new Requirement(booleanSupplier); return new Requirement(booleanSupplier);
} }
@SneakyThrows @SneakyThrows
public <T extends Throwable> void otherwise(Class<T> cls, String format, Object... args) { public <T extends Throwable> void otherwise(final Class<T> cls, final String format, final Object... args) {
if(!booleanSupplier.get()) { if(!booleanSupplier.get()) {
throw newThrowable(cls, format, args); throw newThrowable(cls, format, args);
} }

View File

@@ -37,115 +37,115 @@ public class RetryExecutor {
} }
public interface ExceptionHandler { public interface ExceptionHandler {
ExceptionHandlerOutcome handleError(Throwable t); ExceptionHandlerOutcome handleError(final Throwable t);
} }
public CompletableFuture<Void> submit(Runnable cb) { public CompletableFuture<Void> submit(final Runnable cb) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public CompletableFuture<Void> submit( public CompletableFuture<Void> submit(
Runnable cb, final Runnable cb,
ExecutorService executorService) { final ExecutorService executorService) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService);
} }
public CompletableFuture<Void> submit( public CompletableFuture<Void> submit(
Runnable cb, final Runnable cb,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
ExecutorService executorService) { final ExecutorService executorService) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService);
} }
public CompletableFuture<Void> submit( public CompletableFuture<Void> submit(
Runnable cb, final Runnable cb,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
ExecutorService executorService) { final ExecutorService executorService) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService);
} }
public CompletableFuture<Void> submit( public CompletableFuture<Void> submit(
Runnable cb, final Runnable cb,
Duration initialDelay, final Duration initialDelay,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
ExecutorService executorService) { final ExecutorService executorService) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executorService);
} }
public static CompletableFuture<Void> submit( public static CompletableFuture<Void> submit(
Runnable cb, final Runnable cb,
int maxAttempts, final int maxAttempts,
Duration initialDelay, final Duration initialDelay,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
Executor executor) { final Executor executor) {
return submit(() -> { return submit(() -> {
cb.run(); cb.run();
return null; return null;
}, maxAttempts, initialDelay, exp, exceptionHandler, executor); }, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public <T> CompletableFuture<T> submit(Callable<T> cb) { public <T> CompletableFuture<T> submit(final Callable<T> cb) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public <T> CompletableFuture<T> submit( public <T> CompletableFuture<T> submit(
Callable<T> cb, final Callable<T> cb,
Executor executor) { final Executor executor) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public <T> CompletableFuture<T> submit( public <T> CompletableFuture<T> submit(
Callable<T> cb, final Callable<T> cb,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
Executor executor) { final Executor executor) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public <T> CompletableFuture<T> submit( public <T> CompletableFuture<T> submit(
Callable<T> cb, final Callable<T> cb,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
ExecutorService executor) { final ExecutorService executor) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public <T> CompletableFuture<T> submit( public <T> CompletableFuture<T> submit(
Callable<T> cb, final Callable<T> cb,
Duration initialDelay, final Duration initialDelay,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
ExecutorService executor) { final ExecutorService executor) {
return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor); return submit(cb, maxAttempts, initialDelay, exp, exceptionHandler, executor);
} }
public static <T> CompletableFuture<T> submit( public static <T> CompletableFuture<T> submit(
Callable<T> cb, final Callable<T> cb,
int maxAttempts, final int maxAttempts,
Duration initialDelay, final Duration initialDelay,
Double exp, final Double exp,
ExceptionHandler exceptionHandler, final ExceptionHandler exceptionHandler,
Executor executor) { final Executor executor) {
CompletableFuture<T> result = CompletableFuture.supplyAsync((Sup<T>) cb::call, executor); CompletableFuture<T> result = CompletableFuture.supplyAsync((Sup<T>) cb::call, executor);
double delay = initialDelay.toMillis(); double delay = initialDelay.toMillis();
for(int i = 1; i <= maxAttempts; i++) { for(int i = 1; i <= maxAttempts; i++) {
int attempt = i; final int attempt = i;
double thisAttemptDelay = delay; final double thisAttemptDelay = delay;
result = result.handleAsync((BiFun<T, Throwable, CompletableFuture<T>>) (value, err) -> { result = result.handleAsync((BiFun<T, Throwable, CompletableFuture<T>>) (value, err) -> {
Optional<Throwable> causeOpt = Optional.ofNullable(err).map(Throwable::getCause); final Optional<Throwable> causeOpt = Optional.ofNullable(err).map(Throwable::getCause);
if(!causeOpt.isPresent()) { if(!causeOpt.isPresent()) {
return CompletableFuture.completedFuture(value); return CompletableFuture.completedFuture(value);
} else if(attempt == maxAttempts) { } else if(attempt == maxAttempts) {
throw causeOpt.get(); throw causeOpt.get();
} else { } else {
Throwable cause = causeOpt.get(); final Throwable cause = causeOpt.get();
ExceptionHandlerOutcome eho = exceptionHandler.handleError(cause); final ExceptionHandlerOutcome eho = exceptionHandler.handleError(cause);
switch (eho) { switch (eho) {
case THROW: case THROW:
throw cause; throw cause;
case CONTINUE: case CONTINUE:
Executor delayedExecutor = delayedExecutor( final Executor delayedExecutor = delayedExecutor(
(long) thisAttemptDelay, (long) thisAttemptDelay,
TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS,
executor executor

View File

@@ -26,12 +26,12 @@ public class SQL {
private final Map<String, Tuple2<Object, Class<?>>> fields = new TreeMap<>(); private final Map<String, Tuple2<Object, Class<?>>> fields = new TreeMap<>();
public QueryBuilder field(String name, Object value, Class<?> cls) { public QueryBuilder field(final String name, final Object value, final Class<?> cls) {
fields.put(name, Tuple2.newInstance(value, cls)); fields.put(name, Tuple2.newInstance(value, cls));
return this; return this;
} }
public QueryBuilder field(String name, Object value) { public QueryBuilder field(final String name, final Object value) {
if(value == null) { if(value == null) {
throw newThrowable(IllegalArgumentException.class, "Class argument required for null value"); throw newThrowable(IllegalArgumentException.class, "Class argument required for null value");
} }
@@ -39,15 +39,15 @@ public class SQL {
} }
@SneakyThrows @SneakyThrows
public PreparedStatement buildStatement(Connection conn) { public PreparedStatement buildStatement(final Connection conn) {
StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
switch (operation) { switch (operation) {
case INSERT: case INSERT:
sb.append("INSERT INTO "); sb.append("INSERT INTO ");
sb.append(tableName); sb.append(tableName);
sb.append(" ("); sb.append(" (");
int i = 0; int i = 0;
List<Map.Entry<String, Tuple2<Object, Class<?>>>> entries = new ArrayList<>(fields.entrySet()); final List<Map.Entry<String, Tuple2<Object, Class<?>>>> entries = new ArrayList<>(fields.entrySet());
for(Map.Entry<String, Tuple2<Object, Class<?>>> entry : entries) { for(Map.Entry<String, Tuple2<Object, Class<?>>> entry : entries) {
if(i++ > 0) sb.append(','); if(i++ > 0) sb.append(',');
sb.append(entry.getKey()); sb.append(entry.getKey());
@@ -58,12 +58,12 @@ public class SQL {
if(i > 0) sb.append(','); if(i > 0) sb.append(',');
} }
sb.append(");"); sb.append(");");
PreparedStatement stmt = conn.prepareStatement(sb.toString()); final PreparedStatement stmt = conn.prepareStatement(sb.toString());
i = 1; i = 1;
for(Map.Entry<String, Tuple2<Object, Class<?>>> entry : entries) { for(final Map.Entry<String, Tuple2<Object, Class<?>>> entry : entries) {
Tuple2<Object, Class<?>> tuple2 = entry.getValue(); final Tuple2<Object, Class<?>> tuple2 = entry.getValue();
Object value = tuple2.get_1(); final Object value = tuple2.get_1();
Class<?> cls = tuple2.get_2(); final Class<?> cls = tuple2.get_2();
if(cls.isAssignableFrom(String.class)) { if(cls.isAssignableFrom(String.class)) {
stmt.setString(i, (String) value); stmt.setString(i, (String) value);
} else if(cls.isAssignableFrom(Integer.class)) { } else if(cls.isAssignableFrom(Integer.class)) {

View File

@@ -27,13 +27,13 @@ class SignatureCollector {
/** /**
* @return if the [entry] [JarEntry] can be signed. * @return if the [entry] [JarEntry] can be signed.
*/ */
static boolean isSignable(JarEntry entry) { static boolean isSignable(final JarEntry entry) {
return !entry.isDirectory() && !unsignableEntryName.matcher(entry.getName()).matches(); return !entry.isDirectory() && !unsignableEntryName.matcher(entry.getName()).matches();
} }
private static Set<PublicKey> signers2OrderedPublicKeys(CodeSigner[] signers) { private static Set<PublicKey> signers2OrderedPublicKeys(final CodeSigner[] signers) {
Set<PublicKey> result = new LinkedHashSet<>(); final Set<PublicKey> result = new LinkedHashSet<>();
for (CodeSigner signer : signers) { for (final CodeSigner signer : signers) {
result.add((signer.getSignerCertPath().getCertificates().get(0)).getPublicKey()); result.add((signer.getSignerCertPath().getCertificates().get(0)).getPublicKey());
} }
return Collections.unmodifiableSet(result); return Collections.unmodifiableSet(result);
@@ -47,13 +47,13 @@ class SignatureCollector {
return Collections.unmodifiableSet(_certificates); return Collections.unmodifiableSet(_certificates);
} }
public void addEntry(JarEntry jarEntry) { public void addEntry(final JarEntry jarEntry) {
if (isSignable(jarEntry)) { if (isSignable(jarEntry)) {
CodeSigner[] entrySigners = jarEntry.getCodeSigners() != null ? jarEntry.getCodeSigners() : new CodeSigner[0]; final CodeSigner[] entrySigners = jarEntry.getCodeSigners() != null ? jarEntry.getCodeSigners() : new CodeSigner[0];
if (codeSigners == null) { if (codeSigners == null) {
codeSigners = entrySigners; codeSigners = entrySigners;
firstSignedEntry = jarEntry.getName(); firstSignedEntry = jarEntry.getName();
for (CodeSigner signer : entrySigners) { for (final CodeSigner signer : entrySigners) {
_certificates.add(signer.getSignerCertPath().getCertificates().get(0)); _certificates.add(signer.getSignerCertPath().getCertificates().get(0));
} }
} }

View File

@@ -28,11 +28,11 @@ public class SortedProperties extends Properties {
@Override @Override
public Set<Object> keySet() { public Set<Object> keySet() {
Enumeration<Object> enumeration = super.keys(); final Enumeration<Object> enumeration = super.keys();
TreeSet<String> sortedSet = new TreeSet<>(); final TreeSet<String> sortedSet = new TreeSet<>();
while(enumeration.hasMoreElements()) { while(enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement(); final String key = (String) enumeration.nextElement();
sortedSet.add(key); sortedSet.add(key);
} }
return (Set) sortedSet; return (Set) sortedSet;
@@ -40,11 +40,11 @@ public class SortedProperties extends Properties {
@Override @Override
public Set<Map.Entry<Object, Object>> entrySet() { public Set<Map.Entry<Object, Object>> entrySet() {
Enumeration<Object> enumeration = keys(); final Enumeration<Object> enumeration = keys();
TreeMap<String, Object> sortedMap = new TreeMap<>(); final TreeMap<String, Object> sortedMap = new TreeMap<>();
while(enumeration.hasMoreElements()) { while(enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement(); final String key = (String) enumeration.nextElement();
sortedMap.put(key, get(key)); sortedMap.put(key, get(key));
} }
return (Set) sortedMap.entrySet(); return (Set) sortedMap.entrySet();

View File

@@ -31,7 +31,7 @@ public interface TreeNodeVisitor<NODE extends TreeNodeVisitor.TreeNode<NODE>, T>
/** /**
* @param ctx the user object to set for this stack level * @param ctx the user object to set for this stack level
*/ */
void setContext(T ctx); void setContext(final T ctx);
/** /**
* @return the current user object * @return the current user object
@@ -55,7 +55,7 @@ public interface TreeNodeVisitor<NODE extends TreeNodeVisitor.TreeNode<NODE>, T>
* current node in the tree * current node in the tree
* @return a boolean that will be used to decide whether to traverse the subtree rooted in the current link or not * @return a boolean that will be used to decide whether to traverse the subtree rooted in the current link or not
*/ */
default VisitOutcome visitPre(List<StackContext<NODE, T>> stack) { return VisitOutcome.CONTINUE; } default VisitOutcome visitPre(final List<StackContext<NODE, T>> stack) { return VisitOutcome.CONTINUE; }
/** /**
* This method will be called for each node using * This method will be called for each node using
@@ -63,5 +63,5 @@ public interface TreeNodeVisitor<NODE extends TreeNodeVisitor.TreeNode<NODE>, T>
* @param stack is a list of {@link StackContext} instances corresponding to the full path from the root to the * @param stack is a list of {@link StackContext} instances corresponding to the full path from the root to the
* current node in the tree * current node in the tree
*/ */
default void visitPost(List<StackContext<NODE, T>> stack) {} default void visitPost(final List<StackContext<NODE, T>> stack) {}
} }

View File

@@ -35,11 +35,11 @@ public class TreeWalker<NODE extends TreeNodeVisitor.TreeNode<NODE>, T> {
* {@link TreeNodeVisitor} instance * {@link TreeNodeVisitor} instance
* @param root the root node of the tree * @param root the root node of the tree
*/ */
public void walk(NODE root) { public void walk(final NODE root) {
List<StackElement<NODE, T>> stack = new ArrayList<>(); final List<StackElement<NODE, T>> stack = new ArrayList<>();
StackElement<NODE, T> rootStackElement = new StackElement<>(root); final StackElement<NODE, T> rootStackElement = new StackElement<>(root);
stack.add(rootStackElement); stack.add(rootStackElement);
List<TreeNodeVisitor.StackContext<NODE, T>> publicStack = Collections.unmodifiableList(stack); final List<TreeNodeVisitor.StackContext<NODE, T>> publicStack = Collections.unmodifiableList(stack);
switch (visitor.visitPre(publicStack)) { switch (visitor.visitPre(publicStack)) {
case CONTINUE: case CONTINUE:
rootStackElement.childrenIterator = root.children(); rootStackElement.childrenIterator = root.children();
@@ -51,10 +51,10 @@ public class TreeWalker<NODE extends TreeNodeVisitor.TreeNode<NODE>, T> {
return; return;
} }
while(!stack.isEmpty()) { while(!stack.isEmpty()) {
StackElement<NODE, T> lastElement = tail(stack); final StackElement<NODE, T> lastElement = tail(stack);
if(lastElement.childrenIterator != null && lastElement.childrenIterator.hasNext()) { if(lastElement.childrenIterator != null && lastElement.childrenIterator.hasNext()) {
NODE childNode = lastElement.childrenIterator.next(); final NODE childNode = lastElement.childrenIterator.next();
StackElement<NODE, T> childStackElement = final StackElement<NODE, T> childStackElement =
new StackElement<>(childNode); new StackElement<>(childNode);
stack.add(childStackElement); stack.add(childStackElement);
switch (visitor.visitPre(publicStack)) { switch (visitor.visitPre(publicStack)) {

View File

@@ -9,17 +9,17 @@ public interface Tuple2<T, U> {
T get_1(); T get_1();
U get_2(); U get_2();
static <T,U> Tuple2<T, U> newInstance(T x, U y) { static <T,U> Tuple2<T, U> newInstance(final T x, final U y) {
return new Tuple2Impl<>(x, y); return new Tuple2Impl<>(x, y);
} }
static <X extends Comparable<X>, Y extends Comparable<Y>> Comparator<Tuple2<X, Y>> getComparator(Class<X> cls1, Class<Y> cls2) { static <X extends Comparable<X>, Y extends Comparable<Y>> Comparator<Tuple2<X, Y>> getComparator(final Class<X> cls1, final Class<Y> cls2) {
return Comparator return Comparator
.comparing((Function<Tuple2<X, Y>, X>) Tuple2::get_1) .comparing((Function<Tuple2<X, Y>, X>) Tuple2::get_1)
.thenComparing(Tuple2::get_2); .thenComparing(Tuple2::get_2);
} }
static <X extends Comparable<X>, Y extends Comparable<Y>> Comparator<Tuple2<X, Y>> getComparator(Tuple2<X, Y> tuple) { static <X extends Comparable<X>, Y extends Comparable<Y>> Comparator<Tuple2<X, Y>> getComparator(final Tuple2<X, Y> tuple) {
return Comparator return Comparator
.comparing((Function<Tuple2<X, Y>, X>) Tuple2::get_1) .comparing((Function<Tuple2<X, Y>, X>) Tuple2::get_1)
.thenComparing(Tuple2::get_2); .thenComparing(Tuple2::get_2);

View File

@@ -9,12 +9,12 @@ public interface Tuple3<T, U, V> {
U get_2(); U get_2();
V get_3(); V get_3();
static <T, U, V> Tuple3<T, U, V> newInstance(T x, U y, V z) { static <T, U, V> Tuple3<T, U, V> newInstance(final T x, final U y, final V z) {
return new Tuple3Impl<>(x, y, z); return new Tuple3Impl<>(x, y, z);
} }
static <X extends Comparable<X>, Y extends Comparable<Y>, Z extends Comparable<Z>> static <X extends Comparable<X>, Y extends Comparable<Y>, Z extends Comparable<Z>>
Comparator<Tuple3<X, Y, Z>> getComparator(Class<X> cls1, Class<Y> cls2, Class<Z> cls3) { Comparator<Tuple3<X, Y, Z>> getComparator(final Class<X> cls1, final Class<Y> cls2, final Class<Z> cls3) {
return Comparator return Comparator
.comparing((Tuple3<X, Y, Z> t) -> t.get_1()) .comparing((Tuple3<X, Y, Z> t) -> t.get_1())
.thenComparing((Tuple3<X, Y, Z> t) -> t.get_2()) .thenComparing((Tuple3<X, Y, Z> t) -> t.get_2())
@@ -22,7 +22,7 @@ public interface Tuple3<T, U, V> {
} }
static <X extends Comparable<X>, Y extends Comparable<Y>, Z extends Comparable<Z>> static <X extends Comparable<X>, Y extends Comparable<Y>, Z extends Comparable<Z>>
Comparator<Tuple3<X, Y, Z>> getComparator(Tuple3<X, Y, Z> tuple) { Comparator<Tuple3<X, Y, Z>> getComparator(final Tuple3<X, Y, Z> tuple) {
return Comparator return Comparator
.comparing((Tuple3<X, Y, Z> t) -> t.get_1()) .comparing((Tuple3<X, Y, Z> t) -> t.get_1())
.thenComparing((Tuple3<X, Y, Z> t) -> t.get_2()) .thenComparing((Tuple3<X, Y, Z> t) -> t.get_2())

View File

@@ -10,7 +10,7 @@ import java.io.InputStream;
*/ */
public class UncloseableInputStream extends FilterInputStream { public class UncloseableInputStream extends FilterInputStream {
public UncloseableInputStream(InputStream source) { public UncloseableInputStream(final InputStream source) {
super(source); super(source);
} }

View File

@@ -10,7 +10,7 @@ import java.io.OutputStream;
*/ */
public class UncloseableOutputStream extends FilterOutputStream { public class UncloseableOutputStream extends FilterOutputStream {
public UncloseableOutputStream(OutputStream source) { public UncloseableOutputStream(final OutputStream source) {
super(source); super(source);
} }

View File

@@ -5,7 +5,7 @@ import java.io.IOException;
import java.io.Writer; import java.io.Writer;
public class UncloseableWriter extends FilterWriter { public class UncloseableWriter extends FilterWriter {
public UncloseableWriter(Writer destination) { public UncloseableWriter(final Writer destination) {
super(destination); super(destination);
} }

View File

@@ -18,8 +18,8 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
private final List<Map<K, V>> delegates; private final List<Map<K, V>> delegates;
public static <K, V> UnmodifiableDelegatingMap<K, V> of( public static <K, V> UnmodifiableDelegatingMap<K, V> of(
Supplier<Map<K, V>> mapFactory, final Supplier<Map<K, V>> mapFactory,
Map<K, V>... delegates final Map<K, V>... delegates
) { ) {
return new UnmodifiableDelegatingMap<>(mapFactory, Arrays.asList(delegates)); return new UnmodifiableDelegatingMap<>(mapFactory, Arrays.asList(delegates));
} }
@@ -31,7 +31,7 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
@Override @Override
public boolean isEmpty() { public boolean isEmpty() {
for (Map<K, V> delegate : delegates) { for (final Map<K, V> delegate : delegates) {
if (!delegate.isEmpty()) { if (!delegate.isEmpty()) {
return false; return false;
} }
@@ -40,8 +40,8 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
} }
@Override @Override
public boolean containsKey(Object key) { public boolean containsKey(final Object key) {
for (Map<K, V> delegate : delegates) { for (final Map<K, V> delegate : delegates) {
if (delegate.containsKey(key)) { if (delegate.containsKey(key)) {
return true; return true;
} }
@@ -50,8 +50,8 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
} }
@Override @Override
public boolean containsValue(Object value) { public boolean containsValue(final Object value) {
for (Map<K, V> delegate : delegates) { for (final Map<K, V> delegate : delegates) {
if (delegate.containsValue(value)) { if (delegate.containsValue(value)) {
return true; return true;
} }
@@ -60,9 +60,9 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
} }
@Override @Override
public V get(Object key) { public V get(final Object key) {
V result = null; V result = null;
for (Map<K, V> delegate : delegates) { for (final Map<K, V> delegate : delegates) {
result = delegate.get(key); result = delegate.get(key);
if (result != null) break; if (result != null) break;
} }
@@ -70,17 +70,17 @@ public class UnmodifiableDelegatingMap<K, V> implements Map<K, V> {
} }
@Override @Override
public V put(K key, V value) { public V put(final K key, final V value) {
throw newThrowable(UnsupportedOperationException.class); throw newThrowable(UnsupportedOperationException.class);
} }
@Override @Override
public V remove(Object key) { public V remove(final Object key) {
throw newThrowable(UnsupportedOperationException.class); throw newThrowable(UnsupportedOperationException.class);
} }
@Override @Override
public void putAll(Map<? extends K, ? extends V> m) { public void putAll(final Map<? extends K, ? extends V> m) {
throw newThrowable(UnsupportedOperationException.class); throw newThrowable(UnsupportedOperationException.class);
} }

View File

@@ -6,7 +6,7 @@ import java.util.Objects;
public class VersionComparator implements Comparator<String> { public class VersionComparator implements Comparator<String> {
private static int indexOf(char[] haystack, char needle, int start) { private static int indexOf(final char[] haystack, final char needle, final int start) {
int result = -1; int result = -1;
for (int i = start; i < haystack.length; ++i) { for (int i = start; i < haystack.length; ++i) {
if (haystack[i] == needle) { if (haystack[i] == needle) {
@@ -17,12 +17,12 @@ public class VersionComparator implements Comparator<String> {
return result; return result;
} }
private static int indexOf(char[] haystack, char needle) { private static int indexOf(final char[] haystack, final char needle) {
return indexOf(haystack, needle, 0); return indexOf(haystack, needle, 0);
} }
private static char[] cstring(String s) { private static char[] cstring(final String s) {
char[] result = new char[s.length() + 1]; final char[] result = new char[s.length() + 1];
for(int i=0; i<s.length(); i++) { for(int i=0; i<s.length(); i++) {
result[i] = s.charAt(i); result[i] = s.charAt(i);
} }
@@ -30,11 +30,11 @@ public class VersionComparator implements Comparator<String> {
return result; return result;
} }
private static boolean cstringEquals(char[] cstring1, int begin1, char[] cstring2, int begin2) { private static boolean cstringEquals(final char[] cstring1, final int begin1, final char[] cstring2, final int begin2) {
int i=0; int i=0;
while(i < cstring1.length + begin1 || i < cstring2.length + begin2) { while(i < cstring1.length + begin1 || i < cstring2.length + begin2) {
char c1 = cstring1[begin1 + i]; final char c1 = cstring1[begin1 + i];
char c2 = cstring2[begin2 + i]; final char c2 = cstring2[begin2 + i];
if(c1 != c2) return false; if(c1 != c2) return false;
else if(c1 == '\0') break; else if(c1 == '\0') break;
i++; i++;
@@ -42,7 +42,7 @@ public class VersionComparator implements Comparator<String> {
return true; return true;
} }
private static int strlen(char[] cstring, int begin) { private static int strlen(final char[] cstring, final int begin) {
int i = begin; int i = begin;
while(i < cstring.length) { while(i < cstring.length) {
if(cstring[i] == '\0') break; if(cstring[i] == '\0') break;
@@ -51,16 +51,16 @@ public class VersionComparator implements Comparator<String> {
return i - begin; return i - begin;
} }
private static int strlen(char[] cstring) { private static int strlen(final char[] cstring) {
return strlen(cstring, 0); return strlen(cstring, 0);
} }
private static int strcmp(char[] cstring1, int begin1, char[] cstring2, int begin2) { private static int strcmp(final char[] cstring1, final int begin1, final char[] cstring2, final int begin2) {
int i = 0; int i = 0;
int lim = Math.min(strlen(cstring1, begin1), strlen(cstring2, begin2)); final int lim = Math.min(strlen(cstring1, begin1), strlen(cstring2, begin2));
while(i < lim) { while(i < lim) {
char c1 = cstring1[begin1 + i]; final char c1 = cstring1[begin1 + i];
char c2 = cstring2[begin2 + i]; final char c2 = cstring2[begin2 + i];
if(c1 < c2) { if(c1 < c2) {
return -1; return -1;
} else if(c1 > c2) { } else if(c1 > c2) {
@@ -76,7 +76,7 @@ public class VersionComparator implements Comparator<String> {
* @param text [epoch:]version[-release] string * @param text [epoch:]version[-release] string
* @param evr array that will contain starting indexes of epoch, version, and release * @param evr array that will contain starting indexes of epoch, version, and release
*/ */
private static void parseEVR(char[] text, int[] evr) { private static void parseEVR(final char[] text, final int[] evr) {
int epoch; int epoch;
int version; int version;
int release; int release;
@@ -111,11 +111,11 @@ public class VersionComparator implements Comparator<String> {
} }
private static int rpmvercmp(char[] chars1, int start1, char[] chars2, int start2) { private static int rpmvercmp(final char[] chars1, final int start1, final char[] chars2, final int start2) {
// easy comparison to see if versions are identical // easy comparison to see if versions are identical
if(strcmp(chars1, start1, chars2, start2) == 0) return 0; if(strcmp(chars1, start1, chars2, start2) == 0) return 0;
char[] str1 = Arrays.copyOfRange(chars1, start1, start1 + strlen(chars1, start1) + 1); final char[] str1 = Arrays.copyOfRange(chars1, start1, start1 + strlen(chars1, start1) + 1);
char[] str2 = Arrays.copyOfRange(chars2, start2, start2 + strlen(chars2, start2) + 1); final char[] str2 = Arrays.copyOfRange(chars2, start2, start2 + strlen(chars2, start2) + 1);
int one = 0, two = 0; int one = 0, two = 0;
int ptr1 = 0, ptr2 = 0; int ptr1 = 0, ptr2 = 0;
boolean isNum; boolean isNum;
@@ -207,8 +207,8 @@ public class VersionComparator implements Comparator<String> {
while (str2[two] == '0') two++; while (str2[two] == '0') two++;
/* whichever number has more digits wins */ /* whichever number has more digits wins */
int len1 = strlen(str1, one); final int len1 = strlen(str1, one);
int len2 = strlen(str2, two); final int len2 = strlen(str2, two);
if (len1 > len2) { if (len1 > len2) {
return 1; return 1;
} else if (len2 > len1) { } else if (len2 > len1) {
@@ -219,7 +219,7 @@ public class VersionComparator implements Comparator<String> {
// segments are alpha or if they are numeric. don't return // segments are alpha or if they are numeric. don't return
// if they are equal because there might be more segments to // if they are equal because there might be more segments to
// compare // compare
int rc = strcmp(str1, one, str2, two); final int rc = strcmp(str1, one, str2, two);
if (rc != 0) return rc; if (rc != 0) return rc;
// restore character that was replaced by null above // restore character that was replaced by null above
@@ -252,26 +252,26 @@ public class VersionComparator implements Comparator<String> {
private static char[] defaultEpoch = new char[] {'0'}; private static char[] defaultEpoch = new char[] {'0'};
public static int cmp(String v1, String v2) { public static int cmp(final String v1, final String v2) {
if(v1 == null && v2 == null) return 0; if(v1 == null && v2 == null) return 0;
else if(v1 == null) return -1; else if(v1 == null) return -1;
else if(v2 == null) return 1; else if(v2 == null) return 1;
else if(Objects.equals(v1, v2)) return 0; else if(Objects.equals(v1, v2)) return 0;
char[] chars1 = cstring(v1); final char[] chars1 = cstring(v1);
char[] chars2 = cstring(v2); final char[] chars2 = cstring(v2);
int[] evr = new int[3]; final int[] evr = new int[3];
parseEVR(chars1, evr); parseEVR(chars1, evr);
int epoch1 = evr[0]; final int epoch1 = evr[0];
int version1 = evr[1]; final int version1 = evr[1];
int release1 = evr[2]; final int release1 = evr[2];
parseEVR(chars2, evr); parseEVR(chars2, evr);
int epoch2 = evr[0]; final int epoch2 = evr[0];
int version2 = evr[1]; final int version2 = evr[1];
int release2 = evr[2]; final int release2 = evr[2];
char[] seq1 = epoch1 == -1 ? defaultEpoch : chars1; final char[] seq1 = epoch1 == -1 ? defaultEpoch : chars1;
char[] seq2 = epoch2 == -1 ? defaultEpoch : chars2; final char[] seq2 = epoch2 == -1 ? defaultEpoch : chars2;
int ret = rpmvercmp(seq1, epoch1 == -1 ? 0 : epoch1, seq2, epoch2 == -1 ? 0 : epoch2); int ret = rpmvercmp(seq1, epoch1 == -1 ? 0 : epoch1, seq2, epoch2 == -1 ? 0 : epoch2);
if(ret == 0) { if(ret == 0) {
ret = rpmvercmp(chars1, version1, chars2, version2); ret = rpmvercmp(chars1, version1, chars2, version2);
@@ -283,7 +283,7 @@ public class VersionComparator implements Comparator<String> {
} }
@Override @Override
public int compare(String v1, String v2) { public int compare(final String v1, final String v2) {
return cmp(v1, v2); return cmp(v1, v2);
} }
} }

View File

@@ -13,7 +13,7 @@ import java.util.zip.ZipInputStream;
*/ */
public class ZipExtractorInputStream extends ZipInputStream { public class ZipExtractorInputStream extends ZipInputStream {
public ZipExtractorInputStream(InputStream source, Path destination) { public ZipExtractorInputStream(final InputStream source, final Path destination) {
super(source); super(source);
this.destination = destination; this.destination = destination;
} }
@@ -24,9 +24,9 @@ public class ZipExtractorInputStream extends ZipInputStream {
@Override @Override
public ZipEntry getNextEntry() throws IOException { public ZipEntry getNextEntry() throws IOException {
ZipEntry entry = super.getNextEntry(); final ZipEntry entry = super.getNextEntry();
if(entry != null) { if(entry != null) {
Path newFileSystemLocation = destination.resolve(entry.getName()); final Path newFileSystemLocation = destination.resolve(entry.getName());
if(entry.isDirectory()) { if(entry.isDirectory()) {
Files.createDirectories(newFileSystemLocation); Files.createDirectories(newFileSystemLocation);
} else { } else {
@@ -39,14 +39,14 @@ public class ZipExtractorInputStream extends ZipInputStream {
@Override @Override
public int read() throws IOException { public int read() throws IOException {
int result = super.read(); final int result = super.read();
if(result != -1 && currentFile != null) currentFile.write(result); if(result != -1 && currentFile != null) currentFile.write(result);
return result; return result;
} }
@Override @Override
public int read(byte[] b, int off, int len) throws IOException { public int read(final byte[] b, final int off, final int len) throws IOException {
int read = super.read(b, off, len); final int read = super.read(b, off, len);
if(read != -1 && currentFile != null) currentFile.write(b, off, read); if(read != -1 && currentFile != null) currentFile.write(b, off, read);
return read; return read;
} }

View File

@@ -12,20 +12,20 @@ public class CompressionInputStream extends InputStream {
private final Thread writer; private final Thread writer;
private final InputStream processOutput; private final InputStream processOutput;
public CompressionInputStream(InputStream is, CompressionFormat compressionFormat) { public CompressionInputStream(final InputStream is, final CompressionFormat compressionFormat) {
this(is, compressionFormat, StreamMode.COMPRESSION); this(is, compressionFormat, StreamMode.COMPRESSION);
} }
public CompressionInputStream(InputStream is, CompressionFormat compressionFormat, Integer level) { public CompressionInputStream(final InputStream is, final CompressionFormat compressionFormat, final Integer level) {
this(is, compressionFormat, StreamMode.COMPRESSION, level); this(is, compressionFormat, StreamMode.COMPRESSION, level);
} }
public CompressionInputStream(InputStream is, CompressionFormat compressionFormat, StreamMode mode) { public CompressionInputStream(final InputStream is, final CompressionFormat compressionFormat, final StreamMode mode) {
this(is, compressionFormat, mode, null); this(is, compressionFormat, mode, null);
} }
@SneakyThrows @SneakyThrows
public CompressionInputStream(InputStream is, CompressionFormat compressionFormat, StreamMode mode, Integer level) { public CompressionInputStream(final InputStream is, final CompressionFormat compressionFormat, final StreamMode mode, final Integer level) {
inputStream = is; inputStream = is;
String[] cliArgs; String[] cliArgs;
switch(mode) { switch(mode) {
@@ -42,10 +42,10 @@ public class CompressionInputStream extends InputStream {
default: default:
throw new NullPointerException(); throw new NullPointerException();
} }
ProcessBuilder pb = new ProcessBuilder(cliArgs); final ProcessBuilder pb = new ProcessBuilder(cliArgs);
process = pb.start(); process = pb.start();
processOutput = process.getInputStream(); processOutput = process.getInputStream();
StreamWriter streamWriter = new StreamWriter(inputStream, process.getOutputStream()); final StreamWriter streamWriter = new StreamWriter(inputStream, process.getOutputStream());
writer = new Thread(streamWriter); writer = new Thread(streamWriter);
writer.start(); writer.start();
} }
@@ -56,7 +56,7 @@ public class CompressionInputStream extends InputStream {
} }
@Override @Override
public int read(byte[] bytes, int i, int i1) throws IOException { public int read(final byte[] bytes, final int i, final int i1) throws IOException {
return processOutput.read(bytes, i, i1); return processOutput.read(bytes, i, i1);
} }

View File

@@ -11,20 +11,20 @@ public class CompressionOutputStream extends OutputStream {
private final Thread writer; private final Thread writer;
private final OutputStream processInput; private final OutputStream processInput;
public CompressionOutputStream(OutputStream os, CompressionFormat compressionFormat) { public CompressionOutputStream(final OutputStream os, final CompressionFormat compressionFormat) {
this(os, compressionFormat, StreamMode.COMPRESSION); this(os, compressionFormat, StreamMode.COMPRESSION);
} }
public CompressionOutputStream(OutputStream os, CompressionFormat compressionFormat, Integer level) { public CompressionOutputStream(final OutputStream os, final CompressionFormat compressionFormat, final Integer level) {
this(os, compressionFormat, StreamMode.COMPRESSION, level); this(os, compressionFormat, StreamMode.COMPRESSION, level);
} }
public CompressionOutputStream(OutputStream os, CompressionFormat compressionFormat, StreamMode mode) { public CompressionOutputStream(final OutputStream os, final CompressionFormat compressionFormat, final StreamMode mode) {
this(os, compressionFormat, mode, null); this(os, compressionFormat, mode, null);
} }
@SneakyThrows @SneakyThrows
public CompressionOutputStream(OutputStream os, CompressionFormat compressionFormat, StreamMode mode, Integer level) { public CompressionOutputStream(final OutputStream os, final CompressionFormat compressionFormat, final StreamMode mode, final Integer level) {
outputStream = os; outputStream = os;
String[] cliArgs; String[] cliArgs;
switch(mode) { switch(mode) {
@@ -41,23 +41,23 @@ public class CompressionOutputStream extends OutputStream {
default: default:
throw new NullPointerException(); throw new NullPointerException();
} }
ProcessBuilder pb = new ProcessBuilder(cliArgs); final ProcessBuilder pb = new ProcessBuilder(cliArgs);
process = pb.start(); process = pb.start();
processInput = process.getOutputStream(); processInput = process.getOutputStream();
StreamWriter streamWriter = new StreamWriter(process.getInputStream(), outputStream); final StreamWriter streamWriter = new StreamWriter(process.getInputStream(), outputStream);
writer = new Thread(streamWriter); writer = new Thread(streamWriter);
writer.start(); writer.start();
} }
@Override @Override
@SneakyThrows @SneakyThrows
public void write(byte[] buffer, int offset, int size) { public void write(final byte[] buffer, final int offset, final int size) {
processInput.write(buffer, offset, size); processInput.write(buffer, offset, size);
} }
@Override @Override
@SneakyThrows @SneakyThrows
public void write(int i) { public void write(final int i) {
processInput.write(i); processInput.write(i);
} }

View File

@@ -6,14 +6,14 @@ import java.util.stream.Collectors;
public class ChildProcessException extends RuntimeException { public class ChildProcessException extends RuntimeException {
private static final String cmdLine2str(Iterable<String> cmdLine) { private static final String cmdLine2str(final Iterable<String> cmdLine) {
return JWO.iterable2Stream(cmdLine) return JWO.iterable2Stream(cmdLine)
.map(it -> it.replace("\"", "\\\"")) .map(it -> it.replace("\"", "\\\""))
.map(it -> "\"" + it + "\"") .map(it -> "\"" + it + "\"")
.collect(Collectors.joining(", ")); .collect(Collectors.joining(", "));
} }
public ChildProcessException(Iterable<String> cmdline, int exitCode) { public ChildProcessException(final Iterable<String> cmdline, final int exitCode) {
super(String.format("Child process [%s] terminated with exit code %d", cmdLine2str(cmdline), exitCode)); super(String.format("Child process [%s] terminated with exit code %d", cmdLine2str(cmdline), exitCode));
} }
} }

View File

@@ -14,7 +14,7 @@ public class ByteFilterInputStream extends FilterInputStream {
private final Set<Byte> forbidden; private final Set<Byte> forbidden;
public ByteFilterInputStream(InputStream source, Iterable<Byte> filteredChars) { public ByteFilterInputStream(final InputStream source, final Iterable<Byte> filteredChars) {
super(source); super(source);
forbidden = JWO.iterable2Stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet()); forbidden = JWO.iterable2Stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet());
} }
@@ -23,7 +23,7 @@ public class ByteFilterInputStream extends FilterInputStream {
@Override @Override
public int read() throws IOException { public int read() throws IOException {
while(true) { while(true) {
int res = super.read(); final int res = super.read();
if(!forbidden.contains(res)) { if(!forbidden.contains(res)) {
return res; return res;
} }
@@ -31,17 +31,17 @@ public class ByteFilterInputStream extends FilterInputStream {
} }
@Override @Override
public int read(byte[] b) throws IOException { public int read(final byte[] b) throws IOException {
return read(b, 0, b.length); return read(b, 0, b.length);
} }
@Override @Override
public int read(byte[] b, int off, int len) throws IOException { public int read(final byte[] b, final int off, final int len) throws IOException {
if(finished) return -1; if(finished) return -1;
int i = 0; int i = 0;
int lim = Math.min(len, b.length - off); final int lim = Math.min(len, b.length - off);
while(i < lim) { while(i < lim) {
int c = read(); final int c = read();
if(c < 0) { if(c < 0) {
break; break;
} }

View File

@@ -16,12 +16,12 @@ public class CharFilterReader extends FilterReader {
private final Set<Character> forbidden; private final Set<Character> forbidden;
public CharFilterReader(Reader source, Iterable<Character> filteredChars) { public CharFilterReader(final Reader source, final Iterable<Character> filteredChars) {
super(source); super(source);
forbidden = JWO.iterable2Stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet()); forbidden = JWO.iterable2Stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet());
} }
public CharFilterReader(Reader source, Character ...filteredChars) { public CharFilterReader(final Reader source, final Character ...filteredChars) {
super(source); super(source);
forbidden = Arrays.stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet()); forbidden = Arrays.stream(filteredChars).collect(CollectionUtils.toUnmodifiableTreeSet());
} }
@@ -30,7 +30,7 @@ public class CharFilterReader extends FilterReader {
@Override @Override
public int read() throws IOException { public int read() throws IOException {
while(true) { while(true) {
int res = super.read(); final int res = super.read();
if(!forbidden.contains((char) res)) { if(!forbidden.contains((char) res)) {
return res; return res;
} }
@@ -38,12 +38,12 @@ public class CharFilterReader extends FilterReader {
} }
@Override @Override
public int read(char[] cbuf, int off, int len) throws IOException { public int read(final char[] cbuf, final int off, final int len) throws IOException {
if(finished) return -1; if(finished) return -1;
int i = 0; int i = 0;
int lim = Math.min(len, cbuf.length - off); final int lim = Math.min(len, cbuf.length - off);
while(i < lim) { while(i < lim) {
int c = read(); final int c = read();
if(c < 0) { if(c < 0) {
break; break;
} }
@@ -55,12 +55,12 @@ public class CharFilterReader extends FilterReader {
} }
@Override @Override
public int read(CharBuffer target) throws IOException { public int read(final CharBuffer target) throws IOException {
return read(target.array()); return read(target.array());
} }
@Override @Override
public int read(char[] cbuf) throws IOException { public int read(final char[] cbuf) throws IOException {
return read(cbuf, 0, cbuf.length); return read(cbuf, 0, cbuf.length);
} }
} }

View File

@@ -16,15 +16,15 @@ public class LocalBucket implements Bucket {
private final AtomicLong availableTokens; private final AtomicLong availableTokens;
private final AtomicLong lastFill; private final AtomicLong lastFill;
public LocalBucket(long maxCapacity, long fillAmount, long fillPeriod) { public LocalBucket(final long maxCapacity, final long fillAmount, final long fillPeriod) {
this(maxCapacity, fillAmount, fillPeriod, maxCapacity); this(maxCapacity, fillAmount, fillPeriod, maxCapacity);
} }
public LocalBucket(long maxCapacity, long fillAmount, long fillPeriod, long initialAmount) { public LocalBucket(final long maxCapacity, final long fillAmount, final long fillPeriod, final long initialAmount) {
this(maxCapacity, fillAmount, fillPeriod, initialAmount, System.nanoTime()); this(maxCapacity, fillAmount, fillPeriod, initialAmount, System.nanoTime());
} }
public LocalBucket(long maxCapacity, long fillAmount, long fillPeriod, long initialAmount, long currentTimestamp) { public LocalBucket(final long maxCapacity, final long fillAmount, final long fillPeriod, final long initialAmount, final long currentTimestamp) {
if (maxCapacity <= 0 || fillAmount <= 0 || fillPeriod <= 0) { if (maxCapacity <= 0 || fillAmount <= 0 || fillPeriod <= 0) {
throw new IllegalArgumentException("maxCapacity, fillAmount and fillPeriod must all be positive"); throw new IllegalArgumentException("maxCapacity, fillAmount and fillPeriod must all be positive");
} }
@@ -35,7 +35,7 @@ public class LocalBucket implements Bucket {
this.lastFill = new AtomicLong(currentTimestamp); this.lastFill = new AtomicLong(currentTimestamp);
} }
private long getTokenPrivate(long nTokens, long now, long previousFillTime, long currentFillTime) { private long getTokenPrivate(final long nTokens, final long now, final long previousFillTime, final long currentFillTime) {
final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod; final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod;
if (currentFillTime != previousFillTime) { if (currentFillTime != previousFillTime) {
final long ticks = tickCalculator.applyAsLong(previousFillTime, now); final long ticks = tickCalculator.applyAsLong(previousFillTime, now);
@@ -65,34 +65,34 @@ public class LocalBucket implements Bucket {
@Override @Override
public boolean removeTokens(long nTokens) { public boolean removeTokens(final long nTokens) {
return removeTokens(nTokens, System.nanoTime()); return removeTokens(nTokens, System.nanoTime());
} }
@Override @Override
public boolean removeTokens(long nTokens, long now) { public boolean removeTokens(final long nTokens, final long now) {
if(nTokens > maxCapacity) throw new IllegalArgumentException("The requested number of tokens exceeds the bucket max capacity"); if(nTokens > maxCapacity) throw new IllegalArgumentException("The requested number of tokens exceeds the bucket max capacity");
final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod; final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod;
final LongBinaryOperator timestampCalculator = (lf, currentTimestamp) -> lf + tickCalculator.applyAsLong(lf, currentTimestamp) * fillPeriod; final LongBinaryOperator timestampCalculator = (lf, currentTimestamp) -> lf + tickCalculator.applyAsLong(lf, currentTimestamp) * fillPeriod;
final long previousFillTime = lastFill.getAndAccumulate(now, timestampCalculator); final long previousFillTime = lastFill.getAndAccumulate(now, timestampCalculator);
final long currentFillTime = timestampCalculator.applyAsLong(previousFillTime, now); final long currentFillTime = timestampCalculator.applyAsLong(previousFillTime, now);
long result = getTokenPrivate(nTokens, now, previousFillTime, currentFillTime); final long result = getTokenPrivate(nTokens, now, previousFillTime, currentFillTime);
return result >= nTokens; return result >= nTokens;
} }
@Override @Override
public long removeTokensWithEstimate(long nTokens) { public long removeTokensWithEstimate(final long nTokens) {
return removeTokensWithEstimate(nTokens, System.nanoTime()); return removeTokensWithEstimate(nTokens, System.nanoTime());
} }
@Override @Override
public long removeTokensWithEstimate(long nTokens, long now) { public long removeTokensWithEstimate(final long nTokens, final long now) {
if(nTokens > maxCapacity) throw new IllegalArgumentException("The requested number of tokens exceeds the bucket max capacity"); if(nTokens > maxCapacity) throw new IllegalArgumentException("The requested number of tokens exceeds the bucket max capacity");
final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod; final LongBinaryOperator tickCalculator = (lf, currentTimestamp) -> (currentTimestamp - lf) / fillPeriod;
final LongBinaryOperator timestampCalculator = (lf, currentTimestamp) -> lf + tickCalculator.applyAsLong(lf, currentTimestamp) * fillPeriod; final LongBinaryOperator timestampCalculator = (lf, currentTimestamp) -> lf + tickCalculator.applyAsLong(lf, currentTimestamp) * fillPeriod;
final long previousFillTime = lastFill.getAndAccumulate(now, timestampCalculator); final long previousFillTime = lastFill.getAndAccumulate(now, timestampCalculator);
final long currentFillTime = timestampCalculator.applyAsLong(previousFillTime, now); final long currentFillTime = timestampCalculator.applyAsLong(previousFillTime, now);
long previousTokenAmount = getTokenPrivate(nTokens, now, previousFillTime, currentFillTime); final long previousTokenAmount = getTokenPrivate(nTokens, now, previousFillTime, currentFillTime);
if(previousTokenAmount >= nTokens) { if(previousTokenAmount >= nTokens) {
return -1; return -1;
} else { } else {

View File

@@ -18,12 +18,12 @@ public class SynchronizedLazyValue<T> implements LazyValue<T> {
private final Consumer<T> finalizer; private final Consumer<T> finalizer;
private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false); private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false);
public SynchronizedLazyValue(Supplier<T> valueSupplier) { public SynchronizedLazyValue(final Supplier<T> valueSupplier) {
this(valueSupplier, null); this(valueSupplier, null);
} }
@Override @Override
public <U> LazyValue<U> map(Function<T, U> fun) { public <U> LazyValue<U> map(final Function<T, U> fun) {
return new SynchronizedLazyValue<>(() -> fun.apply(get())); return new SynchronizedLazyValue<>(() -> fun.apply(get()));
} }
@@ -37,7 +37,7 @@ public class SynchronizedLazyValue<T> implements LazyValue<T> {
synchronized (instance) { synchronized (instance) {
if(instance.get_2()) return instance.get_1(); if(instance.get_2()) return instance.get_1();
else { else {
T value = valueSupplier.get(); final T value = valueSupplier.get();
instance.set_1(value); instance.set_1(value);
instance.set_2(true); instance.set_2(true);
return value; return value;
@@ -46,11 +46,11 @@ public class SynchronizedLazyValue<T> implements LazyValue<T> {
} }
@Override @Override
public <U> SynchronizedLazyValue<U> handle(BiFunction<T, Throwable, U> bicon) { public <U> SynchronizedLazyValue<U> handle(final BiFunction<T, Throwable, U> bicon) {
return new SynchronizedLazyValue<>(() -> { return new SynchronizedLazyValue<>(() -> {
try { try {
return bicon.apply(get(), null); return bicon.apply(get(), null);
} catch (Throwable t) { } catch (final Throwable t) {
return bicon.apply(null, t); return bicon.apply(null, t);
} }
}); });

View File

@@ -18,12 +18,12 @@ public class UnsynchronizedLazyValue<T> implements LazyValue<T> {
private final Consumer<T> finalizer; private final Consumer<T> finalizer;
private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false); private final MutableTuple2<T, Boolean> instance = MutableTuple2.newInstance(null, false);
public UnsynchronizedLazyValue(Supplier<T> valueSupplier) { public UnsynchronizedLazyValue(final Supplier<T> valueSupplier) {
this(valueSupplier, null); this(valueSupplier, null);
} }
@Override @Override
public <U> LazyValue<U> map(Function<T, U> fun) { public <U> LazyValue<U> map(final Function<T, U> fun) {
return new UnsynchronizedLazyValue<>(() -> fun.apply(get())); return new UnsynchronizedLazyValue<>(() -> fun.apply(get()));
} }
@@ -35,7 +35,7 @@ public class UnsynchronizedLazyValue<T> implements LazyValue<T> {
public T get() { public T get() {
if(instance.get_2()) return instance.get_1(); if(instance.get_2()) return instance.get_1();
else { else {
T value = valueSupplier.get(); final T value = valueSupplier.get();
instance.set_1(value); instance.set_1(value);
instance.set_2(true); instance.set_2(true);
return value; return value;
@@ -43,11 +43,11 @@ public class UnsynchronizedLazyValue<T> implements LazyValue<T> {
} }
@Override @Override
public <U> UnsynchronizedLazyValue<U> handle(BiFunction<T, Throwable, U> bicon) { public <U> UnsynchronizedLazyValue<U> handle(final BiFunction<T, Throwable, U> bicon) {
return new UnsynchronizedLazyValue<>(() -> { return new UnsynchronizedLazyValue<>(() -> {
try { try {
return bicon.apply(get(), null); return bicon.apply(get(), null);
} catch (Throwable t) { } catch (final Throwable t) {
return bicon.apply(null, t); return bicon.apply(null, t);
} }
}); });

View File

@@ -12,12 +12,12 @@ public class Handler extends URLStreamHandler {
this.classLoader = getClass().getClassLoader(); this.classLoader = getClass().getClassLoader();
} }
public Handler(ClassLoader classLoader) { public Handler(final ClassLoader classLoader) {
this.classLoader = classLoader; this.classLoader = classLoader;
} }
@Override @Override
protected URLConnection openConnection(URL u) throws IOException { protected URLConnection openConnection(final URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath()); final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection(); return resourceUrl.openConnection();
} }

View File

@@ -11,7 +11,7 @@ import java.util.Optional;
public class Handler extends URLStreamHandler { public class Handler extends URLStreamHandler {
@Override @Override
protected URLConnection openConnection(URL u) throws IOException { protected URLConnection openConnection(final URL u) throws IOException {
final Module thisModule = getClass().getModule(); final Module thisModule = getClass().getModule();
final Module sourceModule = Optional.ofNullable(thisModule) final Module sourceModule = Optional.ofNullable(thisModule)
.map(Module::getLayer) .map(Module::getLayer)
@@ -25,7 +25,7 @@ public class Handler extends URLStreamHandler {
private static class ModuleResourceURLConnection extends URLConnection { private static class ModuleResourceURLConnection extends URLConnection {
private final Module module; private final Module module;
private ModuleResourceURLConnection(URL url, Module module) { private ModuleResourceURLConnection(final URL url, final Module module) {
super(url); super(url);
this.module = module; this.module = module;
} }

View File

@@ -18,7 +18,7 @@ class StackElement {
private final Node node; private final Node node;
private final NodeListIterator iterator; private final NodeListIterator iterator;
StackElement(Node node) { StackElement(final Node node) {
this.resultPre = null; this.resultPre = null;
this.node = node; this.node = node;
this.iterator = new NodeListIterator(node.getChildNodes()); this.iterator = new NodeListIterator(node.getChildNodes());
@@ -32,7 +32,7 @@ class Stack {
private final List<Node> nodes = Collections.unmodifiableList(nodeStack); private final List<Node> nodes = Collections.unmodifiableList(nodeStack);
public void push(Node node) { public void push(final Node node) {
stack.add(new StackElement(node)); stack.add(new StackElement(node));
nodeStack.add(node); nodeStack.add(node);
} }
@@ -58,21 +58,21 @@ class Stack {
@RequiredArgsConstructor @RequiredArgsConstructor
public class DocumentWalker { public class DocumentWalker {
public static void walk(Node root, XMLNodeVisitor visitor) { public static void walk(final Node root, final XMLNodeVisitor visitor) {
new DocumentWalker(root).walk(visitor); new DocumentWalker(root).walk(visitor);
} }
private final Node root; private final Node root;
public void walk(XMLNodeVisitor visitor) { public void walk(final XMLNodeVisitor visitor) {
Stack stack = new Stack(); final Stack stack = new Stack();
stack.push(root); stack.push(root);
loop: loop:
while(stack.isNotEmpty()) { while(stack.isNotEmpty()) {
StackElement se = stack.last(); final StackElement se = stack.last();
if(se.getIterator().hasNext()) { if(se.getIterator().hasNext()) {
Node childNode = se.getIterator().next(); final Node childNode = se.getIterator().next();
XMLNodeVisitor.NodeVisitResultPre result = se.getResultPre(); XMLNodeVisitor.NodeVisitResultPre result = se.getResultPre();
if(result == null) { if(result == null) {
result = visitor.visitNodePre(stack.nodes()); result = visitor.visitNodePre(stack.nodes());
@@ -88,7 +88,7 @@ public class DocumentWalker {
break loop; break loop;
} }
} else { } else {
XMLNodeVisitor.NodeVisitResultPost result = visitor.visitNodePost(stack.nodes()); final XMLNodeVisitor.NodeVisitResultPost result = visitor.visitNodePost(stack.nodes());
stack.pop(); stack.pop();
switch (result) { switch (result) {
case CONTINUE: case CONTINUE:

View File

@@ -19,59 +19,57 @@ public class ElementBuilder {
@Getter @Getter
private final Element root; private final Element root;
public ElementBuilder node(String name) { public ElementBuilder node(final String name) {
return node(name, eb -> { return node(name, eb -> {
}); });
} }
public ElementBuilder node(String name, Consumer<ElementBuilder> cb) { public ElementBuilder node(final String name, final Consumer<ElementBuilder> cb) {
Element child = doc.createElement(name); final Element child = doc.createElement(name);
if(root == null) { if(root == null) {
doc.appendChild(child); doc.appendChild(child);
} else { } else {
root.appendChild(child); root.appendChild(child);
} }
ElementBuilder eb = new ElementBuilder(doc, child); final ElementBuilder eb = new ElementBuilder(doc, child);
cb.accept(eb); cb.accept(eb);
return eb; return eb;
} }
public final ElementBuilder node(String name, String textContent, Map<String, String> attrs) { public final ElementBuilder node(final String name, final String textContent, final Map<String, String> attrs) {
return node(name, eb -> { return node(name, eb -> {
if(textContent != null) eb.text(textContent); if(textContent != null) eb.text(textContent);
for(Map.Entry<String, String> attr : attrs.entrySet()) { for(final Map.Entry<String, String> attr : attrs.entrySet()) {
eb.attr(attr.getKey(), attr.getValue()); eb.attr(attr.getKey(), attr.getValue());
} }
}); });
} }
@SafeVarargs @SafeVarargs
public final ElementBuilder node(String name, String textContent, Tuple2<String, String>...attrs) { public final ElementBuilder node(final String name, final String textContent, final Tuple2<String, String>...attrs) {
MapBuilder<String, String> mapBuilder = new MapBuilder<>(); final MapBuilder<String, String> mapBuilder = new MapBuilder<>();
for(Tuple2<String, String> attr : attrs) { for(final Tuple2<String, String> attr : attrs) {
mapBuilder.entry(attr.get_1(), attr.get_2()); mapBuilder.entry(attr.get_1(), attr.get_2());
} }
return node(name, textContent, mapBuilder.build(TreeMap::new)); return node(name, textContent, mapBuilder.build(TreeMap::new));
} }
@SafeVarargs @SafeVarargs
public final ElementBuilder node(String name, Tuple2<String, String>...attrs) { public final ElementBuilder node(final String name, final Tuple2<String, String>...attrs) {
return node(name, null, attrs); return node(name, null, attrs);
} }
public final ElementBuilder node(String name, Map<String, String> attrs) { public final ElementBuilder node(final String name, final Map<String, String> attrs) {
return node(name, null, attrs); return node(name, null, attrs);
} }
public ElementBuilder text(String textContent) { public ElementBuilder text(final String textContent) {
root.setTextContent(textContent); root.setTextContent(textContent);
return this; return this;
} }
public ElementBuilder attr(String name, String value) { public ElementBuilder attr(final String name, final String value) {
root.setAttribute(name, value); root.setAttribute(name, value);
return this; return this;
} }
} }

View File

@@ -12,11 +12,11 @@ public class ElementIterator implements Iterator<Element> {
private final String name; private final String name;
private Element next; private Element next;
public ElementIterator(Element parent) { public ElementIterator(final Element parent) {
this(parent, null); this(parent, null);
} }
public ElementIterator(Element parent, String name) { public ElementIterator(final Element parent, final String name) {
it = new NodeListIterator(parent.getChildNodes()); it = new NodeListIterator(parent.getChildNodes());
this.name = name; this.name = name;
next = getNext(); next = getNext();
@@ -30,7 +30,7 @@ public class ElementIterator implements Iterator<Element> {
@Override @Override
public Element next() { public Element next() {
if(next == null) throw new NoSuchElementException(); if(next == null) throw new NoSuchElementException();
Element result = next; final Element result = next;
next = getNext(); next = getNext();
return result; return result;
} }
@@ -38,7 +38,7 @@ public class ElementIterator implements Iterator<Element> {
private Element getNext() { private Element getNext() {
Element result = null; Element result = null;
while(it.hasNext()) { while(it.hasNext()) {
Node node = it.next(); final Node node = it.next();
if(node instanceof Element && (name == null || Objects.equals(name, ((Element) node).getTagName()))) { if(node instanceof Element && (name == null || Objects.equals(name, ((Element) node).getTagName()))) {
result = (Element) node; result = (Element) node;
break; break;

View File

@@ -6,11 +6,11 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
public interface XMLNodeVisitor { public interface XMLNodeVisitor {
default NodeVisitResultPre visitNodePre(List<Node> stack) { default NodeVisitResultPre visitNodePre(final List<Node> stack) {
return NodeVisitResultPre.CONTINUE; return NodeVisitResultPre.CONTINUE;
} }
default NodeVisitResultPost visitNodePost(List<Node> stack) { default NodeVisitResultPost visitNodePost(final List<Node> stack) {
return NodeVisitResultPost.CONTINUE; return NodeVisitResultPost.CONTINUE;
} }
@@ -22,23 +22,23 @@ public interface XMLNodeVisitor {
CONTINUE, END_TRAVERSAL CONTINUE, END_TRAVERSAL
} }
static boolean stackMatches(List<Node> nodes, String... names) { static boolean stackMatches(final List<Node> nodes, final String... names) {
return stackMatches(nodes, false, names); return stackMatches(nodes, false, names);
} }
static boolean stackSame(List<Node> nodes, String... names) { static boolean stackSame(final List<Node> nodes, final String... names) {
return stackMatches(nodes, true, names); return stackMatches(nodes, true, names);
} }
static boolean stackMatches(List<Node> nodes, boolean strict, String... names) { static boolean stackMatches(final List<Node> nodes, final boolean strict, final String... names) {
if(nodes.size() < names.length) return false; if(nodes.size() < names.length) return false;
int nameIndex = 0; int nameIndex = 0;
int nodeIndex = 0; int nodeIndex = 0;
while(nameIndex < names.length) { while(nameIndex < names.length) {
if(nodeIndex >= nodes.size()) return false; if(nodeIndex >= nodes.size()) return false;
Node node = nodes.get(nodeIndex++); final Node node = nodes.get(nodeIndex++);
if(!strict && node.getNodeType() != Node.ELEMENT_NODE) continue; if(!strict && node.getNodeType() != Node.ELEMENT_NODE) continue;
String name = names[nameIndex++]; final String name = names[nameIndex++];
if(name != null && if(name != null &&
node.getNodeType() == Node.ELEMENT_NODE && node.getNodeType() == Node.ELEMENT_NODE &&
!Objects.equals(name, node.getNodeName())) return false; !Objects.equals(name, node.getNodeName())) return false;

View File

@@ -19,51 +19,51 @@ import java.util.stream.StreamSupport;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Xml { public class Xml {
public static Iterator<Node> iterator(NodeList node) { public static Iterator<Node> iterator(final NodeList node) {
return new NodeListIterator(node); return new NodeListIterator(node);
} }
public static Iterator<Element> iterator(Element element, String tagName) { public static Iterator<Element> iterator(final Element element, final String tagName) {
return new ElementIterator(element, tagName); return new ElementIterator(element, tagName);
} }
public static Iterator<Element> iterator(Element element) { public static Iterator<Element> iterator(final Element element) {
return new ElementIterator(element); return new ElementIterator(element);
} }
public static Spliterator<Node> spliterator(NodeList node) { public static Spliterator<Node> spliterator(final NodeList node) {
return Spliterators.spliteratorUnknownSize(iterator(node), 0); return Spliterators.spliteratorUnknownSize(iterator(node), 0);
} }
public static Spliterator<Element> spliterator(Element element) { public static Spliterator<Element> spliterator(final Element element) {
return Spliterators.spliteratorUnknownSize(iterator(element), 0); return Spliterators.spliteratorUnknownSize(iterator(element), 0);
} }
public static Stream<Node> stream(NodeList node) { public static Stream<Node> stream(final NodeList node) {
return StreamSupport.stream(spliterator(node), false); return StreamSupport.stream(spliterator(node), false);
} }
public static Stream<Element> stream(Element element) { public static Stream<Element> stream(final Element element) {
return StreamSupport.stream(spliterator(element), false); return StreamSupport.stream(spliterator(element), false);
} }
public static Iterable<Node> iterable(NodeList node) { public static Iterable<Node> iterable(final NodeList node) {
return () -> iterator(node); return () -> iterator(node);
} }
public static Iterable<Element> iterable(Element element, String tagName) { public static Iterable<Element> iterable(final Element element, final String tagName) {
return () -> iterator(element, tagName); return () -> iterator(element, tagName);
} }
public static Iterable<Element> iterable(Element element) { public static Iterable<Element> iterable(final Element element) {
return () -> iterator(element); return () -> iterator(element);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T withChild(Node node, Fun<Node, T> callback, String... path) { public static <T> T withChild(final Node node, final Fun<Node, T> callback, String... path) {
Object[] result = new Object[1]; Object[] result = new Object[1];
XMLNodeVisitor visitor = new XMLNodeVisitor() { XMLNodeVisitor visitor = new XMLNodeVisitor() {
@Override @Override
public NodeVisitResultPre visitNodePre(List<Node> stack) { public NodeVisitResultPre visitNodePre(final List<Node> stack) {
if (XMLNodeVisitor.stackMatches(stack, path)) { if (XMLNodeVisitor.stackMatches(stack, path)) {
result[0] = callback.apply(JWO.tail(stack)); result[0] = callback.apply(JWO.tail(stack));
return NodeVisitResultPre.END_TRAVERSAL; return NodeVisitResultPre.END_TRAVERSAL;
@@ -77,14 +77,14 @@ public class Xml {
return (T) result[0]; return (T) result[0];
} }
public static void withChild(Element element, String tagName, Con<Element> callback) { public static void withChild(final Element element, final String tagName, final Con<Element> callback) {
for (Element el : iterable(element, tagName)) { for (final Element el : iterable(element, tagName)) {
callback.accept(el); callback.accept(el);
} }
} }
public static void withChild(Element element, Con<Element> callback) { public static void withChild(final Element element, final Con<Element> callback) {
for (Element el : iterable(element)) { for (final Element el : iterable(element)) {
callback.accept(el); callback.accept(el);
} }
} }

View File

@@ -15,17 +15,17 @@ public class CircularBufferTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void test() { public void test() {
MessageDigest streamDigest = MessageDigest.getInstance("MD5"), outputDigest = MessageDigest.getInstance("MD5"); final MessageDigest streamDigest = MessageDigest.getInstance("MD5"), outputDigest = MessageDigest.getInstance("MD5");
InputStream is = new DigestInputStream(getClass().getResourceAsStream("/render_template_test.txt"), streamDigest); final InputStream is = new DigestInputStream(getClass().getResourceAsStream("/render_template_test.txt"), streamDigest);
CircularBuffer cb = new CircularBuffer(new InputStreamReader(is), 32); final CircularBuffer cb = new CircularBuffer(new InputStreamReader(is), 32);
Random rand = new Random(); final Random rand = new Random();
while (true) { while (true) {
int b = cb.next(); final int b = cb.next();
if (b < 0) break; if (b < 0) break;
if (rand.nextInt() % 2 == 0) { if (rand.nextInt() % 2 == 0) {
cb.prev(); cb.prev();
} else { } else {
char c = (char) b; final char c = (char) b;
outputDigest.update((byte) b); outputDigest.update((byte) b);
} }
} }

View File

@@ -35,7 +35,7 @@ public class ExtractorInputStreamTest {
private Path testExtractionDestination; private Path testExtractionDestination;
@BeforeEach @BeforeEach
void setup(@TempDir Path testDir) { void setup(final @TempDir Path testDir) {
testJar = Paths.get(System.getProperty("junit.jupiter.engine.jar")); testJar = Paths.get(System.getProperty("junit.jupiter.engine.jar"));
referenceExtractionDestination = testDir.resolve("referenceExtraction"); referenceExtractionDestination = testDir.resolve("referenceExtraction");
testExtractionDestination = testDir.resolve("testExtraction"); testExtractionDestination = testDir.resolve("testExtraction");
@@ -44,14 +44,14 @@ public class ExtractorInputStreamTest {
@SneakyThrows @SneakyThrows
private static void referenceUnzipMethod(Path source, Path destination) { private static void referenceUnzipMethod(Path source, Path destination) {
try(FileSystem fs = FileSystems.newFileSystem(source, (ClassLoader) null)) { try(final FileSystem fs = FileSystems.newFileSystem(source, (ClassLoader) null)) {
for(Path root : fs.getRootDirectories()) { for(final Path root : fs.getRootDirectories()) {
Files.walk(root) Files.walk(root)
.filter(it -> !Files.isDirectory(it)).forEach(new Consumer<Path>() { .filter(it -> !Files.isDirectory(it)).forEach(new Consumer<Path>() {
@Override @Override
@SneakyThrows @SneakyThrows
public void accept(Path path) { public void accept(final Path path) {
Path newDir = destination.resolve(root.relativize(path).toString()); final Path newDir = destination.resolve(root.relativize(path).toString());
Files.createDirectories(newDir.getParent()); Files.createDirectories(newDir.getParent());
Files.copy(path, newDir); Files.copy(path, newDir);
} }
@@ -62,22 +62,22 @@ public class ExtractorInputStreamTest {
@SneakyThrows @SneakyThrows
private static NavigableMap<String, Hash> hashFileTree(Path tree) { private static NavigableMap<String, Hash> hashFileTree(Path tree) {
NavigableMap<String, Hash> result = new TreeMap<>(); final NavigableMap<String, Hash> result = new TreeMap<>();
byte[] buffer = new byte[0x1000]; final byte[] buffer = new byte[0x1000];
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { final FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
String key = tree.relativize(file).toString(); final String key = tree.relativize(file).toString();
if(!Objects.equals(JarFile.MANIFEST_NAME, key)) { if(!Objects.equals(JarFile.MANIFEST_NAME, key)) {
try (InputStream is = Files.newInputStream(file)) { try (InputStream is = Files.newInputStream(file)) {
result.put(key, Hash.md5(is, buffer)); result.put(key, Hash.md5(is, buffer));
} }
} else { } else {
Manifest manifest = new Manifest(); final Manifest manifest = new Manifest();
try (InputStream is = Files.newInputStream(file)) { try (final InputStream is = Files.newInputStream(file)) {
manifest.read(is); manifest.read(is);
} }
ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { try {
manifest.write(baos); manifest.write(baos);
} finally { } finally {
@@ -92,18 +92,18 @@ public class ExtractorInputStreamTest {
return result; return result;
} }
private static boolean compareFileTree(Path tree1, Path tree2) { private static boolean compareFileTree(final Path tree1, final Path tree2) {
NavigableMap<String, Hash> hash1 = hashFileTree(tree1); final NavigableMap<String, Hash> hash1 = hashFileTree(tree1);
NavigableMap<String, Hash> hash2 = hashFileTree(tree2); final NavigableMap<String, Hash> hash2 = hashFileTree(tree2);
return Objects.equals(hash1, hash2); return Objects.equals(hash1, hash2);
} }
@SneakyThrows @SneakyThrows
public void run(Supplier<ZipInputStream> zipInputStreamSupplier) { public void run(final Supplier<ZipInputStream> zipInputStreamSupplier) {
referenceUnzipMethod(testJar, referenceExtractionDestination); referenceUnzipMethod(testJar, referenceExtractionDestination);
try(ZipInputStream zipInputStream = zipInputStreamSupplier.get()) { try(final ZipInputStream zipInputStream = zipInputStreamSupplier.get()) {
while(true) { while(true) {
ZipEntry zipEntry = zipInputStream.getNextEntry(); final ZipEntry zipEntry = zipInputStream.getNextEntry();
if(zipEntry == null) break; if(zipEntry == null) break;
JWO.write2Stream(new NullOutputStream(), zipInputStream); JWO.write2Stream(new NullOutputStream(), zipInputStream);
zipInputStream.closeEntry(); zipInputStream.closeEntry();
@@ -115,7 +115,7 @@ public class ExtractorInputStreamTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void zipExtractorInputStreamTest() { public void zipExtractorInputStreamTest() {
Supplier<ZipInputStream> supplier = new Supplier<ZipInputStream>() { final Supplier<ZipInputStream> supplier = new Supplier<ZipInputStream>() {
@Override @Override
@SneakyThrows @SneakyThrows
public ZipInputStream get() { public ZipInputStream get() {
@@ -128,7 +128,7 @@ public class ExtractorInputStreamTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void jarExtractorInputStreamTest() { public void jarExtractorInputStreamTest() {
Supplier<ZipInputStream> supplier = new Supplier<ZipInputStream>() { final Supplier<ZipInputStream> supplier = new Supplier<ZipInputStream>() {
@Override @Override
@SneakyThrows @SneakyThrows
public ZipInputStream get() { public ZipInputStream get() {

View File

@@ -20,15 +20,15 @@ public class HashTest {
@BeforeEach @BeforeEach
public void setup() { public void setup() {
sample = new byte[0x400]; sample = new byte[0x400];
Random random = new Random(0xdeadbeef); final Random random = new Random(0xdeadbeef);
random.nextBytes(sample); random.nextBytes(sample);
} }
@Test @Test
public void checkHashIsRepeatableAndComparesCorrectly() { public void checkHashIsRepeatableAndComparesCorrectly() {
byte[] buffer = new byte[0x1000]; final byte[] buffer = new byte[0x1000];
Hash hash1 = Hash.md5(new ByteArrayInputStream(sample), buffer); final Hash hash1 = Hash.md5(new ByteArrayInputStream(sample), buffer);
Hash hash2 = Hash.md5(new ByteArrayInputStream(sample), buffer); final Hash hash2 = Hash.md5(new ByteArrayInputStream(sample), buffer);
Assertions.assertEquals(hash1.hashCode(), hash2.hashCode()); Assertions.assertEquals(hash1.hashCode(), hash2.hashCode());
Assertions.assertEquals(hash1, hash2); Assertions.assertEquals(hash1, hash2);
Assertions.assertEquals(hash1.toString(), hash2.toString()); Assertions.assertEquals(hash1.toString(), hash2.toString());
@@ -36,14 +36,14 @@ public class HashTest {
@Test @Test
public void checkReversingTheSampleGivesDifferentHash() { public void checkReversingTheSampleGivesDifferentHash() {
byte[] reverseSample = new byte[sample.length]; final byte[] reverseSample = new byte[sample.length];
for(int i = 0; i < sample.length; i++) { for(int i = 0; i < sample.length; i++) {
reverseSample[reverseSample.length - i - 1] = sample[i]; reverseSample[reverseSample.length - i - 1] = sample[i];
} }
byte[] buffer = new byte[0x1000]; final byte[] buffer = new byte[0x1000];
Hash hash1 = Hash.md5(new ByteArrayInputStream(sample), buffer); final Hash hash1 = Hash.md5(new ByteArrayInputStream(sample), buffer);
Hash hash2 = Hash.md5(new ByteArrayInputStream(reverseSample), buffer); final Hash hash2 = Hash.md5(new ByteArrayInputStream(reverseSample), buffer);
Assertions.assertNotEquals(hash1.hashCode(), hash2.hashCode()); Assertions.assertNotEquals(hash1.hashCode(), hash2.hashCode());
Assertions.assertNotEquals(hash1, hash2); Assertions.assertNotEquals(hash1, hash2);
Assertions.assertNotEquals(hash1.toString(), hash2.toString()); Assertions.assertNotEquals(hash1.toString(), hash2.toString());
@@ -53,7 +53,7 @@ public class HashTest {
private static class HexTestArguments implements ArgumentsProvider { private static class HexTestArguments implements ArgumentsProvider {
@Override @Override
public Stream<? extends Arguments> provideArguments( public Stream<? extends Arguments> provideArguments(
ExtensionContext extensionContext final ExtensionContext extensionContext
) { ) {
return Stream.of( return Stream.of(
Arguments.of("A41D767EEF6084823F250E954BDD48CF", null), Arguments.of("A41D767EEF6084823F250E954BDD48CF", null),
@@ -68,13 +68,13 @@ public class HashTest {
@ArgumentsSource(HexTestArguments.class) @ArgumentsSource(HexTestArguments.class)
@ParameterizedTest @ParameterizedTest
public void hexTest(String sourceString, Class<? extends Throwable> t) { public void hexTest(final String sourceString, final Class<? extends Throwable> t) {
if(t != null) { if(t != null) {
Assertions.assertThrows(t, () -> Assertions.assertThrows(t, () ->
Hash.hexToBytes(sourceString) Hash.hexToBytes(sourceString)
); );
} else { } else {
byte[] bytes = Hash.hexToBytes(sourceString); final byte[] bytes = Hash.hexToBytes(sourceString);
Assertions.assertEquals(sourceString.length() / 2, bytes.length); Assertions.assertEquals(sourceString.length() / 2, bytes.length);
Assertions.assertEquals(sourceString.toUpperCase(), Hash.bytesToHex(bytes)); Assertions.assertEquals(sourceString.toUpperCase(), Hash.bytesToHex(bytes));
} }
@@ -82,13 +82,13 @@ public class HashTest {
@ArgumentsSource(HexTestArguments.class) @ArgumentsSource(HexTestArguments.class)
@ParameterizedTest @ParameterizedTest
public void hexTest2(String sourceString, Class<? extends Throwable> t) { public void hexTest2(final String sourceString, final Class<? extends Throwable> t) {
if(t != null) { if(t != null) {
Assertions.assertThrows(t, () -> Assertions.assertThrows(t, () ->
Hash.hexToBytes2(sourceString) Hash.hexToBytes2(sourceString)
); );
} else { } else {
byte[] bytes = Hash.hexToBytes2(sourceString); final byte[] bytes = Hash.hexToBytes2(sourceString);
Assertions.assertEquals(sourceString.length() / 2, bytes.length); Assertions.assertEquals(sourceString.length() / 2, bytes.length);
Assertions.assertEquals(sourceString.toUpperCase(), Hash.bytesToHex(bytes)); Assertions.assertEquals(sourceString.toUpperCase(), Hash.bytesToHex(bytes));
} }

View File

@@ -67,8 +67,8 @@ public class JWOTest {
@Test @Test
public void flatMapTest() { public void flatMapTest() {
Stream<Integer> s = Stream.of(3, 4); final Stream<Integer> s = Stream.of(3, 4);
List<Integer> l = JWO.flatMap(s, (n) -> { final List<Integer> l = JWO.flatMap(s, (n) -> {
if (n > 3) return Optional.of(n); if (n > 3) return Optional.of(n);
else return Optional.empty(); else return Optional.empty();
}).collect(Collectors.toList()); }).collect(Collectors.toList());
@@ -77,7 +77,7 @@ public class JWOTest {
@Test @Test
public void optional2StreamTest() { public void optional2StreamTest() {
Integer integer = 3; final Integer integer = 3;
Optional<Integer> s = Optional.of(integer); Optional<Integer> s = Optional.of(integer);
JWO.optional2Stream(s).forEach(n -> assertEquals(integer, n)); JWO.optional2Stream(s).forEach(n -> assertEquals(integer, n));
s = Optional.empty(); s = Optional.empty();
@@ -88,10 +88,10 @@ public class JWOTest {
@Test @Test
public void optional2StreamTest2() { public void optional2StreamTest2() {
Integer integer = 3; final Integer integer = 3;
Optional<Integer> o1 = Optional.of(integer); final Optional<Integer> o1 = Optional.of(integer);
Integer integer2 = 3; final Integer integer2 = 3;
Optional<Integer> o2 = Optional.of(integer2); final Optional<Integer> o2 = Optional.of(integer2);
final var values = JWO.optional2Stream(o1, Optional.empty(), o2) final var values = JWO.optional2Stream(o1, Optional.empty(), o2)
.collect(Collectors.toList()); .collect(Collectors.toList());
assertEquals(Arrays.asList(integer, integer2), values); assertEquals(Arrays.asList(integer, integer2), values);
@@ -99,9 +99,9 @@ public class JWOTest {
@Test @Test
public void optionalOrTest() { public void optionalOrTest() {
Integer integer = 3; final Integer integer = 3;
Optional<Integer> o1 = Optional.of(integer); final Optional<Integer> o1 = Optional.of(integer);
Optional<Integer> o2 = Optional.of(integer); final Optional<Integer> o2 = Optional.of(integer);
assertEquals(o2, JWO.or(Optional.empty(), o2)); assertEquals(o2, JWO.or(Optional.empty(), o2));
assertEquals(o1, JWO.or(o1, Optional.empty())); assertEquals(o1, JWO.or(o1, Optional.empty()));
assertEquals(Optional.empty(), JWO.or(Optional.empty(), Optional.empty())); assertEquals(Optional.empty(), JWO.or(Optional.empty(), Optional.empty()));
@@ -133,9 +133,9 @@ public class JWOTest {
@ParameterizedTest @ParameterizedTest
@EnumSource(IndexOfWithEscapeTestCase.class) @EnumSource(IndexOfWithEscapeTestCase.class)
public void testIndexOfWithEscape(IndexOfWithEscapeTestCase testCase) { public void testIndexOfWithEscape(final IndexOfWithEscapeTestCase testCase) {
String haystack = testCase.haystack; final String haystack = testCase.haystack;
List<Integer> solution = newArrayList(); final List<Integer> solution = newArrayList();
int i = 0; int i = 0;
while (true) { while (true) {
i = JWO.indexOfWithEscape(haystack, testCase.needle, testCase.escape, i, haystack.length()); i = JWO.indexOfWithEscape(haystack, testCase.needle, testCase.escape, i, haystack.length());
@@ -149,18 +149,18 @@ public class JWOTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void testRenderTemplate() { public void testRenderTemplate() {
Map<String, Object> valuesMap = new HashMap<>(); final Map<String, Object> valuesMap = new HashMap<>();
valuesMap.put("author", "John Doe"); valuesMap.put("author", "John Doe");
valuesMap.put("date", "2020-03-25 16:22"); valuesMap.put("date", "2020-03-25 16:22");
valuesMap.put("adjective", "simple"); valuesMap.put("adjective", "simple");
String expected = """ final String expected = """
This is a simple test made by John Doe on 2020-03-25 16:22. It's really simple! This is a simple test made by John Doe on 2020-03-25 16:22. It's really simple!
/home/user /home/user
/home/user /home/user
defaultValue defaultValue
;=%x$!~L+LJr?50l.^{veaS'zLHo=!}wT ;=%x$!~L+LJr?50l.^{veaS'zLHo=!}wT
"""; """;
Map<String, Map<String, Object>> contextMap = new MapBuilder<String, Map<String, Object>>() final Map<String, Map<String, Object>> contextMap = new MapBuilder<String, Map<String, Object>>()
.entry("env", .entry("env",
new MapBuilder<String, String>() new MapBuilder<String, String>()
.entry("HOME", "/home/user") .entry("HOME", "/home/user")
@@ -171,39 +171,39 @@ public class JWOTest {
.entry("user.home", "/home/user") .entry("user.home", "/home/user")
.build(TreeMap::new, Collections::unmodifiableMap) .build(TreeMap::new, Collections::unmodifiableMap)
).build(TreeMap::new, Collections::unmodifiableMap); ).build(TreeMap::new, Collections::unmodifiableMap);
try (Reader reader = new InputStreamReader( try (final Reader reader = new InputStreamReader(
JWOTest.class.getResourceAsStream("/render_template_test.txt"))) { JWOTest.class.getResourceAsStream("/render_template_test.txt"))) {
String rendered = JWO.renderTemplate(reader, valuesMap, contextMap); final String rendered = JWO.renderTemplate(reader, valuesMap, contextMap);
assertEquals(expected, rendered); assertEquals(expected, rendered);
} }
try (Reader reader = new InputStreamReader( try (final Reader reader = new InputStreamReader(
JWOTest.class.getResourceAsStream("/render_template_test.txt"))) { JWOTest.class.getResourceAsStream("/render_template_test.txt"))) {
String rendered = JWO.renderTemplate(JWO.readAll(reader), valuesMap, contextMap); final String rendered = JWO.renderTemplate(JWO.readAll(reader), valuesMap, contextMap);
assertEquals(expected, rendered); assertEquals(expected, rendered);
} }
} }
public static String renderTemplateNaive(String template, Map<String, Object> valuesMap) { public static String renderTemplateNaive(final String template, final Map<String, Object> valuesMap) {
StringBuilder formatter = new StringBuilder(template); final StringBuilder formatter = new StringBuilder(template);
Object absent = new Object(); final Object absent = new Object();
Matcher matcher = Pattern.compile("\\$\\{(\\w+)}").matcher(template); final Matcher matcher = Pattern.compile("\\$\\{(\\w+)}").matcher(template);
while (matcher.find()) { while (matcher.find()) {
String key = matcher.group(1); final String key = matcher.group(1);
String formatKey = String.format("${%s}", key); final String formatKey = String.format("${%s}", key);
int index = formatter.indexOf(formatKey); final int index = formatter.indexOf(formatKey);
// If the key is present: // If the key is present:
// - If the value is not null, then replace the variable for the value // - If the value is not null, then replace the variable for the value
// - If the value is null, replace the variable for empty string // - If the value is null, replace the variable for empty string
// If the key is not present, leave the variable untouched. // If the key is not present, leave the variable untouched.
if (index != -1) { if (index != -1) {
Object value = valuesMap.getOrDefault(key, absent); final Object value = valuesMap.getOrDefault(key, absent);
if (value != absent) { if (value != absent) {
String valueStr = value != null ? value.toString() : ""; final String valueStr = value != null ? value.toString() : "";
formatter.replace(index, index + formatKey.length(), valueStr); formatter.replace(index, index + formatKey.length(), valueStr);
} }
} }
@@ -214,14 +214,14 @@ public class JWOTest {
@Test @Test
@SneakyThrows @SneakyThrows
@EnabledOnOs(OS.LINUX) @EnabledOnOs(OS.LINUX)
public void uidTest(@TempDir Path testDir) { public void uidTest(final @TempDir Path testDir) {
PosixFileAttributes pfa = Files.readAttributes(testDir, PosixFileAttributes.class); final PosixFileAttributes pfa = Files.readAttributes(testDir, PosixFileAttributes.class);
UserPrincipal expectedUser = pfa.owner(); final UserPrincipal expectedUser = pfa.owner();
Class<? extends UserPrincipal> userClass = expectedUser.getClass(); final Class<? extends UserPrincipal> userClass = expectedUser.getClass();
Method m = userClass.getDeclaredMethod("uid"); final Method m = userClass.getDeclaredMethod("uid");
m.setAccessible(true); m.setAccessible(true);
int expectedUserId = (Integer) m.invoke(expectedUser); final int expectedUserId = (Integer) m.invoke(expectedUser);
int uid = (int) JWO.uid(); final int uid = (int) JWO.uid();
assertEquals(expectedUserId, uid); assertEquals(expectedUserId, uid);
} }
@@ -230,9 +230,9 @@ public class JWOTest {
private interface CommonInterface { private interface CommonInterface {
void replaceFileIfDifferent( void replaceFileIfDifferent(
Supplier<InputStream> inputStreamSupplier, final Supplier<InputStream> inputStreamSupplier,
Path destination, final Path destination,
FileAttribute<?>... attrs final FileAttribute<?>... attrs
); );
} }
@@ -249,9 +249,9 @@ public class JWOTest {
private final CommonInterface xface; private final CommonInterface xface;
public void replaceFileIfDifferent( public void replaceFileIfDifferent(
Supplier<InputStream> inputStreamSupplier, final Supplier<InputStream> inputStreamSupplier,
Path destination, final Path destination,
FileAttribute<?>... attrs final FileAttribute<?>... attrs
) { ) {
xface.replaceFileIfDifferent(inputStreamSupplier, destination, attrs); xface.replaceFileIfDifferent(inputStreamSupplier, destination, attrs);
} }
@@ -267,10 +267,10 @@ public class JWOTest {
@SneakyThrows @SneakyThrows
@ParameterizedTest @ParameterizedTest
@EnumSource(MethodToTest.class) @EnumSource(MethodToTest.class)
public void ensureFileCopy(MethodToTest methodToTest) { public void ensureFileCopy(final MethodToTest methodToTest) {
final var dest = testDir.resolve("cracklib-small"); final var dest = testDir.resolve("cracklib-small");
methodToTest.replaceFileIfDifferent(source, dest); methodToTest.replaceFileIfDifferent(source, dest);
Hash newFileHash, newContentHash; final Hash newFileHash, newContentHash;
try (final var inputStream = source.get()) { try (final var inputStream = source.get()) {
newContentHash = Hash.md5(inputStream); newContentHash = Hash.md5(inputStream);
} }
@@ -283,7 +283,7 @@ public class JWOTest {
@SneakyThrows @SneakyThrows
@ParameterizedTest @ParameterizedTest
@EnumSource(MethodToTest.class) @EnumSource(MethodToTest.class)
public void ensureNoWriteWithNoChange(MethodToTest methodToTest) { public void ensureNoWriteWithNoChange(final MethodToTest methodToTest) {
final var dest = testDir.resolve("cracklib-small"); final var dest = testDir.resolve("cracklib-small");
try (final var inputStream = source.get()) { try (final var inputStream = source.get()) {
Files.copy(inputStream, dest); Files.copy(inputStream, dest);
@@ -297,7 +297,7 @@ public class JWOTest {
@SneakyThrows @SneakyThrows
@ParameterizedTest @ParameterizedTest
@EnumSource(MethodToTest.class) @EnumSource(MethodToTest.class)
public void ensureWriteWithContentChange(MethodToTest methodToTest) { public void ensureWriteWithContentChange(final MethodToTest methodToTest) {
final var dest = testDir.resolve("cracklib-small"); final var dest = testDir.resolve("cracklib-small");
try (final var inputStream = source.get()) { try (final var inputStream = source.get()) {
Files.copy(inputStream, dest); Files.copy(inputStream, dest);
@@ -338,7 +338,7 @@ public class JWOTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("testCases") @MethodSource("testCases")
public void capitalizeTest(TestCase<String, String> testCase) { public void capitalizeTest(final TestCase<String, String> testCase) {
if (testCase.error() == null) { if (testCase.error() == null) {
assertEquals(testCase.expectedOutput(), JWO.capitalize(testCase.input())); assertEquals(testCase.expectedOutput(), JWO.capitalize(testCase.input()));
} else { } else {
@@ -370,7 +370,7 @@ public class JWOTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("testCases") @MethodSource("testCases")
public void decapitalizeTest(TestCase<String, String> testCase) { public void decapitalizeTest(final TestCase<String, String> testCase) {
if (testCase.error() == null) { if (testCase.error() == null) {
assertEquals(testCase.expectedOutput(), JWO.decapitalize(testCase.input())); assertEquals(testCase.expectedOutput(), JWO.decapitalize(testCase.input()));
} else { } else {
@@ -418,10 +418,10 @@ public class JWOTest {
@MethodSource @MethodSource
@ParameterizedTest @ParameterizedTest
public void test(TestCase<Integer[], Void> testCase) { public void test(final TestCase<Integer[], Void> testCase) {
final var it = JWO.iterator(testCase.input()); final var it = JWO.iterator(testCase.input());
for (Integer n : testCase.input()) { for (final Integer n : testCase.input()) {
final var m = it.next(); final var m = it.next();
assertEquals(n, m); assertEquals(n, m);
} }
@@ -432,7 +432,7 @@ public class JWOTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void copyTest() { public void copyTest() {
MessageDigest md1 = Hash.Algorithm.MD5.newMessageDigest(); final MessageDigest md1 = Hash.Algorithm.MD5.newMessageDigest();
final Supplier<Reader> source = JWO.compose( final Supplier<Reader> source = JWO.compose(
JWO.compose( JWO.compose(
() -> getClass().getResourceAsStream(CRACKLIB_RESOURCE), () -> getClass().getResourceAsStream(CRACKLIB_RESOURCE),
@@ -440,7 +440,7 @@ public class JWOTest {
), ),
(InputStream is) -> new InputStreamReader(is) (InputStream is) -> new InputStreamReader(is)
); );
MessageDigest md2 = Hash.Algorithm.MD5.newMessageDigest(); final MessageDigest md2 = Hash.Algorithm.MD5.newMessageDigest();
final Supplier<Writer> destination = JWO.compose( final Supplier<Writer> destination = JWO.compose(
JWO.compose( JWO.compose(
NullOutputStream::new, NullOutputStream::new,
@@ -450,7 +450,7 @@ public class JWOTest {
); );
try (final var reader = source.get()) { try (final var reader = source.get()) {
try (Writer writer = destination.get()) { try (final Writer writer = destination.get()) {
JWO.copy(reader, writer); JWO.copy(reader, writer);
} }
} }
@@ -497,12 +497,12 @@ public class JWOTest {
JWO.extractZip(reassembledBundle, destination3); JWO.extractZip(reassembledBundle, destination3);
final var visitor = new FileVisitor<Path>() { final var visitor = new FileVisitor<Path>() {
@Override @Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) {
final var relativePath = destination1.relativize(file); final var relativePath = destination1.relativize(file);
final var hashes = Stream.of( final var hashes = Stream.of(
destination1.resolve(relativePath), destination1.resolve(relativePath),
@@ -520,12 +520,12 @@ public class JWOTest {
} }
@Override @Override
public FileVisitResult visitFileFailed(Path file, IOException exc) { public FileVisitResult visitFileFailed(final Path file, final IOException exc) {
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
@Override @Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) { public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) {
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
}; };
@@ -560,11 +560,11 @@ public class JWOTest {
super(); super();
} }
public SomeWeirdException(String msg) { public SomeWeirdException(final String msg) {
super(msg); super(msg);
} }
public SomeWeirdException(String msg, Throwable cause) { public SomeWeirdException(final String msg, final Throwable cause) {
super(msg, cause); super(msg, cause);
} }
} }
@@ -634,7 +634,7 @@ public class JWOTest {
"some message with placeholder %d", "some message with placeholder %d",
25 25
); );
} catch (Throwable t) { } catch (final Throwable t) {
assertTrue(t.getCause() == cause); assertTrue(t.getCause() == cause);
throw t; throw t;
} }
@@ -653,7 +653,7 @@ public class JWOTest {
@Test @Test
@SneakyThrows @SneakyThrows
public void readFile(@TempDir Path testDir) { public void readFile(final @TempDir Path testDir) {
final var destination = testDir.resolve("cracklib-small"); final var destination = testDir.resolve("cracklib-small");
final var dis = Hash.Algorithm.MD5.newInputStream(getClass().getResourceAsStream(CRACKLIB_RESOURCE)); final var dis = Hash.Algorithm.MD5.newInputStream(getClass().getResourceAsStream(CRACKLIB_RESOURCE));
final var md = dis.getMessageDigest(); final var md = dis.getMessageDigest();

View File

@@ -64,7 +64,7 @@ public class JavaVersionTest {
@MethodSource @MethodSource
@ParameterizedTest @ParameterizedTest
public void comparatorTest(TestCase<Tuple2<JavaVersion, JavaVersion>, Integer> testCase) { public void comparatorTest(final TestCase<Tuple2<JavaVersion, JavaVersion>, Integer> testCase) {
final var comparator = Comparator.<JavaVersion>naturalOrder(); final var comparator = Comparator.<JavaVersion>naturalOrder();
final var pair = testCase.input(); final var pair = testCase.input();
final var comparisonResult = Optional.of(comparator.compare(pair.get_1(), pair.get_2())) final var comparisonResult = Optional.of(comparator.compare(pair.get_1(), pair.get_2()))

View File

@@ -13,48 +13,48 @@ public class Leb128Test {
@Test @Test
public void testLong() { public void testLong() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<Long> numbers = Arrays.asList(0L, 1L, -3L, 5L, 7L, 8L, 125L, 255L, 10325L, -2000L, 1024L * 1024L * 1024L * 12L); final List<Long> numbers = Arrays.asList(0L, 1L, -3L, 5L, 7L, 8L, 125L, 255L, 10325L, -2000L, 1024L * 1024L * 1024L * 12L);
numbers.forEach(n -> Leb128.encode(baos, n)); numbers.forEach(n -> Leb128.encode(baos, n));
byte[] bytes = baos.toByteArray(); final byte[] bytes = baos.toByteArray();
Leb128.Leb128Decoder decoder = new Leb128.Leb128Decoder(new ByteArrayInputStream(bytes)); final Leb128.Leb128Decoder decoder = new Leb128.Leb128Decoder(new ByteArrayInputStream(bytes));
numbers.forEach(n -> Assertions.assertEquals((long) n, decoder.decode())); numbers.forEach(n -> Assertions.assertEquals((long) n, decoder.decode()));
} }
@Test @Test
public void testDouble() { public void testDouble() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<Double> numbers = Arrays.asList( final List<Double> numbers = Arrays.asList(
0.0, 1.5, -3.0, 0.5, 2.5, 8.25, -125.0, 255.0, 10325.0, -2000.0, 1024.0 * 1024 * 1024 * 12, 0.0, 1.5, -3.0, 0.5, 2.5, 8.25, -125.0, 255.0, 10325.0, -2000.0, 1024.0 * 1024 * 1024 * 12,
-122.42200352825247, 37.80848009696725); -122.42200352825247, 37.80848009696725);
numbers.forEach(n -> Leb128.encode(baos, n)); numbers.forEach(n -> Leb128.encode(baos, n));
byte[] bytes = baos.toByteArray(); final byte[] bytes = baos.toByteArray();
Leb128.Leb128Decoder decoder = new Leb128.Leb128Decoder(new ByteArrayInputStream(bytes)); final Leb128.Leb128Decoder decoder = new Leb128.Leb128Decoder(new ByteArrayInputStream(bytes));
numbers.forEach(n -> Assertions.assertEquals(n, decoder.decodeDouble(), 0.0)); numbers.forEach(n -> Assertions.assertEquals(n, decoder.decodeDouble(), 0.0));
} }
@Test @Test
public void reverseTest() { public void reverseTest() {
long n = 101325; final long n = 101325;
Assertions.assertEquals(n, Leb128.reverse(Leb128.reverse(n))); Assertions.assertEquals(n, Leb128.reverse(Leb128.reverse(n)));
} }
@Test @Test
@SneakyThrows @SneakyThrows
public void reverseTestDouble() { public void reverseTestDouble() {
double n = 0.25; final double n = 0.25;
long doubleLong = Double.doubleToLongBits(n); final long doubleLong = Double.doubleToLongBits(n);
long reverse = Leb128.reverse(doubleLong); final long reverse = Leb128.reverse(doubleLong);
try(ByteArrayOutputStream os = new ByteArrayOutputStream()) { try(final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Leb128.encode(os, reverse); Leb128.encode(os, reverse);
byte[] bytes = os.toByteArray(); final byte[] bytes = os.toByteArray();
Assertions.assertEquals(3, bytes.length); Assertions.assertEquals(3, bytes.length);
} }
} }

View File

@@ -13,7 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
public class LexicographicIterableComparatorTest { public class LexicographicIterableComparatorTest {
private final static Comparator<Integer> DESCENDING_INTEGER_COMPARATOR = new Comparator<Integer>() { private final static Comparator<Integer> DESCENDING_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) { public int compare(final Integer o1, final Integer o2) {
return -o1.compareTo(o2); return -o1.compareTo(o2);
} }
}; };

View File

@@ -30,10 +30,10 @@ class RandomObject implements Serializable {
String md5half2 = md5.substring(16); String md5half2 = md5.substring(16);
@SneakyThrows @SneakyThrows
private String md5(String source) { private String md5(final String source) {
MessageDigest md = MessageDigest.getInstance("MD5"); final MessageDigest md = MessageDigest.getInstance("MD5");
md.update(source.getBytes()); md.update(source.getBytes());
byte[] digest = md.digest(); final byte[] digest = md.digest();
return JWO.bytesToHex(digest); return JWO.bytesToHex(digest);
} }
} }
@@ -94,7 +94,7 @@ public class LruCacheTest {
@Test @Test
public void cacheWithFallback() { public void cacheWithFallback() {
Map<String, RandomObject> fallback = new HashMap<>(); final Map<String, RandomObject> fallback = new HashMap<>();
lruCache = new LruCache<>(CACHE_MAX_SIZE, true, null, fallback); lruCache = new LruCache<>(CACHE_MAX_SIZE, true, null, fallback);
objects = new ArrayList<>(); objects = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_ENTRIES; i++) { for (int i = 0; i < NUMBER_OF_ENTRIES; i++) {
@@ -110,7 +110,7 @@ public class LruCacheTest {
Assertions.assertEquals(NUMBER_OF_ENTRIES, lruCache.size()); Assertions.assertEquals(NUMBER_OF_ENTRIES, lruCache.size());
//Removing the first inserted element should return it and decrease the cache size by 1 //Removing the first inserted element should return it and decrease the cache size by 1
RandomObject randomObject = objects.get(0); final RandomObject randomObject = objects.get(0);
Assertions.assertEquals(randomObject, lruCache.remove(randomObject.name)); Assertions.assertEquals(randomObject, lruCache.remove(randomObject.name));
Assertions.assertFalse(lruCache.containsKey(randomObject.name)); Assertions.assertFalse(lruCache.containsKey(randomObject.name));
Assertions.assertEquals(NUMBER_OF_ENTRIES - 1, lruCache.size()); Assertions.assertEquals(NUMBER_OF_ENTRIES - 1, lruCache.size());
@@ -122,12 +122,12 @@ public class LruCacheTest {
@Test @Test
public void cacheWithLoader() { public void cacheWithLoader() {
Function<String, RandomObject> loader = key -> { final Function<String, RandomObject> loader = key -> {
loaderInvocations++; loaderInvocations++;
return objects.stream().filter(o -> Objects.equals(key, o.name)).findFirst().get(); return objects.stream().filter(o -> Objects.equals(key, o.name)).findFirst().get();
}; };
lruCache = new LruCache<>(CACHE_MAX_SIZE, true, loader); lruCache = new LruCache<>(CACHE_MAX_SIZE, true, loader);
LruCache<String, RandomObject>.Stats stats = lruCache.getStats(); final LruCache<String, RandomObject>.Stats stats = lruCache.getStats();
objects = new ArrayList<>(); objects = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_ENTRIES; i++) { for (int i = 0; i < NUMBER_OF_ENTRIES; i++) {
RandomObject randomObject = new RandomObject(); RandomObject randomObject = new RandomObject();
@@ -150,7 +150,7 @@ public class LruCacheTest {
Assertions.assertEquals(loaderInvocations, this.loaderInvocations); Assertions.assertEquals(loaderInvocations, this.loaderInvocations);
// The cache should not contain any of the first NUMBER_OF_ENTRIES - CACHE_MAX_SIZE elements // The cache should not contain any of the first NUMBER_OF_ENTRIES - CACHE_MAX_SIZE elements
int evictedElements = NUMBER_OF_ENTRIES - CACHE_MAX_SIZE; final int evictedElements = NUMBER_OF_ENTRIES - CACHE_MAX_SIZE;
objects.stream().limit(evictedElements) objects.stream().limit(evictedElements)
.forEach(value -> Assertions.assertFalse(lruCache.containsKey(value.name))); .forEach(value -> Assertions.assertFalse(lruCache.containsKey(value.name)));

View File

@@ -25,7 +25,7 @@ public class PathClassLoaderTest {
List<Path> paths = StreamSupport.stream(fs.getRootDirectories().spliterator(), false).flatMap(new Function<Path, Stream<Path>>() { List<Path> paths = StreamSupport.stream(fs.getRootDirectories().spliterator(), false).flatMap(new Function<Path, Stream<Path>>() {
@Override @Override
@SneakyThrows @SneakyThrows
public Stream<Path> apply(Path path) { public Stream<Path> apply(final Path path) {
return Files.list(path) return Files.list(path)
.filter(Files::isRegularFile) .filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".jar")); .filter(p -> p.getFileName().toString().endsWith(".jar"));
@@ -33,13 +33,13 @@ public class PathClassLoaderTest {
}).flatMap(new Function<Path, Stream<Path>>() { }).flatMap(new Function<Path, Stream<Path>>() {
@Override @Override
@SneakyThrows @SneakyThrows
public Stream<Path> apply(Path path) { public Stream<Path> apply(final Path path) {
System.out.println(path.getFileName().toString()); System.out.println(path.getFileName().toString());
return StreamSupport.stream(FileSystems.newFileSystem(path, (ClassLoader) null).getRootDirectories().spliterator(), false); return StreamSupport.stream(FileSystems.newFileSystem(path, (ClassLoader) null).getRootDirectories().spliterator(), false);
} }
}).collect(Collectors.toUnmodifiableList()); }).collect(Collectors.toUnmodifiableList());
PathClassLoader classLoader = new PathClassLoader(paths); final PathClassLoader classLoader = new PathClassLoader(paths);
Class<?>[] cls = new Class[1]; final Class<?>[] cls = new Class[1];
Assertions.assertDoesNotThrow(() -> { Assertions.assertDoesNotThrow(() -> {
cls[0] = classLoader.loadClass("com.google.common.collect.ImmutableMap"); cls[0] = classLoader.loadClass("com.google.common.collect.ImmutableMap");
}); });

View File

@@ -43,7 +43,7 @@ public class TreeWalkerTest {
.map(entry -> newNode(entry.getKey(), entry.getValue())) .map(entry -> newNode(entry.getKey(), entry.getValue()))
.collect(Collectors.toMap(Node::getId, Function.identity())); .collect(Collectors.toMap(Node::getId, Function.identity()));
private Node newNode(int id, List<Integer> children) { private Node newNode(final int id, final List<Integer> children) {
if(children == null) { if(children == null) {
return new Node(id, Collections.emptyList()); return new Node(id, Collections.emptyList());
} else { } else {
@@ -63,7 +63,7 @@ public class TreeWalkerTest {
Iterator<Integer> it_post = expected_post_sequence.iterator(); Iterator<Integer> it_post = expected_post_sequence.iterator();
TreeNodeVisitor<Node, Void> nodeVisitor = new TreeNodeVisitor<Node, Void>() { TreeNodeVisitor<Node, Void> nodeVisitor = new TreeNodeVisitor<Node, Void>() {
@Override @Override
public VisitOutcome visitPre(List<StackContext<Node, Void>> stackContextList) { public VisitOutcome visitPre(final List<StackContext<Node, Void>> stackContextList) {
Assertions.assertTrue(it_pre.hasNext()); Assertions.assertTrue(it_pre.hasNext());
Assertions.assertEquals(it_pre.next(), Assertions.assertEquals(it_pre.next(),
stackContextList.get(stackContextList.size() - 1).getNode().getId()); stackContextList.get(stackContextList.size() - 1).getNode().getId());
@@ -71,13 +71,13 @@ public class TreeWalkerTest {
} }
@Override @Override
public void visitPost(List<StackContext<Node, Void>> stackContextList) { public void visitPost(final List<StackContext<Node, Void>> stackContextList) {
Assertions.assertTrue(it_post.hasNext()); Assertions.assertTrue(it_post.hasNext());
Assertions.assertEquals(it_post.next(), Assertions.assertEquals(it_post.next(),
stackContextList.get(stackContextList.size() - 1).getNode().getId()); stackContextList.get(stackContextList.size() - 1).getNode().getId());
} }
}; };
TreeWalker<Node, Void> walker = final TreeWalker<Node, Void> walker =
new TreeWalker<>(nodeVisitor); new TreeWalker<>(nodeVisitor);
walker.walk(testNodeMap.get(1)); walker.walk(testNodeMap.get(1));
Assertions.assertFalse(it_pre.hasNext()); Assertions.assertFalse(it_pre.hasNext());
@@ -86,14 +86,14 @@ public class TreeWalkerTest {
@Test @Test
public void filterTest() { public void filterTest() {
List<Integer> expected_pre_sequence = Stream.of(1, 2, 3, 4, 5, 8) final List<Integer> expected_pre_sequence = Stream.of(1, 2, 3, 4, 5, 8)
.collect(Collectors.toList()); .collect(Collectors.toList());
Iterator<Integer> it = expected_pre_sequence.iterator(); final Iterator<Integer> it = expected_pre_sequence.iterator();
TreeNodeVisitor<Node, Void> linkVisitor = new TreeNodeVisitor<Node, Void>() { final TreeNodeVisitor<Node, Void> linkVisitor = new TreeNodeVisitor<Node, Void>() {
@Override @Override
public VisitOutcome visitPre(List<StackContext<Node, Void>> nodePath) { public VisitOutcome visitPre(final List<StackContext<Node, Void>> nodePath) {
Assertions.assertTrue(it.hasNext()); Assertions.assertTrue(it.hasNext());
Integer id = nodePath.get(nodePath.size() - 1).getNode().getId(); final Integer id = nodePath.get(nodePath.size() - 1).getNode().getId();
Assertions.assertEquals(it.next(), id); Assertions.assertEquals(it.next(), id);
if(Objects.equals(4, nodePath.get(nodePath.size() - 1).getNode().getId())) { if(Objects.equals(4, nodePath.get(nodePath.size() - 1).getNode().getId())) {
return VisitOutcome.SKIP; return VisitOutcome.SKIP;
@@ -102,7 +102,7 @@ public class TreeWalkerTest {
} }
} }
}; };
TreeWalker<Node, Void> walker = final TreeWalker<Node, Void> walker =
new TreeWalker<>(linkVisitor); new TreeWalker<>(linkVisitor);
walker.walk(testNodeMap.get(1)); walker.walk(testNodeMap.get(1));
Assertions.assertFalse(it.hasNext()); Assertions.assertFalse(it.hasNext());

View File

@@ -15,7 +15,7 @@ public class VersionComparatorTest {
private static class TestCaseProvider implements ArgumentsProvider { private static class TestCaseProvider implements ArgumentsProvider {
@Override @Override
@SneakyThrows @SneakyThrows
public Stream<? extends Arguments> provideArguments(ExtensionContext context) { public Stream<? extends Arguments> provideArguments(final ExtensionContext context) {
return Stream.of( return Stream.of(
Arguments.of("", "", 0), Arguments.of("", "", 0),
Arguments.of("asdfg-2019", "asdfg-2019", 0), Arguments.of("asdfg-2019", "asdfg-2019", 0),
@@ -34,7 +34,7 @@ public class VersionComparatorTest {
@ParameterizedTest(name="version1: \"{0}\", version2: \"{1}\", expected outcome: {2}") @ParameterizedTest(name="version1: \"{0}\", version2: \"{1}\", expected outcome: {2}")
@ArgumentsSource(TestCaseProvider.class) @ArgumentsSource(TestCaseProvider.class)
public void test(String version1, String version2, int expectedOutcome) { public void test(final String version1, final String version2, final int expectedOutcome) {
Assertions.assertEquals(expectedOutcome, VersionComparator.cmp(version1, version2)); Assertions.assertEquals(expectedOutcome, VersionComparator.cmp(version1, version2));
} }
} }

View File

@@ -29,27 +29,27 @@ public class CompressionOutputStreamTest {
@SneakyThrows @SneakyThrows
@ParameterizedTest @ParameterizedTest
@MethodSource("testParameters") @MethodSource("testParameters")
public void test(CompressionFormat compressionFormat, int level) { public void test(final CompressionFormat compressionFormat, final int level) {
MessageDigest inputDigest = MessageDigest.getInstance("MD5"); final MessageDigest inputDigest = MessageDigest.getInstance("MD5");
byte[] compressed; byte[] compressed;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try(InputStream is = new BufferedInputStream(new DigestInputStream( try(final InputStream is = new BufferedInputStream(new DigestInputStream(
getClass().getResourceAsStream("/cracklib-small"), inputDigest)); getClass().getResourceAsStream("/cracklib-small"), inputDigest));
CompressionOutputStream compressionOutputStream = final CompressionOutputStream compressionOutputStream =
new CompressionOutputStream(new BufferedOutputStream(byteArrayOutputStream), compressionFormat, level) new CompressionOutputStream(new BufferedOutputStream(byteArrayOutputStream), compressionFormat, level)
) { ) {
int read; int read;
byte[] buffer = new byte[1024]; final byte[] buffer = new byte[1024];
while((read = is.read(buffer, 0, buffer.length)) >= 0) { while((read = is.read(buffer, 0, buffer.length)) >= 0) {
compressionOutputStream.write(buffer, 0, read); compressionOutputStream.write(buffer, 0, read);
} }
} }
compressed = byteArrayOutputStream.toByteArray(); compressed = byteArrayOutputStream.toByteArray();
MessageDigest outputDigest = MessageDigest.getInstance("MD5"); final MessageDigest outputDigest = MessageDigest.getInstance("MD5");
try(InputStream is = new DigestInputStream(new CompressionInputStream( try(final InputStream is = new DigestInputStream(new CompressionInputStream(
new ByteArrayInputStream(compressed), compressionFormat, StreamMode.DECOMPRESSION), outputDigest)) { new ByteArrayInputStream(compressed), compressionFormat, StreamMode.DECOMPRESSION), outputDigest)) {
byte[] buffer = new byte[1024]; final byte[] buffer = new byte[1024];
while(is.read(buffer, 0, buffer.length) >= 0) {} while(is.read(buffer, 0, buffer.length) >= 0) {}
} }
Assertions.assertArrayEquals(inputDigest.digest(), outputDigest.digest()); Assertions.assertArrayEquals(inputDigest.digest(), outputDigest.digest());