getErrorMessages() {
}
messages.addAll(errorMessages);
if (lines > maxLines) {
- messages.add(String.format(Locale.ENGLISH, " ... skipped logging of %d additional errors ...", lines - maxLines));
+ messages.add(String.format(
+ Locale.ENGLISH, " ... skipped logging of %d additional errors ...", lines - maxLines));
}
return messages;
- }
- finally {
+ } finally {
lock.unlock();
}
}
@@ -242,8 +220,7 @@ public boolean hasErrors() {
lock.lock();
try {
return !errorMessages.isEmpty();
- }
- finally {
+ } finally {
lock.unlock();
}
}
@@ -251,16 +228,14 @@ public boolean hasErrors() {
/**
* Merges the info and error messages of the other log.
*
- * @param other
- * the log to merge
+ * @param other the log to merge
*/
public void merge(final FilteredLog other) {
lock.lock();
try {
infoMessages.addAll(other.getInfoMessages());
errorMessages.addAll(other.getErrorMessages());
- }
- finally {
+ } finally {
lock.unlock();
}
}
diff --git a/src/main/java/edu/hm/hafner/util/Generated.java b/src/main/java/edu/hm/hafner/util/Generated.java
index 4f7122f62..103184b76 100644
--- a/src/main/java/edu/hm/hafner/util/Generated.java
+++ b/src/main/java/edu/hm/hafner/util/Generated.java
@@ -1,11 +1,18 @@
package edu.hm.hafner.util;
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.CLASS;
+
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import static java.lang.annotation.ElementType.*;
-import static java.lang.annotation.RetentionPolicy.*;
-
/**
* This annotation is used to mark source code that has been generated or is somehow not relevant for style checking or
* code coverage analysis. It is quite similar to the annotation of the abandoned JSR305 project. The main difference is
diff --git a/src/main/java/edu/hm/hafner/util/JavaPackageDetector.java b/src/main/java/edu/hm/hafner/util/JavaPackageDetector.java
index f7a44d2a9..bb315008c 100644
--- a/src/main/java/edu/hm/hafner/util/JavaPackageDetector.java
+++ b/src/main/java/edu/hm/hafner/util/JavaPackageDetector.java
@@ -1,7 +1,6 @@
package edu.hm.hafner.util;
import edu.hm.hafner.util.PackageDetectorFactory.FileSystemFacade;
-
import java.util.regex.Pattern;
/**
@@ -10,8 +9,7 @@
* @author Ullrich Hafner
*/
class JavaPackageDetector extends PackageDetector {
- private static final Pattern PACKAGE_PATTERN = Pattern.compile(
- "^\\s*package\\s*([a-z]+[.\\w]*)\\s*;.*");
+ private static final Pattern PACKAGE_PATTERN = Pattern.compile("^\\s*package\\s*([a-z]+[.\\w]*)\\s*;.*");
JavaPackageDetector(final FileSystemFacade fileSystem) {
super(fileSystem);
diff --git a/src/main/java/edu/hm/hafner/util/KotlinPackageDetector.java b/src/main/java/edu/hm/hafner/util/KotlinPackageDetector.java
index 4fd7abcbe..8147a5a65 100644
--- a/src/main/java/edu/hm/hafner/util/KotlinPackageDetector.java
+++ b/src/main/java/edu/hm/hafner/util/KotlinPackageDetector.java
@@ -1,8 +1,7 @@
package edu.hm.hafner.util;
-import java.util.regex.Pattern;
-
import edu.hm.hafner.util.PackageDetectorFactory.FileSystemFacade;
+import java.util.regex.Pattern;
/**
* Detects the package name of a Kotlin file.
@@ -10,8 +9,7 @@
* @author Bastian Kersting
*/
class KotlinPackageDetector extends PackageDetector {
- private static final Pattern PACKAGE_PATTERN = Pattern.compile(
- "^\\s*package\\s*([a-z]+[.\\w]*)\\s*.*");
+ private static final Pattern PACKAGE_PATTERN = Pattern.compile("^\\s*package\\s*([a-z]+[.\\w]*)\\s*.*");
@VisibleForTesting
KotlinPackageDetector(final FileSystemFacade fileSystem) {
diff --git a/src/main/java/edu/hm/hafner/util/LineRange.java b/src/main/java/edu/hm/hafner/util/LineRange.java
index 8bc2812f8..fdcbbefe3 100644
--- a/src/main/java/edu/hm/hafner/util/LineRange.java
+++ b/src/main/java/edu/hm/hafner/util/LineRange.java
@@ -22,8 +22,7 @@ public final class LineRange implements Serializable {
/**
* Creates a new instance of {@link LineRange}.
*
- * @param line
- * the single line of this range
+ * @param line the single line of this range
*/
public LineRange(final int line) {
this(line, line);
@@ -32,22 +31,18 @@ public LineRange(final int line) {
/**
* Creates a new instance of {@link LineRange}.
*
- * @param start
- * start of the range
- * @param end
- * end of the range
+ * @param start start of the range
+ * @param end end of the range
*/
@SuppressMutation(mutator = PitMutator.CONDITIONALS_BOUNDARY, justification = "False positive")
public LineRange(final int start, final int end) {
if (start <= 0) {
this.start = 0;
this.end = 0;
- }
- else if (start < end) {
+ } else if (start < end) {
this.start = start;
this.end = end;
- }
- else {
+ } else {
this.start = end;
this.end = start;
}
@@ -113,8 +108,7 @@ public boolean equals(final Object o) {
return false;
}
var lineRange = (LineRange) o;
- return start == lineRange.start
- && end == lineRange.end;
+ return start == lineRange.start && end == lineRange.end;
}
@Override
diff --git a/src/main/java/edu/hm/hafner/util/LineRangeList.java b/src/main/java/edu/hm/hafner/util/LineRangeList.java
index 5821d5fba..653885ed1 100644
--- a/src/main/java/edu/hm/hafner/util/LineRangeList.java
+++ b/src/main/java/edu/hm/hafner/util/LineRangeList.java
@@ -1,10 +1,8 @@
package edu.hm.hafner.util;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
import java.io.Serial;
import java.io.Serializable;
import java.util.AbstractList;
@@ -19,24 +17,22 @@
/**
* {@link List} of {@link LineRange} that stores values more efficiently at runtime.
*
- *
- * This class thinks of {@link LineRange} as two integers (start and end-start), hence a list of {@link LineRange}
+ *
This class thinks of {@link LineRange} as two integers (start and end-start), hence a list of {@link LineRange}
* becomes a list of integers. The class then stores those integers in {@code byte[]}. Each number is packed to UTF-8
* like variable length format. To store a long value N, we first split into 7 bit chunk, and store each 7 bit chunk as
* a byte, in the little endian order. The last byte gets its 8th bit set to indicate that that's the last byte. Thus in
* this format, 0x0 gets stored as 0x80, 0x1234 gets stored as {0x34,0xA4(0x24|0x80)}.
- *
*
- *
- * This variable length mode stores data most efficiently, since most line numbers are small. Access characteristic gets
- * close to that of {@link LinkedList}, since we can only traverse this packed byte[] from the start or from the end.
- *
+ * This variable length mode stores data most efficiently, since most line numbers are small. Access characteristic
+ * gets close to that of {@link LinkedList}, since we can only traverse this packed byte[] from the start or from the
+ * end.
*
* @author Kohsuke Kawaguchi
*/
public class LineRangeList extends AbstractList implements Serializable {
@Serial
private static final long serialVersionUID = -1123973098942984623L;
+
private static final int DEFAULT_CAPACITY = 16;
private static final boolean SEQUENTIAL = false;
@@ -45,9 +41,7 @@ public class LineRangeList extends AbstractList implements Serializab
/** Number of bytes in {@link #data} that's already used. This is not {@link List#size()}. */
private int len;
- /**
- * Creates an empty {@link LineRangeList}. It uses a capacity of {@link LineRangeList#DEFAULT_CAPACITY}.
- */
+ /** Creates an empty {@link LineRangeList}. It uses a capacity of {@link LineRangeList#DEFAULT_CAPACITY}. */
public LineRangeList() {
this(DEFAULT_CAPACITY);
}
@@ -55,8 +49,7 @@ public LineRangeList() {
/**
* Creates an empty {@link LineRangeList} with the specified capacity.
*
- * @param capacity
- * the initial capacity of the list
+ * @param capacity the initial capacity of the list
*/
public LineRangeList(final int capacity) {
super();
@@ -68,8 +61,7 @@ public LineRangeList(final int capacity) {
/**
* Creates a new {@link LineRangeList} with the specified elements.
*
- * @param copy
- * the initial elements
+ * @param copy the initial elements
*/
public LineRangeList(final Collection copy) {
this(copy.size() * 4); // guess
@@ -80,8 +72,7 @@ public LineRangeList(final Collection copy) {
/**
* Creates a new {@link LineRangeList} with the specified elements.
*
- * @param initialElements
- * the initial elements
+ * @param initialElements the initial elements
*/
@SuppressWarnings("PMD.UseArraysAsList")
public LineRangeList(final LineRange... initialElements) {
@@ -93,20 +84,17 @@ public LineRangeList(final LineRange... initialElements) {
}
/**
- * Appends all the elements in the specified collection to the end of this list, in the order that they are
- * returned by the specified collection's iterator (optional operation). The behavior of this operation is
- * undefined if the specified collection is modified while the operation is in progress. (Note that this will occur
- * if the specified collection is this list, and it's nonempty.)
- *
- * @param ranges
- * collection containing elements to be added to this list
+ * Appends all the elements in the specified collection to the end of this list, in the order that they are returned
+ * by the specified collection's iterator (optional operation). The behavior of this operation is undefined if the
+ * specified collection is modified while the operation is in progress. (Note that this will occur if the specified
+ * collection is this list, and it's nonempty.)
*
+ * @param ranges collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
- * @throws NullPointerException
- * if the specified collection contains one or more null elements and this list does not permit null
- * elements, or if the specified collection is null
- * @throws IllegalArgumentException
- * if some property of an element of the specified collection prevents it from being added to this list
+ * @throws NullPointerException if the specified collection contains one or more null elements and this list does
+ * not permit null elements, or if the specified collection is null
+ * @throws IllegalArgumentException if some property of an element of the specified collection prevents it from
+ * being added to this list
* @see #add(Object)
*/
public final boolean addAll(final Iterable extends LineRange> ranges) {
@@ -119,8 +107,7 @@ public final boolean addAll(final Iterable extends LineRange> ranges) {
/**
* Makes sure that the buffer has capability to store N bytes.
*
- * @param n
- * capacity
+ * @param n capacity
*/
private void ensure(final int n) {
if (data.length < n) {
@@ -133,7 +120,7 @@ private void ensure(final int n) {
@Override
public boolean contains(final Object o) {
if (o instanceof final LineRange other) {
- for (var cursor = new Cursor(); cursor.hasNext();) {
+ for (var cursor = new Cursor(); cursor.hasNext(); ) {
if (cursor.compare(other)) {
return true;
}
@@ -196,9 +183,7 @@ public ListIterator listIterator(final int index) {
return new Cursor().skip(index);
}
- /**
- * Minimizes the memory waste by throwing away excess capacity.
- */
+ /** Minimizes the memory waste by throwing away excess capacity. */
public void trim() {
if (len != data.length) {
var small = new byte[len];
@@ -207,9 +192,7 @@ public void trim() {
}
}
- /**
- * Navigates through the ranges and performs the conversion to and from {@link LineRange}.
- */
+ /** Navigates through the ranges and performs the conversion to and from {@link LineRange}. */
@SuppressWarnings("PMD.AssignmentInOperand")
private class Cursor implements ListIterator {
private int position;
@@ -222,9 +205,7 @@ private class Cursor implements ListIterator {
this(0);
}
- /**
- * Does the opposite of {@link #read()} and skips back one int.
- */
+ /** Does the opposite of {@link #read()} and skips back one int. */
private void prev() {
if (position == 0) {
throw new NoSuchElementException("Cursor is a the beginning.");
@@ -239,7 +220,8 @@ private void prev() {
*
* @return the current element
*/
- @Override @SuppressFBWarnings(value = "IT_NO_SUCH_ELEMENT", justification = "thrown in read()")
+ @Override
+ @SuppressFBWarnings(value = "IT_NO_SUCH_ELEMENT", justification = "thrown in read()")
public LineRange next() {
int s = read();
int d = read();
@@ -253,9 +235,7 @@ public LineRange previous() {
return copy().next();
}
- /**
- * Removes the last returned value.
- */
+ /** Removes the last returned value. */
@Override
public void remove() {
prev();
@@ -310,9 +290,7 @@ private void write(final LineRange r) {
/**
* Reads the current value at the cursor and compares it.
*
- * @param other
- * the line range to compare with
- *
+ * @param other the line range to compare with
* @return {@code true} if the read value is equal to the specified range
*/
private boolean compare(final LineRange other) {
@@ -324,9 +302,7 @@ private boolean compare(final LineRange other) {
/**
* Skips forward and gets the pointer to N-th element.
*
- * @param n
- * number of elements to skip
- *
+ * @param n number of elements to skip
* @return this cursor
*/
@CanIgnoreReturnValue
@@ -372,8 +348,7 @@ private void adjust(final int diff) {
ensure(len + diff);
if (diff > 0) {
System.arraycopy(data, position, data, position + diff, len - position);
- }
- else {
+ } else {
System.arraycopy(data, position - diff, data, position, len - position + diff);
}
len += diff;
@@ -382,9 +357,7 @@ private void adjust(final int diff) {
/**
* Rewrites the value at the current cursor position.
*
- * @param other
- * the line range to rewrite
- *
+ * @param other the line range to rewrite
* @return the changed line range
*/
private LineRange rewrite(final LineRange other) {
@@ -402,9 +375,7 @@ public void set(final LineRange v) {
rewrite(v);
}
- /**
- * Inserts the value at the current cursor position.
- */
+ /** Inserts the value at the current cursor position. */
@Override
public void add(final LineRange v) {
int newSize = sizeOf(v);
@@ -431,9 +402,7 @@ private int sizeOf(final LineRange v) {
/**
* Computes the number of bytes that the value 'index' would occupy in its encoded form.
*
- * @param index
- * the index to check
- *
+ * @param index the index to check
* @return the number of bytes
*/
private int sizeOf(final int index) {
diff --git a/src/main/java/edu/hm/hafner/util/LookaheadStream.java b/src/main/java/edu/hm/hafner/util/LookaheadStream.java
index afc96318c..da8559661 100644
--- a/src/main/java/edu/hm/hafner/util/LookaheadStream.java
+++ b/src/main/java/edu/hm/hafner/util/LookaheadStream.java
@@ -4,7 +4,6 @@
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
import java.util.stream.Stream;
-
import org.apache.commons.lang3.StringUtils;
/**
@@ -25,8 +24,7 @@ public class LookaheadStream implements AutoCloseable {
/**
* Wraps the specified stream of lines into a {@link LookaheadStream}.
*
- * @param stream
- * the lines to wrap
+ * @param stream the lines to wrap
*/
public LookaheadStream(final Stream stream) {
this(stream, StringUtils.EMPTY);
@@ -35,10 +33,8 @@ public LookaheadStream(final Stream stream) {
/**
* Wraps the specified stream of lines into a {@link LookaheadStream}.
*
- * @param stream
- * the lines to wrap
- * @param fileName
- * the file name of the stream
+ * @param stream the lines to wrap
+ * @param fileName the file name of the stream
*/
public LookaheadStream(final Stream stream, final String fileName) {
this.stream = stream;
@@ -68,9 +64,7 @@ public boolean hasNext() {
/**
* Returns {@code true} if the stream has at least one more element that matches the given regular expression.
*
- * @param regexp
- * the regular expression
- *
+ * @param regexp the regular expression
* @return {@code true} if the stream has more elements that match the regexp
*/
public boolean hasNext(final String regexp) {
@@ -89,8 +83,7 @@ public boolean hasNext(final String regexp) {
* the next call of {@link #next()} will again return this value.
*
* @return the next element in the stream
- * @throws NoSuchElementException
- * if the stream has no more elements
+ * @throws NoSuchElementException if the stream has no more elements
*/
public String peekNext() {
if (!isLookaheadFilled) {
@@ -108,8 +101,7 @@ private void fillLookahead() {
* Returns the next element in the stream.
*
* @return the next element in the stream
- * @throws NoSuchElementException
- * if the stream has no more elements
+ * @throws NoSuchElementException if the stream has no more elements
*/
public String next() {
line++;
@@ -130,7 +122,8 @@ public int getLine() {
return line;
}
- @Override @Generated
+ @Override
+ @Generated
public String toString() {
return "[%d] -> '%s'".formatted(line, lookaheadLine);
}
diff --git a/src/main/java/edu/hm/hafner/util/PackageDetector.java b/src/main/java/edu/hm/hafner/util/PackageDetector.java
index 0c55ee05b..fab52e9bd 100644
--- a/src/main/java/edu/hm/hafner/util/PackageDetector.java
+++ b/src/main/java/edu/hm/hafner/util/PackageDetector.java
@@ -1,9 +1,6 @@
package edu.hm.hafner.util;
-import org.apache.commons.io.input.BOMInputStream;
-
import edu.hm.hafner.util.PackageDetectorFactory.FileSystemFacade;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -14,6 +11,7 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
+import org.apache.commons.io.input.BOMInputStream;
/**
* Base class for package detectors.
@@ -26,8 +24,7 @@ abstract class PackageDetector {
/**
* Creates a new instance of {@link PackageDetector}.
*
- * @param fileSystem
- * file system facade
+ * @param fileSystem file system facade
*/
PackageDetector(final FileSystemFacade fileSystem) {
this.fileSystem = fileSystem;
@@ -36,26 +33,22 @@ abstract class PackageDetector {
/**
* Detects the package or namespace name of the specified file.
*
- * @param fileName
- * the file name of the file to scan
- * @param charset
- * the charset to use when reading the source files
- *
+ * @param fileName the file name of the file to scan
+ * @param charset the charset to use when reading the source files
* @return the detected package or namespace name
*/
Optional detectPackageName(final String fileName, final Charset charset) {
try (var stream = fileSystem.openFile(fileName)) {
return detectPackageName(stream, charset);
- }
- catch (IOException | InvalidPathException ignore) {
+ } catch (IOException | InvalidPathException ignore) {
// ignore IO errors
}
return Optional.empty();
}
private Optional detectPackageName(final InputStream stream, final Charset charset) throws IOException {
- try (var buffer = new BufferedReader(
- new InputStreamReader(BOMInputStream.builder().setInputStream(stream).get(), charset))) {
+ try (var buffer = new BufferedReader(new InputStreamReader(
+ BOMInputStream.builder().setInputStream(stream).get(), charset))) {
return detectPackageName(buffer.lines());
}
}
@@ -64,9 +57,7 @@ private Optional detectPackageName(final InputStream stream, final Chars
* Detects the package or namespace name of the specified input stream. The stream will be closed automatically by
* the caller of this method.
*
- * @param lines
- * the content of the file to scan
- *
+ * @param lines the content of the file to scan
* @return the detected package or namespace name
*/
private Optional detectPackageName(final Stream lines) {
@@ -88,9 +79,7 @@ private Optional detectPackageName(final Stream lines) {
/**
* Returns whether this classifier accepts the specified file for processing.
*
- * @param fileName
- * the file name
- *
+ * @param fileName the file name
* @return {@code true} if the classifier accepts the specified file for processing.
*/
abstract boolean accepts(String fileName);
diff --git a/src/main/java/edu/hm/hafner/util/PackageDetectorFactory.java b/src/main/java/edu/hm/hafner/util/PackageDetectorFactory.java
index fe9281af3..ad55182ff 100644
--- a/src/main/java/edu/hm/hafner/util/PackageDetectorFactory.java
+++ b/src/main/java/edu/hm/hafner/util/PackageDetectorFactory.java
@@ -1,7 +1,6 @@
package edu.hm.hafner.util;
import com.google.errorprone.annotations.MustBeClosed;
-
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
@@ -27,9 +26,7 @@ public static PackageDetectorRunner createPackageDetectors() {
/**
* Creates a new package detector runner that uses the detectors for Java, Kotlin, and C#.
*
- * @param facade
- * the file system facade to use
- *
+ * @param facade the file system facade to use
* @return the package detector runner
*/
@VisibleForTesting
@@ -44,23 +41,17 @@ private PackageDetectorFactory() {
// prevents instantiation
}
- /**
- * Facade for file system operations. May be replaced by stubs in test cases.
- */
+ /** Facade for file system operations. May be replaced by stubs in test cases. */
@VisibleForTesting
@SuppressMutation(justification = "This method is not tested directly because it accesses the file system.")
public static class FileSystemFacade {
/**
* Opens the specified file.
*
- * @param fileName
- * the name of the file to open
- *
+ * @param fileName the name of the file to open
* @return the input stream to read the file
- * @throws IOException
- * if the file could not be opened
- * @throws InvalidPathException
- * the file name is invalid
+ * @throws IOException if the file could not be opened
+ * @throws InvalidPathException the file name is invalid
*/
@MustBeClosed
public InputStream openFile(final String fileName) throws IOException, InvalidPathException {
diff --git a/src/main/java/edu/hm/hafner/util/PackageDetectorRunner.java b/src/main/java/edu/hm/hafner/util/PackageDetectorRunner.java
index bf3dc3d17..b1b0e040d 100644
--- a/src/main/java/edu/hm/hafner/util/PackageDetectorRunner.java
+++ b/src/main/java/edu/hm/hafner/util/PackageDetectorRunner.java
@@ -20,11 +20,8 @@ public class PackageDetectorRunner {
/**
* Detects the package name of the specified file based on several detector strategies.
*
- * @param fileName
- * the filename of the file to scan
- * @param charset
- * the charset to use when reading the source files
- *
+ * @param fileName the filename of the file to scan
+ * @param charset the charset to use when reading the source files
* @return the detected package name or {@link Optional#empty()} if no package name could be detected
*/
public Optional detectPackageName(final String fileName, final Charset charset) {
diff --git a/src/main/java/edu/hm/hafner/util/PathUtil.java b/src/main/java/edu/hm/hafner/util/PathUtil.java
index 05e79836a..a8e2f9609 100644
--- a/src/main/java/edu/hm/hafner/util/PathUtil.java
+++ b/src/main/java/edu/hm/hafner/util/PathUtil.java
@@ -1,5 +1,6 @@
package edu.hm.hafner.util;
+import edu.umd.cs.findbugs.annotations.CheckForNull;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -7,15 +8,12 @@
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Objects;
-
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
-import edu.umd.cs.findbugs.annotations.CheckForNull;
-
/**
- * Utilities for {@link Path} instances. These methods handle file paths in Windows and Unix file system
- * implementations transparently. Moreover, these methods do not throw exceptions when illegal paths are specified.
+ * Utilities for {@link Path} instances. These methods handle file paths in Windows and Unix file system implementations
+ * transparently. Moreover, these methods do not throw exceptions when illegal paths are specified.
*
* @author Ullrich Hafner
*/
@@ -27,23 +25,18 @@ public class PathUtil {
/**
* Tests whether a file exists.
*
- *
- * Note that the result of this method is immediately outdated. If this method indicates the file exists then there
- * is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security
- * sensitive applications.
- *
- *
- * @param fileName
- * the absolute path of the file
+ * Note that the result of this method is immediately outdated. If this method indicates the file exists then
+ * there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in
+ * security sensitive applications.
*
+ * @param fileName the absolute path of the file
* @return {@code true} if the file exists; {@code false} if the file does not exist or its existence cannot be
- * determined.
+ * determined.
*/
public boolean exists(final String fileName) {
try {
return Files.exists(Path.of(fileName));
- }
- catch (IllegalArgumentException ignore) {
+ } catch (IllegalArgumentException ignore) {
return false;
}
}
@@ -51,19 +44,14 @@ public boolean exists(final String fileName) {
/**
* Tests whether a file exists.
*
- *
- * Note that the result of this method is immediately outdated. If this method indicates the file exists then there
- * is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security
- * sensitive applications.
- *
- *
- * @param fileName
- * the file name
- * @param directory
- * the directory that contains the file
+ * Note that the result of this method is immediately outdated. If this method indicates the file exists then
+ * there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in
+ * security sensitive applications.
*
+ * @param fileName the file name
+ * @param directory the directory that contains the file
* @return {@code true} if the file exists; {@code false} if the file does not exist or its existence cannot be
- * determined.
+ * determined.
*/
public boolean exists(final String fileName, final String directory) {
return exists(createAbsolutePath(directory, fileName));
@@ -75,16 +63,13 @@ public boolean exists(final String fileName, final String directory) {
* provided {@code path} will be returned unchanged (but normalized using the UNIX path separator and upper case
* drive letter).
*
- * @param path
- * the path to get the absolute path for
- *
+ * @param path the path to get the absolute path for
* @return the absolute path
*/
public String getAbsolutePath(final String path) {
try {
return getAbsolutePath(Path.of(path));
- }
- catch (IllegalArgumentException ignored) {
+ } catch (IllegalArgumentException ignored) {
return makeUnixPath(path);
}
}
@@ -95,78 +80,64 @@ public String getAbsolutePath(final String path) {
* provided {@code path} will be returned unchanged (but normalized using the UNIX path separator and upper case
* drive letter).
*
- * @param path
- * the path to get the absolute path for
- *
+ * @param path the path to get the absolute path for
* @return the absolute path
*/
public String getAbsolutePath(final Path path) {
try {
return makeUnixPath(normalize(path).toString());
- }
- catch (IOException | IllegalArgumentException ignored) {
+ } catch (IOException | IllegalArgumentException ignored) {
return makeUnixPath(path.toString());
}
}
/**
- * Returns the relative path of the specified path with respect to the provided base directory. The given path will be
- * actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the base
- * directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could not
- * be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using the
- * UNIX path separator and upper case drive letter).
- *
- * @param base
- * the base directory that should be used to get the absolute path for
- * @param path
- * the path to get the absolute path for
- *
+ * Returns the relative path of the specified path with respect to the provided base directory. The given path will
+ * be actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the
+ * base directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could
+ * not be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using
+ * the UNIX path separator and upper case drive letter).
+ *
+ * @param base the base directory that should be used to get the absolute path for
+ * @param path the path to get the absolute path for
* @return the relative path
*/
public String getRelativePath(final Path base, final String path) {
try {
return getRelativePath(base, Path.of(path));
- }
- catch (IllegalArgumentException ignored) {
+ } catch (IllegalArgumentException ignored) {
return makeUnixPath(path);
}
}
/**
- * Returns the relative path of the specified path with respect to the provided base directory. The given path will be
- * actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the base
- * directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could not
- * be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using the
- * UNIX path separator and upper case drive letter).
- *
- * @param base
- * the base directory that should be to get the absolute path for
- * @param path
- * the path to get the absolute path for
- *
+ * Returns the relative path of the specified path with respect to the provided base directory. The given path will
+ * be actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the
+ * base directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could
+ * not be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using
+ * the UNIX path separator and upper case drive letter).
+ *
+ * @param base the base directory that should be to get the absolute path for
+ * @param path the path to get the absolute path for
* @return the relative path
*/
public String getRelativePath(final String base, final String path) {
try {
return getRelativePath(Path.of(base), Path.of(path));
- }
- catch (IllegalArgumentException ignored) {
+ } catch (IllegalArgumentException ignored) {
return makeUnixPath(path);
}
}
/**
- * Returns the relative path of the specified path with respect to the provided base directory. The given path will be
- * actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the base
- * directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could not
- * be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using the
- * UNIX path separator and upper case drive letter).
- *
- * @param base
- * the base directory that should be to get the absolute path for
- * @param path
- * the path to get the absolute path for
- *
+ * Returns the relative path of the specified path with respect to the provided base directory. The given path will
+ * be actually resolved in the file system (which may lead to a different fully qualified absolute path). Then the
+ * base directory prefix will be removed (if possible). In case of an error, i.e., if the file is not found or could
+ * not be resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using
+ * the UNIX path separator and upper case drive letter).
+ *
+ * @param base the base directory that should be to get the absolute path for
+ * @param path the path to get the absolute path for
* @return the relative path
*/
public String getRelativePath(final Path base, final Path path) {
@@ -175,23 +146,21 @@ public String getRelativePath(final Path base, final Path path) {
if (path.isAbsolute()) {
return makeUnixPath(normalizedBase.relativize(normalize(path)).toString());
}
- return makeUnixPath(normalizedBase.relativize(normalize(base.resolve(path))).toString());
- }
- catch (IOException | IllegalArgumentException ignored) {
+ return makeUnixPath(
+ normalizedBase.relativize(normalize(base.resolve(path))).toString());
+ } catch (IOException | IllegalArgumentException ignored) {
// ignore and return the path as such
}
return makeUnixPath(path.toString());
}
/**
- * Returns a normalized relative path of the specified path. The given path will be actually resolved in the file system
- * (which may lead to a different path). In case of an error, i.e., if the file is not found or could not be
+ * Returns a normalized relative path of the specified path. The given path will be actually resolved in the file
+ * system (which may lead to a different path). In case of an error, i.e., if the file is not found or could not be
* resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using the UNIX
* path separator and upper case drive letter).
*
- * @param relative
- * the path to get the normalized path for
- *
+ * @param relative the path to get the normalized path for
* @return the normalized relative path
*/
public String getRelativePath(final Path relative) {
@@ -199,21 +168,18 @@ public String getRelativePath(final Path relative) {
}
/**
- * Returns a normalized relative path of the specified path. The given path will be actually resolved in the file system
- * (which may lead to a different path). In case of an error, i.e., if the file is not found or could not be
+ * Returns a normalized relative path of the specified path. The given path will be actually resolved in the file
+ * system (which may lead to a different path). In case of an error, i.e., if the file is not found or could not be
* resolved in the parent, then the provided {@code path} will be returned unchanged (but normalized using the UNIX
* path separator and upper case drive letter).
*
- * @param relative
- * the path to get the normalized path for
- *
+ * @param relative the path to get the normalized path for
* @return the normalized relative path
*/
public String getRelativePath(final String relative) {
try {
return getRelativePath(Path.of(relative));
- }
- catch (IllegalArgumentException ignored) {
+ } catch (IllegalArgumentException ignored) {
// ignore and return the path as such
}
return makeUnixPath(relative);
@@ -222,11 +188,8 @@ public String getRelativePath(final String relative) {
/**
* Returns the absolute path of the specified file in the given directory.
*
- * @param directory
- * the directory that contains the file
- * @param fileName
- * the file name
- *
+ * @param directory the directory that contains the file
+ * @param fileName the file name
* @return the absolute path
*/
public String createAbsolutePath(@CheckForNull final String directory, final String fileName) {
@@ -238,16 +201,14 @@ public String createAbsolutePath(@CheckForNull final String directory, final Str
String separator;
if (path.endsWith(SLASH)) {
separator = StringUtils.EMPTY;
- }
- else {
+ } else {
separator = SLASH;
}
try {
var normalized = FilenameUtils.normalize(String.join(separator, path, fileName));
return makeUnixPath(normalized == null ? fileName : normalized);
- }
- catch (IllegalArgumentException ignored) {
+ } catch (IllegalArgumentException ignored) {
return makeUnixPath(fileName);
}
}
@@ -255,9 +216,7 @@ public String createAbsolutePath(@CheckForNull final String directory, final Str
/**
* Returns whether the specified file name is an absolute path.
*
- * @param fileName
- * the file name to test
- *
+ * @param fileName the file name to test
* @return {@code true} if this path is an absolute path, {@code false} if a relative path
*/
public boolean isAbsolute(final String fileName) {
@@ -266,8 +225,7 @@ public boolean isAbsolute(final String fileName) {
if (uri.isAbsolute()) {
return true;
}
- }
- catch (URISyntaxException ignored) {
+ } catch (URISyntaxException ignored) {
// catch and ignore as system paths are not URI, and we need to check them separately
}
return FilenameUtils.getPrefixLength(fileName) > 0;
diff --git a/src/main/java/edu/hm/hafner/util/PitMutator.java b/src/main/java/edu/hm/hafner/util/PitMutator.java
index dd086de5e..781feea0d 100644
--- a/src/main/java/edu/hm/hafner/util/PitMutator.java
+++ b/src/main/java/edu/hm/hafner/util/PitMutator.java
@@ -1,9 +1,6 @@
package edu.hm.hafner.util;
-/**
- * Represents the mutators available in PIT.
- * This enum maps each mutator name to its fully qualified class name.
- */
+/** Represents the mutators available in PIT. This enum maps each mutator name to its fully qualified class name. */
public enum PitMutator {
CONDITIONALS_BOUNDARY("org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator"),
CONSTRUCTOR_CALLS("org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutator"),
@@ -19,28 +16,44 @@ public enum PitMutator {
EMPTY_RETURNS("org.pitest.mutationtest.engine.gregor.mutators.returns.EmptyObjectReturnValsMutator"),
NULL_RETURNS("org.pitest.mutationtest.engine.gregor.mutators.returns.NullReturnValsMutator"),
PRIMITIVE_RETURNS("org.pitest.mutationtest.engine.gregor.mutators.returns.PrimitiveReturnsMutator"),
- EXPERIMENTAL_ARGUMENT_PROPAGATION("org.pitest.mutationtest.engine.gregor.mutators.experimental.ArgumentPropagationMutator"),
+ EXPERIMENTAL_ARGUMENT_PROPAGATION(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.ArgumentPropagationMutator"),
EXPERIMENTAL_BIG_DECIMAL("org.pitest.mutationtest.engine.gregor.mutators.experimental.BigDecimalMutator"),
EXPERIMENTAL_BIG_INTEGER("org.pitest.mutationtest.engine.gregor.mutators.experimental.BigIntegerMutator"),
EXPERIMENTAL_MEMBER_VARIABLE("org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator"),
EXPERIMENTAL_NAKED_RECEIVER("org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator"),
REMOVE_INCREMENTS("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveIncrementsMutator"),
REMOVE_CONDITIONALS_EQUAL_IF("org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF"),
- REMOVE_CONDITIONALS_EQUAL_ELSE("org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_ELSE"),
+ REMOVE_CONDITIONALS_EQUAL_ELSE(
+ "org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_ELSE"),
REMOVE_CONDITIONALS_ORDER_IF("org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_ORDER_IF"),
- REMOVE_CONDITIONALS_ORDER_ELSE("org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_ORDER_ELSE"),
+ REMOVE_CONDITIONALS_ORDER_ELSE(
+ "org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_ORDER_ELSE"),
EXPERIMENTAL_SWITCH("org.pitest.mutationtest.engine.gregor.mutators.experimental.SwitchMutator"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_0("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_0"), //todo maybe find a better solution for n cases
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_1("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_1"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_2("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_2"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_3("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_3"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_4("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_4"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_5("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_5"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_6("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_6"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_7("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_7"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_8("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_8"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_9("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_9"),
- EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_10("org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_10"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_0(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_0"), // todo maybe find a
+ // better solution for
+ // n cases
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_1(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_1"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_2(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_2"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_3(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_3"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_4(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_4"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_5(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_5"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_6(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_6"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_7(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_7"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_8(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_8"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_9(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_9"),
+ EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_10(
+ "org.pitest.mutationtest.engine.gregor.mutators.experimental.RemoveSwitchMutator_10"),
NONE("");
private final String fqcn;
diff --git a/src/main/java/edu/hm/hafner/util/PrefixLogger.java b/src/main/java/edu/hm/hafner/util/PrefixLogger.java
index 1edfc6f19..bfd4f062f 100644
--- a/src/main/java/edu/hm/hafner/util/PrefixLogger.java
+++ b/src/main/java/edu/hm/hafner/util/PrefixLogger.java
@@ -1,10 +1,9 @@
package edu.hm.hafner.util;
+import com.google.errorprone.annotations.FormatMethod;
import java.io.PrintStream;
import java.util.Collection;
-import com.google.errorprone.annotations.FormatMethod;
-
/**
* A simple logger that prefixes each message with a given name.
*
@@ -17,16 +16,13 @@ public class PrefixLogger {
/**
* Creates a new {@link PrefixLogger}.
*
- * @param logger
- * the logger to create
- * @param prefix
- * the prefix to print
+ * @param logger the logger to create
+ * @param prefix the prefix to print
*/
public PrefixLogger(final PrintStream logger, final String prefix) {
if (prefix.contains("[")) {
this.toolName = prefix + " ";
- }
- else {
+ } else {
this.toolName = "[%s] ".formatted(prefix);
}
delegate = logger;
@@ -35,12 +31,9 @@ public PrefixLogger(final PrintStream logger, final String prefix) {
/**
* Logs the specified message.
*
- * @param format
- * A format string
- * @param args
- * Arguments referenced by the format specifiers in the format string. If there are more arguments than
- * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be
- * zero.
+ * @param format A format string
+ * @param args Arguments referenced by the format specifiers in the format string. If there are more arguments than
+ * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.
*/
@FormatMethod
public void log(final String format, final Object... args) {
@@ -50,8 +43,7 @@ public void log(final String format, final Object... args) {
/**
* Logs the specified messages.
*
- * @param lines
- * the messages to log
+ * @param lines the messages to log
*/
public void logEachLine(final Collection lines) {
lines.forEach(this::print);
diff --git a/src/main/java/edu/hm/hafner/util/ResourceExtractor.java b/src/main/java/edu/hm/hafner/util/ResourceExtractor.java
index ab012091b..58185d226 100644
--- a/src/main/java/edu/hm/hafner/util/ResourceExtractor.java
+++ b/src/main/java/edu/hm/hafner/util/ResourceExtractor.java
@@ -1,8 +1,5 @@
package edu.hm.hafner.util;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringUtils;
-
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -17,6 +14,8 @@
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
/**
* A proxy for resources. Extracts a given collection of files from the classpath and copies them to a target path.
@@ -31,8 +30,7 @@ public class ResourceExtractor {
/**
* Creates a new {@link ResourceExtractor} that extracts resources from the classloader of the specified class.
*
- * @param targetClass
- * the target class to use the classloader from
+ * @param targetClass the target class to use the classloader from
*/
public ResourceExtractor(final Class> targetClass) {
this(targetClass, targetClass.getProtectionDomain());
@@ -56,8 +54,7 @@ public ResourceExtractor(final Class> targetClass) {
readingFromJarFile = Files.isRegularFile(entryPoint);
if (readingFromJarFile) {
extractor = new JarExtractor(entryPoint);
- }
- else {
+ } else {
extractor = new FolderExtractor(entryPoint);
}
resourcePath = entryPoint.toString();
@@ -74,12 +71,9 @@ public boolean isReadingFromJarFile() {
/**
* Extracts the specified source files from the classloader and saves them to the specified target folder.
*
- * @param targetDirectory
- * the target path that will be the parent folder of all extracted files
- * @param source
- * the source file to extract
- * @param sources
- * the additional source files to extract
+ * @param targetDirectory the target path that will be the parent folder of all extracted files
+ * @param source the source file to extract
+ * @param sources the additional source files to extract
*/
public void extract(final Path targetDirectory, final String source, final String... sources) {
if (!Files.isDirectory(targetDirectory)) {
@@ -91,9 +85,7 @@ public void extract(final Path targetDirectory, final String source, final Strin
extractor.extractFiles(targetDirectory, allSources);
}
- /**
- * Extracts a collection of files and copies them to a given target path.
- */
+ /** Extracts a collection of files and copies them to a given target path. */
private abstract static class Extractor {
private final Path entryPoint;
@@ -108,9 +100,7 @@ Path getEntryPoint() {
abstract void extractFiles(Path targetDirectory, String... sources);
}
- /**
- * Extracts files from a folder, typically provided by the development environment or build system.
- */
+ /** Extracts files from a folder, typically provided by the development environment or build system. */
private static class FolderExtractor extends Extractor {
FolderExtractor(final Path entryPoint) {
super(entryPoint);
@@ -124,8 +114,7 @@ void extractFiles(final Path targetDirectory, final String... sources) {
Files.createDirectories(targetFile);
copy(targetFile, source);
}
- }
- catch (IOException exception) {
+ } catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
@@ -133,16 +122,13 @@ void extractFiles(final Path targetDirectory, final String... sources) {
private void copy(final Path target, final String source) {
try {
Files.copy(getEntryPoint().resolve(source), target, StandardCopyOption.REPLACE_EXISTING);
- }
- catch (IOException exception) {
+ } catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
}
- /**
- * Extracts files from a deployed jar file.
- */
+ /** Extracts files from a deployed jar file. */
private static class JarExtractor extends Extractor {
JarExtractor(final Path entryPoint) {
super(entryPoint);
@@ -161,8 +147,7 @@ void extractFiles(final Path targetDirectory, final String... sources) {
remaining.remove(name);
}
}
- }
- catch (IOException exception) {
+ } catch (IOException exception) {
throw new UncheckedIOException(exception);
}
if (!remaining.isEmpty()) {
@@ -180,7 +165,8 @@ private void copy(final Path targetDirectory, final JarFile jar, final JarEntry
if (parent != null) {
Files.createDirectories(parent);
}
- try (var inputStream = jar.getInputStream(entry); var outputStream = Files.newOutputStream(targetFile)) {
+ try (var inputStream = jar.getInputStream(entry);
+ var outputStream = Files.newOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
}
}
diff --git a/src/main/java/edu/hm/hafner/util/SecureXmlParserFactory.java b/src/main/java/edu/hm/hafner/util/SecureXmlParserFactory.java
index 2557c4cbb..c934e144c 100644
--- a/src/main/java/edu/hm/hafner/util/SecureXmlParserFactory.java
+++ b/src/main/java/edu/hm/hafner/util/SecureXmlParserFactory.java
@@ -1,5 +1,16 @@
package edu.hm.hafner.util;
+import static javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD;
+import static javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA;
+import static javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET;
+import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING;
+
+import com.google.errorprone.annotations.FormatMethod;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Serial;
+import java.nio.charset.Charset;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -12,7 +23,6 @@
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
-
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.w3c.dom.Document;
@@ -22,34 +32,25 @@
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
-import com.google.errorprone.annotations.FormatMethod;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.Serial;
-import java.nio.charset.Charset;
-
-import static javax.xml.XMLConstants.*;
-
/**
* Factory for XML Parsers that prevent XML External Entity attacks. Those attacks occur when untrusted XML input
* containing a reference to an external entity is processed by a weakly configured XML parser.
*
* @author Ullrich Hafner
* @see XML
- * External Entity Prevention Cheat Sheet
- * @see XML parsers should not be vulnerable to XXE
- * attacks
+ * External Entity Prevention Cheat Sheet
+ * @see XML parsers should not be vulnerable to XXE attacks
*/
-@SuppressMutation(mutator = PitMutator.VOID_METHOD_CALLS, justification = "Setters are used to configure the parsers and factories")
+@SuppressMutation(
+ mutator = PitMutator.VOID_METHOD_CALLS,
+ justification = "Setters are used to configure the parsers and factories")
public class SecureXmlParserFactory {
/**
* The following constants are copied from the Xerces distribution 2.12.2. This avoids adding a dependency to
* Xerces.
*/
private static final String SAX_FEATURE_PREFIX = "http://xml.org/sax/features/";
+
private static final String XERCES_FEATURE_PREFIX = "http://apache.org/xml/features/";
private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = "external-general-entities";
private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = "external-parameter-entities";
@@ -60,22 +61,21 @@ public class SecureXmlParserFactory {
private static final String LOAD_EXTERNAL_DTD_FEATURE = "nonvalidating/load-external-dtd";
private static final String[] ENABLED_PROPERTIES = {
-// XERCES_FEATURE_PREFIX + DISALLOW_DOCTYPE_DECL_FEATURE, - If this feature is activated we cannot parse any XML documents that use a DOCTYPE anymore
- FEATURE_SECURE_PROCESSING
+ // XERCES_FEATURE_PREFIX + DISALLOW_DOCTYPE_DECL_FEATURE, - If this feature is activated we cannot
+ // parse any XML documents that use a DOCTYPE anymore
+ FEATURE_SECURE_PROCESSING
};
private static final String[] DISABLED_PROPERTIES = {
- SAX_FEATURE_PREFIX + EXTERNAL_GENERAL_ENTITIES_FEATURE,
- SAX_FEATURE_PREFIX + EXTERNAL_PARAMETER_ENTITIES_FEATURE,
- SAX_FEATURE_PREFIX + RESOLVE_DTD_URIS_FEATURE,
- SAX_FEATURE_PREFIX + USE_ENTITY_RESOLVER2_FEATURE,
- XERCES_FEATURE_PREFIX + CREATE_ENTITY_REF_NODES_FEATURE,
- XERCES_FEATURE_PREFIX + LOAD_DTD_GRAMMAR_FEATURE,
- XERCES_FEATURE_PREFIX + LOAD_EXTERNAL_DTD_FEATURE
+ SAX_FEATURE_PREFIX + EXTERNAL_GENERAL_ENTITIES_FEATURE,
+ SAX_FEATURE_PREFIX + EXTERNAL_PARAMETER_ENTITIES_FEATURE,
+ SAX_FEATURE_PREFIX + RESOLVE_DTD_URIS_FEATURE,
+ SAX_FEATURE_PREFIX + USE_ENTITY_RESOLVER2_FEATURE,
+ XERCES_FEATURE_PREFIX + CREATE_ENTITY_REF_NODES_FEATURE,
+ XERCES_FEATURE_PREFIX + LOAD_DTD_GRAMMAR_FEATURE,
+ XERCES_FEATURE_PREFIX + LOAD_EXTERNAL_DTD_FEATURE
};
private static final String[] DISABLED_ATTRIBUTES = {
- ACCESS_EXTERNAL_DTD,
- ACCESS_EXTERNAL_SCHEMA,
- ACCESS_EXTERNAL_STYLESHEET
+ ACCESS_EXTERNAL_DTD, ACCESS_EXTERNAL_SCHEMA, ACCESS_EXTERNAL_STYLESHEET
};
private static final String CLEAR_ATTRIBUTE = "";
private static final String SUPPORTING_EXTERNAL_ENTITIES = "javax.xml.stream.isSupportingExternalEntities";
@@ -95,8 +95,7 @@ public DocumentBuilder createDocumentBuilder() {
clearAttributes(factory);
return factory.newDocumentBuilder();
- }
- catch (ParserConfigurationException exception) {
+ } catch (ParserConfigurationException exception) {
throw new IllegalArgumentException("Can't create instance of DocumentBuilder", exception);
}
}
@@ -118,8 +117,7 @@ private void setFeatures(final DocumentBuilderFactory factory) {
private void setFeature(final DocumentBuilderFactory factory, final String enabledProperty, final boolean value) {
try {
factory.setFeature(enabledProperty, value);
- }
- catch (ParserConfigurationException ignored) {
+ } catch (ParserConfigurationException ignored) {
// ignore and continue
}
}
@@ -128,8 +126,7 @@ private void clearAttributes(final DocumentBuilderFactory factory) {
for (String securityAttribute : DISABLED_ATTRIBUTES) {
try {
factory.setAttribute(securityAttribute, CLEAR_ATTRIBUTE);
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ignore and continue
}
}
@@ -139,8 +136,7 @@ private void clearAttributes(final TransformerFactory transformerFactory) {
for (String securityAttribute : DISABLED_ATTRIBUTES) {
try {
transformerFactory.setAttribute(securityAttribute, CLEAR_ATTRIBUTE);
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ignore and continue
}
}
@@ -159,8 +155,7 @@ public SAXParser createSaxParser() {
var parser = factory.newSAXParser();
secureParser(parser);
return parser;
- }
- catch (ParserConfigurationException | SAXException exception) {
+ } catch (ParserConfigurationException | SAXException exception) {
throw new IllegalArgumentException("Can't create instance of SAXParser", exception);
}
}
@@ -173,15 +168,13 @@ SAXParserFactory createSaxParserFactory() {
/**
* Secure the {@link SAXParser} so that it does not resolve external entities.
*
- * @param parser
- * the parser to secure
+ * @param parser the parser to secure
*/
private void secureParser(final SAXParser parser) {
for (String securityAttribute : DISABLED_ATTRIBUTES) {
try {
parser.setProperty(securityAttribute, CLEAR_ATTRIBUTE);
- }
- catch (SAXNotRecognizedException | SAXNotSupportedException e) {
+ } catch (SAXNotRecognizedException | SAXNotSupportedException e) {
// ignore and continue
}
}
@@ -190,8 +183,7 @@ private void secureParser(final SAXParser parser) {
/**
* Configures a {@link SAXParserFactory} so that it does not resolve external entities.
*
- * @param factory
- * the facotry to configure
+ * @param factory the facotry to configure
*/
public void configureSaxParserFactory(final SAXParserFactory factory) {
factory.setValidating(false);
@@ -200,16 +192,14 @@ public void configureSaxParserFactory(final SAXParserFactory factory) {
for (String enabledProperty : ENABLED_PROPERTIES) {
try {
factory.setFeature(enabledProperty, true);
- }
- catch (ParserConfigurationException | SAXException ignored) {
+ } catch (ParserConfigurationException | SAXException ignored) {
// ignore and continue
}
}
for (String disabledProperty : DISABLED_PROPERTIES) {
try {
factory.setFeature(disabledProperty, false);
- }
- catch (ParserConfigurationException | SAXException ignored) {
+ } catch (ParserConfigurationException | SAXException ignored) {
// ignore and continue
}
}
@@ -218,17 +208,14 @@ public void configureSaxParserFactory(final SAXParserFactory factory) {
/**
* Creates a new instance of a {@link XMLStreamReader} that does not resolve external entities.
*
- * @param reader
- * the reader to wrap
- *
+ * @param reader the reader to wrap
* @return a new instance of a {@link XMLStreamReader}
*/
@SuppressFBWarnings(value = "XXE_XMLSTREAMREADER", justification = "The reader is secured in the called method")
public XMLStreamReader createXmlStreamReader(final Reader reader) {
try {
return createSecureInputFactory().createXMLStreamReader(reader);
- }
- catch (XMLStreamException exception) {
+ } catch (XMLStreamException exception) {
throw new IllegalArgumentException("Can't create instance of XMLStreamReader", exception);
}
}
@@ -236,17 +223,14 @@ public XMLStreamReader createXmlStreamReader(final Reader reader) {
/**
* Creates a new instance of a {@link XMLStreamReader} that does not resolve external entities.
*
- * @param reader
- * the reader to wrap
- *
+ * @param reader the reader to wrap
* @return a new instance of a {@link XMLStreamReader}
*/
@SuppressFBWarnings(value = "XXE_XMLSTREAMREADER", justification = "The reader is secured in the called method")
public XMLEventReader createXmlEventReader(final Reader reader) {
try {
return createSecureInputFactory().createXMLEventReader(reader);
- }
- catch (XMLStreamException exception) {
+ } catch (XMLStreamException exception) {
throw new IllegalArgumentException("Can't create instance of XMLEventReader", exception);
}
}
@@ -267,22 +251,16 @@ XMLInputFactory createXmlInputFactory() {
* Creates a {@link SAXParser} that does not resolve external entities and parses the provided content with the
* given SAX {@link DefaultHandler}.
*
- * @param reader
- * the content that should be parsed
- * @param charset
- * the charset to use when reading the content
- * @param handler
- * the SAX handler to parse the file
- *
- * @throws ParsingException
- * if the file could not be parsed
+ * @param reader the content that should be parsed
+ * @param charset the charset to use when reading the content
+ * @param handler the SAX handler to parse the file
+ * @throws ParsingException if the file could not be parsed
*/
@SuppressFBWarnings(value = "XXE_SAXPARSER", justification = "The parser is secured in the called method")
public void parse(final Reader reader, final Charset charset, final DefaultHandler handler) {
try {
createSaxParser().parse(createInputSource(reader, charset), handler);
- }
- catch (SAXException | IOException exception) {
+ } catch (SAXException | IOException exception) {
throw new ParsingException(exception);
}
}
@@ -290,27 +268,25 @@ public void parse(final Reader reader, final Charset charset, final DefaultHandl
/**
* Parses the provided content into a {@link Document}.
*
- * @param reader
- * the content that should be parsed
- * @param charset
- * the charset to use when reading the content
- *
+ * @param reader the content that should be parsed
+ * @param charset the charset to use when reading the content
* @return the file content as a document
- * @throws ParsingException
- * if the file could not be parsed
+ * @throws ParsingException if the file could not be parsed
*/
@SuppressFBWarnings(value = "XXE_DOCUMENT", justification = "The parser is secured in the called method")
public Document readDocument(final Reader reader, final Charset charset) {
try {
return createDocumentBuilder().parse(createInputSource(reader, charset));
- }
- catch (SAXException | IOException exception) {
+ } catch (SAXException | IOException exception) {
throw new ParsingException(exception);
}
}
private InputSource createInputSource(final Reader reader, final Charset charset) throws IOException {
- var inputStream = ReaderInputStream.builder().setReader(reader).setCharset(charset).get();
+ var inputStream = ReaderInputStream.builder()
+ .setReader(reader)
+ .setCharset(charset)
+ .get();
return new InputSource(inputStream);
}
@@ -327,21 +303,20 @@ public Transformer createTransformer() {
clearAttributes(transformerFactory);
return transformerFactory.newTransformer();
- }
- catch (TransformerConfigurationException exception) {
+ } catch (TransformerConfigurationException exception) {
throw new IllegalArgumentException("Can't create instance of Transformer", exception);
}
}
@VisibleForTesting
- @SuppressFBWarnings(value = {"XXE_DTD_TRANSFORM_FACTORY", "XXE_XSLT_TRANSFORM_FACTORY"}, justification = "The transformer is secured in the called method")
+ @SuppressFBWarnings(
+ value = {"XXE_DTD_TRANSFORM_FACTORY", "XXE_XSLT_TRANSFORM_FACTORY"},
+ justification = "The transformer is secured in the called method")
TransformerFactory createTransformerFactory() {
return TransformerFactory.newInstance();
}
- /**
- * Indicates that during parsing a non-recoverable error has been occurred.
- */
+ /** Indicates that during parsing a non-recoverable error has been occurred. */
public static class ParsingException extends RuntimeException {
@Serial
private static final long serialVersionUID = -9016364685084958944L;
@@ -349,8 +324,7 @@ public static class ParsingException extends RuntimeException {
/**
* Constructs a new {@link ParsingException} with the specified cause.
*
- * @param cause
- * the cause (which is saved for later retrieval by the {@link #getCause()} method).
+ * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
*/
public ParsingException(final Throwable cause) {
super(createMessage(cause, "Exception occurred during parsing"), cause);
@@ -359,15 +333,13 @@ public ParsingException(final Throwable cause) {
/**
* Constructs a new {@link ParsingException} with the specified message.
*
- * @param messageFormat
- * the message as a format string as described in Format string
- * syntax
- * @param args
- * Arguments referenced by the format specifiers in the format string. If there are more arguments than
- * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.
- * The maximum number of arguments is limited by the maximum dimension of a Java array as defined by
- * The Java™ Virtual Machine Specification. The behaviour on a {@code null} argument
- * depends on the conversion.
+ * @param messageFormat the message as a format string as described in Format string syntax
+ * @param args Arguments referenced by the format specifiers in the format string. If there are more arguments
+ * than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be
+ * zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by
+ * The Java™ Virtual Machine Specification. The behaviour on a {@code null} argument
+ * depends on the conversion.
*/
@FormatMethod
public ParsingException(final String messageFormat, final Object... args) {
@@ -377,17 +349,14 @@ public ParsingException(final String messageFormat, final Object... args) {
/**
* Constructs a new {@link ParsingException} with the specified cause and message.
*
- * @param cause
- * the cause (which is saved for later retrieval by the {@link #getCause()} method).
- * @param messageFormat
- * the message as a format string as described in Format string
- * syntax
- * @param args
- * Arguments referenced by the format specifiers in the format string. If there are more arguments than
- * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.
- * The maximum number of arguments is limited by the maximum dimension of a Java array as defined by
- * The Java™ Virtual Machine Specification. The behaviour on a {@code null} argument
- * depends on the conversion.
+ * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
+ * @param messageFormat the message as a format string as described in Format string syntax
+ * @param args Arguments referenced by the format specifiers in the format string. If there are more arguments
+ * than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be
+ * zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by
+ * The Java™ Virtual Machine Specification. The behaviour on a {@code null} argument
+ * depends on the conversion.
*/
@FormatMethod
public ParsingException(final Throwable cause, final String messageFormat, final Object... args) {
@@ -395,8 +364,8 @@ public ParsingException(final Throwable cause, final String messageFormat, final
}
private static String createMessage(final Throwable cause, final String message) {
- return "%s%n%s%n%s".formatted(message,
- ExceptionUtils.getMessage(cause), ExceptionUtils.getStackTrace(cause));
+ return "%s%n%s%n%s"
+ .formatted(message, ExceptionUtils.getMessage(cause), ExceptionUtils.getStackTrace(cause));
}
}
}
diff --git a/src/main/java/edu/hm/hafner/util/SuppressMutation.java b/src/main/java/edu/hm/hafner/util/SuppressMutation.java
index 98df17731..6849cb179 100644
--- a/src/main/java/edu/hm/hafner/util/SuppressMutation.java
+++ b/src/main/java/edu/hm/hafner/util/SuppressMutation.java
@@ -1,20 +1,18 @@
package edu.hm.hafner.util;
+import static edu.hm.hafner.util.PitMutator.NONE;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import static edu.hm.hafner.util.PitMutator.*;
-
/**
* Suppresses specific mutations when the feature {@code FANNOT} is enabled in PitMute.
*
- *
- * This annotation can be applied to classes, methods, or constructors. When used without parameters, all mutations in
- * that scope are suppressed. For more information, please see the README in PitMute.
- *
+ * This annotation can be applied to classes, methods, or constructors. When used without parameters, all mutations
+ * in that scope are suppressed. For more information, please see the README in PitMute.
*
* @see PitMute
*/
diff --git a/src/main/java/edu/hm/hafner/util/SuppressMutations.java b/src/main/java/edu/hm/hafner/util/SuppressMutations.java
index 65df4b855..b35c1ade5 100644
--- a/src/main/java/edu/hm/hafner/util/SuppressMutations.java
+++ b/src/main/java/edu/hm/hafner/util/SuppressMutations.java
@@ -5,9 +5,7 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-/**
- * Container annotation for repeating the {@link SuppressMutation} annotation.
- */
+/** Container annotation for repeating the {@link SuppressMutation} annotation. */
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface SuppressMutations {
diff --git a/src/main/java/edu/hm/hafner/util/TreeString.java b/src/main/java/edu/hm/hafner/util/TreeString.java
index 54c60146d..efcc7f538 100644
--- a/src/main/java/edu/hm/hafner/util/TreeString.java
+++ b/src/main/java/edu/hm/hafner/util/TreeString.java
@@ -1,20 +1,16 @@
package edu.hm.hafner.util;
-import org.apache.commons.lang3.StringUtils;
-
import edu.umd.cs.findbugs.annotations.CheckForNull;
-
import java.io.Serial;
import java.io.Serializable;
import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
/**
* {@link TreeString} is an alternative string representation that saves the memory when you have a large number of
* strings that share common prefixes (such as various file names.)
*
- *
- * {@link TreeString} can be built with {@link TreeStringBuilder}.
- *
+ * {@link TreeString} can be built with {@link TreeStringBuilder}.
*
* @author Kohsuke Kawaguchi
*/
@@ -29,9 +25,7 @@ public final class TreeString implements Serializable {
/** {@link #parent} + {@code label} is the string value of this node. */
private char[] label;
- /**
- * Creates a new root {@link TreeString}.
- */
+ /** Creates a new root {@link TreeString}. */
TreeString() {
this(null, "");
}
@@ -39,10 +33,8 @@ public final class TreeString implements Serializable {
/**
* Creates a new {@link TreeString} with the given parent and suffix.
*
- * @param parent
- * the parent
- * @param label
- * the suffix
+ * @param parent the parent
+ * @param label the suffix
*/
@SuppressWarnings("NullAway")
TreeString(@CheckForNull final TreeString parent, final String label) {
@@ -50,7 +42,8 @@ public final class TreeString implements Serializable {
.isTrue("if there's a parent '%s', label '%s' can't be empty", parent, label);
this.parent = parent;
- this.label = label.toCharArray(); // String created as a substring of another string can have a lot of garbage attached to it.
+ this.label = label.toCharArray(); // String created as a substring of another string can have a lot of garbage
+ // attached to it.
}
String getLabel() {
@@ -60,13 +53,9 @@ String getLabel() {
/**
* Inserts a new node between this node and its parent, and returns the newly inserted node.
*
- *
- * This operation doesn't change the string representation of this node.
- *
- *
- * @param prefix
- * the prefix to remove
+ * This operation doesn't change the string representation of this node.
*
+ * @param prefix the prefix to remove
* @return the new node in the middle
*/
@SuppressMutation(mutator = PitMutator.VOID_METHOD_CALLS, justification = "No need to check assertions")
@@ -90,8 +79,8 @@ TreeString getParent() {
}
/**
- * How many nodes do we have from the root to this node (including 'this' itself?). Thus, the depth of
- * the root node is 1.
+ * How many nodes do we have from the root to this node (including 'this' itself?). Thus, the depth of the root node
+ * is 1.
*
* @return the depth
*/
@@ -119,9 +108,7 @@ public int hashCode() {
return toString().hashCode();
}
- /**
- * Returns the full string representation.
- */
+ /** Returns the full string representation. */
@Override
@SuppressWarnings("PMD.AssignmentInOperand")
public String toString() {
@@ -144,16 +131,14 @@ public String toString() {
/**
* Interns {@link #label}.
*
- * @param table
- * the table containing the existing strings
+ * @param table the table containing the existing strings
*/
void dedup(final Map table) {
var l = getLabel();
var v = table.get(l);
if (v == null) {
table.put(l, label);
- }
- else {
+ } else {
label = v;
}
}
@@ -163,12 +148,10 @@ public boolean isBlank() {
}
/**
- * Creates a {@link TreeString}. Useful if you need to create one-off {@link TreeString} without {@link
- * TreeStringBuilder}. Memory consumption is still about the same to {@code new String(string)}.
- *
- * @param string
- * the tree string
+ * Creates a {@link TreeString}. Useful if you need to create one-off {@link TreeString} without
+ * {@link TreeStringBuilder}. Memory consumption is still about the same to {@code new String(string)}.
*
+ * @param string the tree string
* @return the new {@link TreeString}
*/
public static TreeString valueOf(final String string) {
diff --git a/src/main/java/edu/hm/hafner/util/TreeStringBuilder.java b/src/main/java/edu/hm/hafner/util/TreeStringBuilder.java
index 3b16f0f99..d760c18ac 100644
--- a/src/main/java/edu/hm/hafner/util/TreeStringBuilder.java
+++ b/src/main/java/edu/hm/hafner/util/TreeStringBuilder.java
@@ -9,12 +9,10 @@
* {@link TreeString} that represents the same string, but as you intern more strings that share the same prefixes,
* those {@link TreeString}s that you get back start to share data.
*
- *
- * Because the internal state of {@link TreeString}s get mutated as new strings are interned (to exploit new-found
+ *
Because the internal state of {@link TreeString}s get mutated as new strings are interned (to exploit new-found
* common prefixes), {@link TreeString}s returned from {@link #intern(String)} aren't thread-safe until
* {@link TreeStringBuilder} is disposed. That is, you have to make sure other threads don't see those
* {@link TreeString}s until you are done interning strings.
- *
*
* @author Kohsuke Kawaguchi
*/
@@ -31,9 +29,7 @@ private Child getRoot() {
/**
* Interns a string.
*
- * @param string
- * the string to intern
- *
+ * @param string the string to intern
* @return the String as {@link TreeString} instance
*/
public TreeString intern(final String string) {
@@ -43,26 +39,22 @@ public TreeString intern(final String string) {
/**
* Interns a {@link TreeString} created elsewhere.
*
- * @param treeString
- * the {@link TreeString} to intern
- *
+ * @param treeString the {@link TreeString} to intern
* @return the String as {@link TreeString} instance
*/
public TreeString intern(final TreeString treeString) {
return getRoot().intern(treeString.toString()).getNode();
}
- /**
- * Further reduces the memory footprint by finding the same labels across multiple {@link TreeString}s.
- */
- @SuppressMutation(mutator = PitMutator.VOID_METHOD_CALLS, justification = "Memory optimization without visible side effect")
+ /** Further reduces the memory footprint by finding the same labels across multiple {@link TreeString}s. */
+ @SuppressMutation(
+ mutator = PitMutator.VOID_METHOD_CALLS,
+ justification = "Memory optimization without visible side effect")
public void dedup() {
getRoot().dedup(new HashMap<>());
}
- /**
- * Child node that may store other elements.
- */
+ /** Child node that may store other elements. */
private static final class Child {
private final TreeString node;
@@ -75,9 +67,7 @@ private static final class Child {
/**
* Adds one edge and leaf to this tree node, or returns an existing node if any.
*
- * @param string
- * the string to intern
- *
+ * @param string the string to intern
* @return the node
*/
private Child intern(final String string) {
@@ -100,8 +90,7 @@ private Child intern(final String string) {
children.put(prefix, middle);
return middle.intern(string.substring(plen));
- }
- else {
+ } else {
return entry.getValue().intern(string.substring(plen)); // entire key is suffix
}
}
@@ -116,9 +105,7 @@ private Child intern(final String string) {
return t;
}
- /**
- * Makes sure {@link #children} is writable.
- */
+ /** Makes sure {@link #children} is writable. */
@SuppressWarnings("ReferenceEquality")
private void makeWritable() {
if (children == NO_CHILDREN) {
@@ -130,9 +117,7 @@ private void makeWritable() {
* Inserts a new node between this node and its parent and returns that node. The newly inserted 'middle' node
* will have this node as its sole child.
*
- * @param prefix
- * the prefix
- *
+ * @param prefix the prefix
* @return the node
*/
private Child split(final String prefix) {
@@ -148,11 +133,8 @@ private Child split(final String prefix) {
/**
* Returns the common prefix between two strings.
*
- * @param a
- * a string
- * @param b
- * another string
- *
+ * @param a a string
+ * @param b another string
* @return the prefix in characters
*/
private int commonPrefix(final String a, final String b) {
@@ -169,10 +151,11 @@ private int commonPrefix(final String a, final String b) {
/**
* Calls {@link TreeString#dedup(Map)} recursively.
*
- * @param table
- * the table containing the existing strings
+ * @param table the table containing the existing strings
*/
- @SuppressMutation(mutator = PitMutator.VOID_METHOD_CALLS, justification = "Memory optimization without visible side effect")
+ @SuppressMutation(
+ mutator = PitMutator.VOID_METHOD_CALLS,
+ justification = "Memory optimization without visible side effect")
private void dedup(final Map table) {
getNode().dedup(table);
for (Child child : children.values()) {
diff --git a/src/main/java/edu/hm/hafner/util/VisibleForTesting.java b/src/main/java/edu/hm/hafner/util/VisibleForTesting.java
index 1b4d4279c..7782f668e 100644
--- a/src/main/java/edu/hm/hafner/util/VisibleForTesting.java
+++ b/src/main/java/edu/hm/hafner/util/VisibleForTesting.java
@@ -1,10 +1,8 @@
package edu.hm.hafner.util;
/**
- * An annotation that indicates that the visibility of a type or member has
- * been relaxed to make the code testable.
+ * An annotation that indicates that the visibility of a type or member has been relaxed to make the code testable.
*
* @author Johannes Henkel (copied from Google Guava Library)
*/
-public @interface VisibleForTesting {
-}
+public @interface VisibleForTesting {}
diff --git a/src/main/java/edu/hm/hafner/util/package-info.java b/src/main/java/edu/hm/hafner/util/package-info.java
index f609b3258..774456823 100644
--- a/src/main/java/edu/hm/hafner/util/package-info.java
+++ b/src/main/java/edu/hm/hafner/util/package-info.java
@@ -1,6 +1,6 @@
/**
- * Provides highly reusable utility classes and static methods, chiefly concerned
- * with adding value to java.lang, java.util, and other standard core classes.
+ * Provides highly reusable utility classes and static methods, chiefly concerned with adding value to java.lang,
+ * java.util, and other standard core classes.
*
* @author Ullrich Hafner
*/
diff --git a/src/test/java/edu/hm/hafner/archunit/ArchitectureRules.java b/src/test/java/edu/hm/hafner/archunit/ArchitectureRules.java
index 0464ee600..1e40518e1 100644
--- a/src/test/java/edu/hm/hafner/archunit/ArchitectureRules.java
+++ b/src/test/java/edu/hm/hafner/archunit/ArchitectureRules.java
@@ -1,7 +1,11 @@
package edu.hm.hafner.archunit;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
+import static com.tngtech.archunit.core.domain.JavaAccess.Predicates.targetOwner;
+import static com.tngtech.archunit.lang.conditions.ArchConditions.fullyQualifiedName;
+import static com.tngtech.archunit.lang.conditions.ArchPredicates.has;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.fields;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaCall;
@@ -15,16 +19,11 @@
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
-
import edu.hm.hafner.util.VisibleForTesting;
-
import java.io.Serializable;
import java.util.List;
-
-import static com.tngtech.archunit.core.domain.JavaAccess.Predicates.*;
-import static com.tngtech.archunit.lang.conditions.ArchConditions.*;
-import static com.tngtech.archunit.lang.conditions.ArchPredicates.*;
-import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
/**
* Defines several architecture rules that should be enforced in this project.
@@ -33,62 +32,85 @@
*/
public final class ArchitectureRules {
/** No class should have non-private instance fields. */
- public static final ArchRule ONLY_PRIVATE_FIELDS =
- fields().that().doNotHaveModifier(JavaModifier.STATIC)
- .should().bePrivate().allowEmptyShould(true);
+ public static final ArchRule ONLY_PRIVATE_FIELDS = fields().that()
+ .doNotHaveModifier(JavaModifier.STATIC)
+ .should()
+ .bePrivate()
+ .allowEmptyShould(true);
/** Tests should not use fields. Recommendation is to use factory methods for stubs and mocks. */
- public static final ArchRule NO_FIELDS_IN_TESTS =
- fields().that().areDeclaredInClassesThat().haveSimpleNameEndingWith("Test")
- .should().beFinal().andShould().haveModifier(JavaModifier.STATIC)
- .because("use factory methods in favor of instance fields when creating stubs or mocks in tests")
- .allowEmptyShould(true);
+ public static final ArchRule NO_FIELDS_IN_TESTS = fields().that()
+ .areDeclaredInClassesThat()
+ .haveSimpleNameEndingWith("Test")
+ .should()
+ .beFinal()
+ .andShould()
+ .haveModifier(JavaModifier.STATIC)
+ .because("use factory methods in favor of instance fields when creating stubs or mocks in tests")
+ .allowEmptyShould(true);
/** Never create exception without any context. */
- public static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR =
- noClasses().that().haveSimpleNameNotContaining("Benchmark")
- .should().callConstructorWhere(exceptionHasNoContextAsParameter())
- .because("exceptions should include failure-capture information in detail messages (Effective Java Item 75)")
- .allowEmptyShould(true);
+ public static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR = noClasses()
+ .that()
+ .haveSimpleNameNotContaining("Benchmark")
+ .should()
+ .callConstructorWhere(exceptionHasNoContextAsParameter())
+ .because(
+ "exceptions should include failure-capture information in detail messages (Effective Java Item 75)")
+ .allowEmptyShould(true);
/** Junit 5 test classes should not be public. */
- public static final ArchRule NO_PUBLIC_TEST_CLASSES =
- noClasses().that().haveSimpleNameEndingWith("Test")
- .and().haveSimpleNameNotContaining("_jmh")
- .and().doNotHaveModifier(JavaModifier.ABSTRACT)
- .should().bePublic()
- .because("test classes are not part of the API and should be hidden in a package");
+ public static final ArchRule NO_PUBLIC_TEST_CLASSES = noClasses()
+ .that()
+ .haveSimpleNameEndingWith("Test")
+ .and()
+ .haveSimpleNameNotContaining("_jmh")
+ .and()
+ .doNotHaveModifier(JavaModifier.ABSTRACT)
+ .should()
+ .bePublic()
+ .because("test classes are not part of the API and should be hidden in a package");
/** Junit 5 test methods should not be public. */
- public static final ArchRule ONLY_PACKAGE_PRIVATE_TEST_METHODS =
- methods().that().areAnnotatedWith(Test.class)
- .or().areAnnotatedWith(ParameterizedTest.class)
- .and().areDeclaredInClassesThat()
- .haveSimpleNameEndingWith("Test")
- .should().bePackagePrivate()
- .because("test methods are not part of the API and should be hidden in a package");
+ public static final ArchRule ONLY_PACKAGE_PRIVATE_TEST_METHODS = methods()
+ .that()
+ .areAnnotatedWith(Test.class)
+ .or()
+ .areAnnotatedWith(ParameterizedTest.class)
+ .and()
+ .areDeclaredInClassesThat()
+ .haveSimpleNameEndingWith("Test")
+ .should()
+ .bePackagePrivate()
+ .because("test methods are not part of the API and should be hidden in a package");
/** ArchUnit tests should not be public. */
- public static final ArchRule ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS =
- fields().that().areAnnotatedWith(ArchTest.class)
- .should().bePackagePrivate()
- .because("architecture tests are not part of the API and should be hidden in a package")
- .allowEmptyShould(true);
+ public static final ArchRule ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS = fields().that()
+ .areAnnotatedWith(ArchTest.class)
+ .should()
+ .bePackagePrivate()
+ .because("architecture tests are not part of the API and should be hidden in a package")
+ .allowEmptyShould(true);
/**
* Methods or constructors that are annotated with {@link VisibleForTesting} must not be called by other classes.
* These methods are meant to be {@code private}. Only test classes are allowed to call these methods.
*/
- public static final ArchRule NO_TEST_API_CALLED =
- noClasses().that().haveSimpleNameNotEndingWith("Test")
- .and().haveSimpleNameNotContaining("Benchmark")
- .should().callCodeUnitWhere(accessIsRestrictedForTests())
- .because("Production code should never access methods that are marked with @VisibleForTesting")
- .allowEmptyShould(true);
+ public static final ArchRule NO_TEST_API_CALLED = noClasses()
+ .that()
+ .haveSimpleNameNotEndingWith("Test")
+ .and()
+ .haveSimpleNameNotContaining("Benchmark")
+ .should()
+ .callCodeUnitWhere(accessIsRestrictedForTests())
+ .because("Production code should never access methods that are marked with @VisibleForTesting")
+ .allowEmptyShould(true);
/** Prevents that classes use visible but forbidden API. */
- public static final ArchRule NO_FORBIDDEN_PACKAGE_ACCESSED =
- noClasses().should().dependOnClassesThat().resideInAnyPackage(
+ public static final ArchRule NO_FORBIDDEN_PACKAGE_ACCESSED = noClasses()
+ .should()
+ .dependOnClassesThat()
+ .resideInAnyPackage(
"org.apache.commons.lang..",
"org.joda.time..",
"javax.xml.bind..",
@@ -96,45 +118,48 @@ public final class ArchitectureRules {
"junit..",
"org.hamcrest..",
"com.google.common..",
- "org.junit"
- );
+ "org.junit");
/** Prevents that classes use visible but forbidden annotations. */
- public static final ArchRule NO_FORBIDDEN_ANNOTATION_USED =
- noClasses().should()
- .dependOnClassesThat()
- .haveNameMatching("javax.annotation.Check.*")
- .orShould()
- .dependOnClassesThat()
- .haveNameMatching("javax.annotation.Nonnull")
- .orShould()
- .dependOnClassesThat()
- .haveNameMatching("jakarta.annotation.Nullable")
- .orShould()
- .dependOnClassesThat()
- .haveNameMatching("javax.annotation.Nullable")
- .orShould()
- .dependOnClassesThat()
- .haveNameMatching("javax.annotation.Parameters.*")
- .orShould()
- .dependOnClassesThat()
- .haveNameMatching(
- "edu.umd.cs.findbugs.annotations.Nullable") // only CheckForNull and NonNull is allowed
- .because("JSR 305 annotations are forbidden, as well as the Nullable annotation from FindBugs");
+ public static final ArchRule NO_FORBIDDEN_ANNOTATION_USED = noClasses()
+ .should()
+ .dependOnClassesThat()
+ .haveNameMatching("javax.annotation.Check.*")
+ .orShould()
+ .dependOnClassesThat()
+ .haveNameMatching("javax.annotation.Nonnull")
+ .orShould()
+ .dependOnClassesThat()
+ .haveNameMatching("jakarta.annotation.Nullable")
+ .orShould()
+ .dependOnClassesThat()
+ .haveNameMatching("javax.annotation.Nullable")
+ .orShould()
+ .dependOnClassesThat()
+ .haveNameMatching("javax.annotation.Parameters.*")
+ .orShould()
+ .dependOnClassesThat()
+ .haveNameMatching("edu.umd.cs.findbugs.annotations.Nullable") // only CheckForNull and NonNull is allowed
+ .because("JSR 305 annotations are forbidden, as well as the Nullable annotation from FindBugs");
/** Prevents that classes use visible but forbidden API. */
- public static final ArchRule NO_FORBIDDEN_CLASSES_CALLED =
- noClasses().should().callCodeUnitWhere(targetOwner(has(
- fullyQualifiedName("org.junit.jupiter.api.Assertions")
- .or(fullyQualifiedName("org.junit.Assert")))))
- .because("only AssertJ should be used for assertions");
+ public static final ArchRule NO_FORBIDDEN_CLASSES_CALLED = noClasses()
+ .should()
+ .callCodeUnitWhere(targetOwner(has(
+ fullyQualifiedName("org.junit.jupiter.api.Assertions").or(fullyQualifiedName("org.junit.Assert")))))
+ .because("only AssertJ should be used for assertions");
/** Ensures that the {@code readResolve} methods are protected so subclasses can call the parent method. */
- public static final ArchRule READ_RESOLVE_SHOULD_BE_PROTECTED =
- methods().that().haveName("readResolve").and().haveRawReturnType(Object.class)
- .should().beDeclaredInClassesThat().implement(Serializable.class)
- .andShould(beProtected())
- .allowEmptyShould(true);
+ public static final ArchRule READ_RESOLVE_SHOULD_BE_PROTECTED = methods()
+ .that()
+ .haveName("readResolve")
+ .and()
+ .haveRawReturnType(Object.class)
+ .should()
+ .beDeclaredInClassesThat()
+ .implement(Serializable.class)
+ .andShould(beProtected())
+ .allowEmptyShould(true);
private static ExceptionHasNoContext exceptionHasNoContextAsParameter() {
return new ExceptionHasNoContext(IncompatibleClassChangeError.class);
@@ -155,9 +180,10 @@ private static ArchCondition beProtected() {
/**
* Matches if a call from outside the defining class uses a method or constructor annotated with
* {@link VisibleForTesting}. There are two exceptions:
+ *
*
- * - The method is called on the same class
- * - The method is called in a method also annotated with {@link VisibleForTesting}
+ * - The method is called on the same class
+ *
- The method is called in a method also annotated with {@link VisibleForTesting}
*
*/
private static class AccessRestrictedToTests extends DescribedPredicate> {
@@ -177,17 +203,14 @@ private boolean isVisibleForTesting(final CanBeAnnotated target) {
}
}
- /**
- * Matches if an exception has no context, i.e., the constructor is invoked without a message.
- */
+ /** Matches if an exception has no context, i.e., the constructor is invoked without a message. */
private static class ExceptionHasNoContext extends DescribedPredicate {
private final List> allowedExceptions;
/**
* Creates a new predicate.
*
- * @param allowedExceptions
- * exceptions that are allowed to be instantiated without arguments
+ * @param allowedExceptions exceptions that are allowed to be instantiated without arguments
*/
@SafeVarargs
@SuppressWarnings("varargs")
@@ -203,8 +226,7 @@ public boolean test(final JavaConstructorCall javaConstructorCall) {
if (!target.getRawParameterTypes().isEmpty()) {
return false;
}
- return target.getOwner().isAssignableTo(Throwable.class)
- && !isPermittedException(target.getOwner());
+ return target.getOwner().isAssignableTo(Throwable.class) && !isPermittedException(target.getOwner());
}
private boolean isPermittedException(final JavaClass owner) {
@@ -225,9 +247,10 @@ public void check(final JavaMethod method, final ConditionEvents events) {
if (method.getOwner().getModifiers().contains(JavaModifier.FINAL)) {
return;
}
- events.add(SimpleConditionEvent.violated(method,
- "%s is not protected but the class might be extended in %s".formatted(
- method.getDescription(), method.getSourceCodeLocation())));
+ events.add(SimpleConditionEvent.violated(
+ method,
+ "%s is not protected but the class might be extended in %s"
+ .formatted(method.getDescription(), method.getSourceCodeLocation())));
}
}
}
diff --git a/src/test/java/edu/hm/hafner/archunit/ArchitectureRulesTest.java b/src/test/java/edu/hm/hafner/archunit/ArchitectureRulesTest.java
index c8dd74d1f..635ed55ef 100644
--- a/src/test/java/edu/hm/hafner/archunit/ArchitectureRulesTest.java
+++ b/src/test/java/edu/hm/hafner/archunit/ArchitectureRulesTest.java
@@ -1,17 +1,16 @@
package edu.hm.hafner.archunit;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThatNoException;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
-
import edu.hm.hafner.util.Generated;
-
import java.io.Serial;
import java.io.Serializable;
-
-import static org.assertj.core.api.Assertions.*;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* Verifies the architecture rules in {@link ArchitectureRules}.
@@ -23,115 +22,123 @@ class ArchitectureRulesTest {
@Test
void shouldVerifyThatFieldsArePrivate() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.ONLY_PRIVATE_FIELDS.check(importBrokenClass()))
- .withMessageContainingAll(BROKEN_CLASS_NAME, "fields that do not have modifier STATIC should be private' was violated");
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.ONLY_PRIVATE_FIELDS.check(importBrokenClass()))
+ .withMessageContainingAll(
+ BROKEN_CLASS_NAME, "fields that do not have modifier STATIC should be private' was violated");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.ONLY_PRIVATE_FIELDS.check(importPassingClass()));
+ assertThatNoException().isThrownBy(() -> ArchitectureRules.ONLY_PRIVATE_FIELDS.check(importPassingClass()));
}
@Test
void shouldUseProtectedForReadResolve() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.READ_RESOLVE_SHOULD_BE_PROTECTED.check(importBrokenClass()))
- .withMessageContainingAll(BROKEN_CLASS_NAME, "was violated (3 times)",
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.READ_RESOLVE_SHOULD_BE_PROTECTED.check(importBrokenClass()))
+ .withMessageContainingAll(
+ BROKEN_CLASS_NAME,
+ "was violated (3 times)",
"Method is not protected but the class might be extended in (ArchitectureRulesTest.java:",
"Method is not declared in classes that implement java.io.Serializable in (ArchitectureRulesTest.java:",
"Method is not protected but the class might be extended in (ArchitectureRulesTest.java:");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.READ_RESOLVE_SHOULD_BE_PROTECTED.check(importPassingClass()));
+ assertThatNoException()
+ .isThrownBy(() -> ArchitectureRules.READ_RESOLVE_SHOULD_BE_PROTECTED.check(importPassingClass()));
}
@Test
void shouldNotUseJsr305Annotations() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED.check(
- importClasses(ArchitectureRulesViolatedTest.class)))
- .withMessageContainingAll("was violated (3 times)", "edu.umd.cs.findbugs.annotations",
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED.check(
+ importClasses(ArchitectureRulesViolatedTest.class)))
+ .withMessageContainingAll(
+ "was violated (3 times)",
+ "edu.umd.cs.findbugs.annotations",
"Field is annotated with ",
"Method is annotated with ",
"Parameter of method is annotated with ");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED.check(importPassingClass()));
+ assertThatNoException()
+ .isThrownBy(() -> ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED.check(importPassingClass()));
}
@Test
void shouldVerifyThatTestsDoNotUseFields() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.NO_FIELDS_IN_TESTS.check(importBrokenClass()))
- .withMessageContainingAll(BROKEN_CLASS_NAME, "use factory methods in favor of instance fields when creating stubs or mocks in tests");
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.NO_FIELDS_IN_TESTS.check(importBrokenClass()))
+ .withMessageContainingAll(
+ BROKEN_CLASS_NAME,
+ "use factory methods in favor of instance fields when creating stubs or mocks in tests");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.NO_FIELDS_IN_TESTS.check(importPassingClass()));
+ assertThatNoException().isThrownBy(() -> ArchitectureRules.NO_FIELDS_IN_TESTS.check(importPassingClass()));
}
@Test
void shouldVerifyForbiddenAnnotations() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.NO_FORBIDDEN_CLASSES_CALLED.check(importBrokenClass()))
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.NO_FORBIDDEN_CLASSES_CALLED.check(importBrokenClass()))
.withMessageContainingAll(BROKEN_CLASS_NAME, "only AssertJ should be used");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.NO_FORBIDDEN_CLASSES_CALLED.check(importPassingClass()));
+ assertThatNoException()
+ .isThrownBy(() -> ArchitectureRules.NO_FORBIDDEN_CLASSES_CALLED.check(importPassingClass()));
}
@Test
void shouldVerifyExceptionWithNoArgConstructorCalled() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR.check(importBrokenClass()))
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR.check(importBrokenClass()))
.withMessageContainingAll(BROKEN_CLASS_NAME, "(Effective Java Item 75)");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR.check(importPassingClass()));
+ assertThatNoException()
+ .isThrownBy(() -> ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR.check(importPassingClass()));
}
@Test
void shouldVerifyNoPublicTestClassesRule() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.NO_PUBLIC_TEST_CLASSES.check(importBrokenClass()))
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.NO_PUBLIC_TEST_CLASSES.check(importBrokenClass()))
.withMessageContainingAll(BROKEN_CLASS_NAME, "test classes are not part of the API");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.NO_PUBLIC_TEST_CLASSES.check(importPassingClass()));
+ assertThatNoException().isThrownBy(() -> ArchitectureRules.NO_PUBLIC_TEST_CLASSES.check(importPassingClass()));
}
@Test
void shouldVerifyNoPublicTestMethodsRule() {
- assertThatExceptionOfType(AssertionError.class).isThrownBy(
- () -> ArchitectureRules.ONLY_PACKAGE_PRIVATE_TEST_METHODS.check(importBrokenClass()))
+ assertThatExceptionOfType(AssertionError.class)
+ .isThrownBy(() -> ArchitectureRules.ONLY_PACKAGE_PRIVATE_TEST_METHODS.check(importBrokenClass()))
.withMessageContainingAll(BROKEN_CLASS_NAME, "test methods are not part of the API");
- assertThatNoException().isThrownBy(
- () -> ArchitectureRules.ONLY_PACKAGE_PRIVATE_TEST_METHODS.check(importPassingClass()));
+ assertThatNoException()
+ .isThrownBy(() -> ArchitectureRules.ONLY_PACKAGE_PRIVATE_TEST_METHODS.check(importPassingClass()));
}
private JavaClasses importPassingClass() {
- return new ClassFileImporter().importClasses(ArchitectureRulesPassedTest.class,
- ArchitectureRulesAlsoPassedTest.class, ArchitectureRulesPassed.class);
+ return new ClassFileImporter()
+ .importClasses(
+ ArchitectureRulesPassedTest.class,
+ ArchitectureRulesAlsoPassedTest.class,
+ ArchitectureRulesPassed.class);
}
private JavaClasses importBrokenClass() {
- return importClasses(ArchitectureRulesViolatedTest.class,
- ArchitectureRulesAlsoViolatedTest.class);
+ return importClasses(ArchitectureRulesViolatedTest.class, ArchitectureRulesAlsoViolatedTest.class);
}
private JavaClasses importClasses(final Class>... classes) {
return new ClassFileImporter().importClasses(classes);
}
- @SuppressWarnings("all") @Generated // This class is just there to be used in architecture tests
+ @SuppressWarnings("all")
+ @Generated // This class is just there to be used in architecture tests
public static class ArchitectureRulesViolatedTest {
@edu.umd.cs.findbugs.annotations.Nullable
private final String noNullable = null;
int nonPrivate;
- @Test @Disabled("This test is just there to be used in architecture tests")
+ @Test
+ @Disabled("This test is just there to be used in architecture tests")
public void shouldFail() {
- org.junit.jupiter.api.Assertions.assertEquals(1, 1);
+ Assertions.assertEquals(1, 1);
throw new IllegalArgumentException();
}
@@ -151,7 +158,8 @@ private Object readResolve() {
}
}
- @SuppressWarnings("all") @Generated // This class is just there to be used in architecture tests
+ @SuppressWarnings("all")
+ @Generated // This class is just there to be used in architecture tests
public static class ArchitectureRulesAlsoViolatedTest implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@@ -166,12 +174,14 @@ private Object readResolve() {
}
}
- @SuppressWarnings("all") @Generated // This class is just there to be used in architecture tests
+ @SuppressWarnings("all")
+ @Generated // This class is just there to be used in architecture tests
static final class ArchitectureRulesPassedTest implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
- @Test @Disabled("This test is just there to be used in architecture tests")
+ @Test
+ @Disabled("This test is just there to be used in architecture tests")
void shouldPass() {
throw new IllegalArgumentException("context");
}
diff --git a/src/test/java/edu/hm/hafner/archunit/ArchitectureTest.java b/src/test/java/edu/hm/hafner/archunit/ArchitectureTest.java
index a901e76fe..7114850a8 100644
--- a/src/test/java/edu/hm/hafner/archunit/ArchitectureTest.java
+++ b/src/test/java/edu/hm/hafner/archunit/ArchitectureTest.java
@@ -5,7 +5,6 @@
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
-
import edu.hm.hafner.archunit.ArchitectureTest.DoNotIncludeRulesUnderTest;
/**
@@ -13,10 +12,8 @@
*
* @author Ullrich Hafner
*/
-@AnalyzeClasses(packages = "edu.hm.hafner", importOptions = DoNotIncludeRulesUnderTest.class) final class ArchitectureTest {
- private ArchitectureTest() {
- }
-
+@AnalyzeClasses(packages = "edu.hm.hafner", importOptions = DoNotIncludeRulesUnderTest.class)
+class ArchitectureTest {
@ArchTest
static final ArchRule NO_PUBLIC_TEST_CLASSES = ArchitectureRules.NO_PUBLIC_TEST_CLASSES;
@@ -24,7 +21,8 @@ private ArchitectureTest() {
static final ArchRule ONLY_PACKAGE_PRIVATE_TEST_METHODS = ArchitectureRules.ONLY_PACKAGE_PRIVATE_TEST_METHODS;
@ArchTest
- static final ArchRule ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS = ArchitectureRules.ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS;
+ static final ArchRule ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS =
+ ArchitectureRules.ONLY_PACKAGE_PRIVATE_ARCHITECTURE_TESTS;
@ArchTest
static final ArchRule NO_FIELDS_IN_TESTS = ArchitectureRules.NO_FIELDS_IN_TESTS;
@@ -42,7 +40,8 @@ private ArchitectureTest() {
static final ArchRule NO_FORBIDDEN_ANNOTATION_USED = ArchitectureRules.NO_FORBIDDEN_ANNOTATION_USED;
@ArchTest
- static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR = ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR;
+ static final ArchRule NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR =
+ ArchitectureRules.NO_EXCEPTIONS_WITH_NO_ARG_CONSTRUCTOR;
static final class DoNotIncludeRulesUnderTest implements ImportOption {
@Override
diff --git a/src/test/java/edu/hm/hafner/archunit/PackageArchitectureTest.java b/src/test/java/edu/hm/hafner/archunit/PackageArchitectureTest.java
index fbce25e42..63541f7c4 100644
--- a/src/test/java/edu/hm/hafner/archunit/PackageArchitectureTest.java
+++ b/src/test/java/edu/hm/hafner/archunit/PackageArchitectureTest.java
@@ -1,30 +1,28 @@
package edu.hm.hafner.archunit;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
+import static com.tngtech.archunit.library.plantuml.rules.PlantUmlArchCondition.Configuration.consideringOnlyDependenciesInAnyPackage;
+import static com.tngtech.archunit.library.plantuml.rules.PlantUmlArchCondition.adhereToPlantUmlDiagram;
+
import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
-
import java.net.URL;
import java.util.Objects;
-import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
-import static com.tngtech.archunit.library.plantuml.rules.PlantUmlArchCondition.Configuration.*;
-import static com.tngtech.archunit.library.plantuml.rules.PlantUmlArchCondition.*;
-
/**
* Checks the package architecture of this module.
*
* @author Ullrich Hafner
*/
-@AnalyzeClasses(packages = "edu.hm.hafner..", importOptions = DoNotIncludeTests.class) final class PackageArchitectureTest {
+@AnalyzeClasses(packages = "edu.hm.hafner..", importOptions = DoNotIncludeTests.class)
+final class PackageArchitectureTest {
private static final URL PACKAGE_DESIGN = PackageArchitectureTest.class.getResource("/design.puml");
@ArchTest
- static final ArchRule ADHERES_TO_PACKAGE_DESIGN
- = classes().should(adhereToPlantUmlDiagram(Objects.requireNonNull(PACKAGE_DESIGN),
+ static final ArchRule ADHERES_TO_PACKAGE_DESIGN = classes()
+ .should(adhereToPlantUmlDiagram(
+ Objects.requireNonNull(PACKAGE_DESIGN),
consideringOnlyDependenciesInAnyPackage("edu.hm.hafner..")));
-
- private PackageArchitectureTest() {
- }
}
diff --git a/src/test/java/edu/hm/hafner/util/AbstractComparableTest.java b/src/test/java/edu/hm/hafner/util/AbstractComparableTest.java
index 2b582ee1f..56b62107f 100644
--- a/src/test/java/edu/hm/hafner/util/AbstractComparableTest.java
+++ b/src/test/java/edu/hm/hafner/util/AbstractComparableTest.java
@@ -1,8 +1,8 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.*;
+import org.junit.jupiter.api.Test;
/**
* Verifies that comparable objects comply with the contract in {@link Comparable#compareTo(Object)}.
@@ -28,9 +28,7 @@ void shouldBeNegativeIfThisIsSmaller() {
assertThat(greater.compareTo(greater)).isZero();
}
- /**
- * Verifies that {@code sgn(x.compareTo(y)) == -sgn(y.compareTo(x))} for all {@code x} and {@code y}.
- */
+ /** Verifies that {@code sgn(x.compareTo(y)) == -sgn(y.compareTo(x))} for all {@code x} and {@code y}. */
@Test
void shouldBeSymmetric() {
var left = createSmallerSut();
@@ -43,16 +41,16 @@ void shouldBeSymmetric() {
}
/**
- * Creates a subject under test. The SUT must be smaller than the SUT of the opposite method {@link
- * #createGreaterSut()}.
+ * Creates a subject under test. The SUT must be smaller than the SUT of the opposite method
+ * {@link #createGreaterSut()}.
*
* @return the SUT
*/
protected abstract T createSmallerSut();
/**
- * Creates a subject under test. The SUT must be greater than the SUT of the opposite method {@link
- * #createSmallerSut()}.
+ * Creates a subject under test. The SUT must be greater than the SUT of the opposite method
+ * {@link #createSmallerSut()}.
*
* @return the SUT
*/
diff --git a/src/test/java/edu/hm/hafner/util/AbstractEqualsTest.java b/src/test/java/edu/hm/hafner/util/AbstractEqualsTest.java
index d42893af7..d474f9810 100644
--- a/src/test/java/edu/hm/hafner/util/AbstractEqualsTest.java
+++ b/src/test/java/edu/hm/hafner/util/AbstractEqualsTest.java
@@ -1,8 +1,8 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.*;
+import org.junit.jupiter.api.Test;
/**
* Verifies that objects of any Java class comply with the contract in {@link Object#equals(Object)}.
@@ -17,9 +17,7 @@ public abstract class AbstractEqualsTest {
*/
protected abstract Object createSut();
- /**
- * Verifies that for any non-null reference value {@code x}, {@code x.equals(null)} should return {@code false}.
- */
+ /** Verifies that for any non-null reference value {@code x}, {@code x.equals(null)} should return {@code false}. */
@Test
@SuppressWarnings({"PMD.EqualsNull", "checkstyle:equalsavoidnull", "ConstantConditions"})
void shouldReturnFalseOnEqualsNull() {
diff --git a/src/test/java/edu/hm/hafner/util/EnsureTest.java b/src/test/java/edu/hm/hafner/util/EnsureTest.java
index 974c863e6..5ac7da3c7 100644
--- a/src/test/java/edu/hm/hafner/util/EnsureTest.java
+++ b/src/test/java/edu/hm/hafner/util/EnsureTest.java
@@ -1,14 +1,14 @@
package edu.hm.hafner.util;
-import org.assertj.core.util.Lists;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
-
-import static org.assertj.core.api.Assertions.*;
+import org.assertj.core.util.Lists;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link Ensure}.
@@ -19,166 +19,146 @@ class EnsureTest {
private static final String SOME_STRING = "-";
private static final String ERROR_MESSAGE = "assertThatThrownBy Error.";
- /**
- * Checks whether no exception is thrown if we adhere to all contracts.
- */
+ /** Checks whether no exception is thrown if we adhere to all contracts. */
@Test
@SuppressWarnings("checkstyle:LambdaBodyLength")
void shouldNotThrowExceptionIfContractIsValid() {
assertThatCode(() -> {
- Ensure.that(false).isFalse();
- Ensure.that(true).isTrue();
- Ensure.that("").isNotNull();
- Ensure.that("", "").isNotNull();
- Ensure.that(null, (Object) null).isNull();
- Ensure.that(new String[]{""}).isNotEmpty();
- Ensure.that(new String[]{""}).hasSize(1);
- Ensure.that(new String[0]).isEmpty();
- Ensure.that(Path.of("")).isNotEmpty();
- Ensure.that(new String[0]).hasSize(0);
- Ensure.that(SOME_STRING).isNotEmpty();
- Ensure.that(SOME_STRING).isNotBlank();
- Ensure.that("").isInstanceOf(String.class);
- Ensure.that(Set.of()).isEmpty();
- Ensure.that(Set.of("")).isNotEmpty();
- Ensure.that(Set.of("")).hasSize(1);
- Ensure.that(Set.of("")).contains("");
- Ensure.that(Set.of("")).doesNotContain(SOME_STRING);
- }).doesNotThrowAnyException();
+ Ensure.that(false).isFalse();
+ Ensure.that(true).isTrue();
+ Ensure.that("").isNotNull();
+ Ensure.that("", "").isNotNull();
+ Ensure.that(null, (Object) null).isNull();
+ Ensure.that(new String[] {""}).isNotEmpty();
+ Ensure.that(new String[] {""}).hasSize(1);
+ Ensure.that(new String[0]).isEmpty();
+ Ensure.that(Path.of("")).isNotEmpty();
+ Ensure.that(new String[0]).hasSize(0);
+ Ensure.that(SOME_STRING).isNotEmpty();
+ Ensure.that(SOME_STRING).isNotBlank();
+ Ensure.that("").isInstanceOf(String.class);
+ Ensure.that(Set.of()).isEmpty();
+ Ensure.that(Set.of("")).isNotEmpty();
+ Ensure.that(Set.of("")).hasSize(1);
+ Ensure.that(Set.of("")).contains("");
+ Ensure.that(Set.of("")).doesNotContain(SOME_STRING);
+ })
+ .doesNotThrowAnyException();
}
- /**
- * Checks whether we throw an exception if a contract is violated.
- */
+ /** Checks whether we throw an exception if a contract is violated. */
@Test
@SuppressWarnings("Convert2MethodRef")
void shouldThrowExceptionIfContractIsViolated() {
- assertThatThrownBy(() -> Ensure.that(new IllegalArgumentException(ERROR_MESSAGE)).isNeverThrown(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(() -> Ensure.that(true).isFalse())
- .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() ->
+ Ensure.that(new IllegalArgumentException(ERROR_MESSAGE)).isNeverThrown(ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(() -> Ensure.that(true).isFalse()).isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> Ensure.that(true).isFalse(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(() -> Ensure.that(false).isTrue())
- .isInstanceOf(AssertionError.class);
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(() -> Ensure.that(false).isTrue()).isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> Ensure.that(false).isTrue(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(Ensure::thatStatementIsNeverReached)
- .isInstanceOf(AssertionError.class);
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(Ensure::thatStatementIsNeverReached).isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> Ensure.thatStatementIsNeverReached(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(() -> Ensure.that(SOME_STRING).isNull())
- .isInstanceOf(AssertionError.class);
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(() -> Ensure.that(SOME_STRING).isNull()).isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> Ensure.that(SOME_STRING).isNull(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(SOME_STRING, SOME_STRING).isNull(ERROR_MESSAGE))
- .isInstanceOf(AssertionError.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(AssertionError.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(Collections.emptySet()).contains(""))
.isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of("")).contains(SOME_STRING))
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of("")).doesNotContain(""))
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of("")).isEmpty())
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of()).isNotEmpty())
+ assertThatThrownBy(() -> Ensure.that(Set.of("")).contains(SOME_STRING)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Set.of("")).doesNotContain("")).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Set.of("")).isEmpty()).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Set.of()).isNotEmpty()).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Set.of("")).hasSize(0)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Set.of("")).hasSize(2)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(new String[] {"not-empty"}).isEmpty())
.isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of("")).hasSize(0))
+ assertThatThrownBy(() -> Ensure.that(new String[] {"not-empty"}).hasSize(0))
.isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(Set.of("")).hasSize(2))
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(new String[]{"not-empty"}).isEmpty())
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(new String[]{"not-empty"}).hasSize(0))
- .isInstanceOf(AssertionError.class);
- assertThatThrownBy(() -> Ensure.that(new String[]{"not-empty"}).hasSize(2))
+ assertThatThrownBy(() -> Ensure.that(new String[] {"not-empty"}).hasSize(2))
.isInstanceOf(AssertionError.class);
}
- /**
- * Checks whether we throw an exception if a contract is violated.
- */
+ /** Checks whether we throw an exception if a contract is violated. */
@Test
@SuppressWarnings("NullAway")
void shouldThrowNpeIfContractIsViolated() {
assertThatThrownBy(() -> Ensure.that((Object) null).isNotNull(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(SOME_STRING, (Object) null).isNotNull(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(SOME_STRING, (Object[]) null).isNotNull(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(null, SOME_STRING).isNotNull(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that(null, (Object[]) null).isNotNull(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(() -> Ensure.that((Object) null).isNotNull())
- .isInstanceOf(NullPointerException.class);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(() -> Ensure.that((Object) null).isNotNull()).isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> Ensure.that((Collection>) null).isNotNull())
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> Ensure.that((Iterable>) null).isNotNull())
- .isInstanceOf(NullPointerException.class);
+ assertThatThrownBy(() -> Ensure.that((Iterable>) null).isNotNull()).isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> Ensure.that(SOME_STRING, (Object) null).isNotNull())
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> Ensure.that(null, SOME_STRING).isNotNull())
- .isInstanceOf(NullPointerException.class);
+ assertThatThrownBy(() -> Ensure.that(null, SOME_STRING).isNotNull()).isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> Ensure.that(null, (Object[]) null).isNotNull())
.isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> Ensure.that((Object[]) null).isNotEmpty(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
assertThatThrownBy(() -> Ensure.that((String) null).isNotEmpty(ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class).hasMessage(ERROR_MESSAGE);
- assertThatThrownBy(() -> Ensure.that((Object[]) null).isNotEmpty())
- .isInstanceOf(NullPointerException.class);
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage(ERROR_MESSAGE);
+ assertThatThrownBy(() -> Ensure.that((Object[]) null).isNotEmpty()).isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> Ensure.that((Collection>) null).isNotEmpty())
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> Ensure.that((Iterable>) null).isNotEmpty())
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> Ensure.that((String) null).isNotEmpty())
- .isInstanceOf(NullPointerException.class);
+ assertThatThrownBy(() -> Ensure.that((Iterable>) null).isNotEmpty()).isInstanceOf(NullPointerException.class);
+ assertThatThrownBy(() -> Ensure.that((String) null).isNotEmpty()).isInstanceOf(NullPointerException.class);
}
- /**
- * Checks whether we throw an exception if something is empty.
- */
+ /** Checks whether we throw an exception if something is empty. */
@Test
void shouldThrowExceptionIfEmpty() {
- assertThatThrownBy(() ->
- Ensure.that(new String[0]).isNotEmpty(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(Lists.newArrayList("", null, "")).isNotEmpty(ERROR_MESSAGE)).isInstanceOf(
- AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(new String[]{"", null, ""}).isNotEmpty(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that("").isNotEmpty(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(" ").isNotBlank(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that("").isNotBlank(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that("").isInstanceOf(Integer.class, ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(new String[0]).isNotEmpty()).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(Lists.newArrayList("", null, "")).isNotEmpty()).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(new String[]{"", null, ""}).isNotEmpty()).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that("").isNotEmpty()).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that(" ").isNotBlank()).isInstanceOf(AssertionError.class);
- assertThatThrownBy(() ->
- Ensure.that("").isInstanceOf(Integer.class, ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(new String[0]).isNotEmpty(ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Lists.newArrayList("", null, "")).isNotEmpty(ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(new String[] {"", null, ""}).isNotEmpty(ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that("").isNotEmpty(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(" ").isNotBlank(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that("").isNotBlank(ERROR_MESSAGE)).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that("").isInstanceOf(Integer.class, ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(new String[0]).isNotEmpty()).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(Lists.newArrayList("", null, "")).isNotEmpty())
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(new String[] {"", null, ""}).isNotEmpty())
+ .isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that("").isNotEmpty()).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that(" ").isNotBlank()).isInstanceOf(AssertionError.class);
+ assertThatThrownBy(() -> Ensure.that("").isInstanceOf(Integer.class, ERROR_MESSAGE))
+ .isInstanceOf(AssertionError.class);
}
- /**
- * Verifies that the message format is correctly interpreted.
- */
+ /** Verifies that the message format is correctly interpreted. */
@Test
void shouldThrowExceptionWithCorrectMessage() {
- assertThatThrownBy(() ->
- Ensure.that("")
- .isInstanceOf(Integer.class, "'%s' prints %d", "String.format", 42))
+ assertThatThrownBy(() -> Ensure.that("").isInstanceOf(Integer.class, "'%s' prints %d", "String.format", 42))
.isInstanceOf(AssertionError.class)
.hasMessage("'String.format' prints 42");
}
diff --git a/src/test/java/edu/hm/hafner/util/FilteredLogTest.java b/src/test/java/edu/hm/hafner/util/FilteredLogTest.java
index f19c945fb..92777369f 100644
--- a/src/test/java/edu/hm/hafner/util/FilteredLogTest.java
+++ b/src/test/java/edu/hm/hafner/util/FilteredLogTest.java
@@ -1,13 +1,12 @@
package edu.hm.hafner.util;
-import org.apache.commons.lang3.StringUtils;
-import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
-import org.junit.jupiter.api.Test;
+import static edu.hm.hafner.util.assertions.Assertions.assertThat;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
-
-import static edu.hm.hafner.util.assertions.Assertions.*;
+import org.apache.commons.lang3.StringUtils;
+import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link FilteredLog}.
@@ -67,20 +66,23 @@ void shouldSkipAdditionalErrorsWithTitle() {
}
private void verifyFiveErrorMessages(final FilteredLog filteredLog) {
- assertThat(filteredLog).hasErrorMessages(
- "1", "2", "3", "4", "5",
- "java.lang.IllegalStateException: 1",
- "java.lang.IllegalStateException: 2",
- "java.lang.IllegalStateException: 3",
- "java.lang.IllegalStateException: 4",
- "java.lang.IllegalStateException: 5",
- " ... skipped logging of 2 additional errors ...");
-
- assertThat(filteredLog).doesNotHaveErrorMessages(
- "6",
- "java.lang.IllegalStateException: 6",
- "7",
- "java.lang.IllegalStateException: 7");
+ assertThat(filteredLog)
+ .hasErrorMessages(
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "java.lang.IllegalStateException: 1",
+ "java.lang.IllegalStateException: 2",
+ "java.lang.IllegalStateException: 3",
+ "java.lang.IllegalStateException: 4",
+ "java.lang.IllegalStateException: 5",
+ " ... skipped logging of 2 additional errors ...");
+
+ assertThat(filteredLog)
+ .doesNotHaveErrorMessages(
+ "6", "java.lang.IllegalStateException: 6", "7", "java.lang.IllegalStateException: 7");
}
private FilteredLog create5ErrorsLogWithTitle(final String title) {
@@ -112,7 +114,8 @@ void shouldMergeLogger() {
parent.merge(child);
- assertThat(parent).hasOnlyInfoMessages("parent Info 1", "child Info 1")
+ assertThat(parent)
+ .hasOnlyInfoMessages("parent Info 1", "child Info 1")
.hasOnlyErrorMessages("Parent Errors", "parent Error 1", "Child Errors", "child Error 1");
assertThat(parent.size()).isEqualTo(1);
}
@@ -129,7 +132,8 @@ void shouldSkipEmptyErrorLogWhenMerging() {
parent.merge(child);
- assertThat(parent).hasOnlyInfoMessages("parent Info 1", "child Info 1")
+ assertThat(parent)
+ .hasOnlyInfoMessages("parent Info 1", "child Info 1")
.hasOnlyErrorMessages("Child Errors", "child Error 1");
assertThat(parent.size()).isZero();
}
@@ -141,28 +145,30 @@ void shouldLogExceptions() {
filteredLog.logException(new IllegalArgumentException("Cause"), "Message");
filteredLog.logException(new IllegalArgumentException(""), "Message");
- assertThat(filteredLog).hasErrorMessages(TITLE,
- "Message", "java.lang.IllegalArgumentException: Cause");
+ assertThat(filteredLog).hasErrorMessages(TITLE, "Message", "java.lang.IllegalArgumentException: Cause");
}
@Test
void shouldLog20ErrorsByDefault() {
var filteredLog = createLogWith20Elements();
- assertThat(filteredLog.getErrorMessages()).hasSize(22)
+ assertThat(filteredLog.getErrorMessages())
+ .hasSize(22)
.contains(TITLE)
.contains("error19")
.doesNotContain("error20")
.contains(" ... skipped logging of 5 additional errors ...");
- assertThat(filteredLog.getInfoMessages()).hasSize(25)
- .contains("info0")
- .contains("info24");
+ assertThat(filteredLog.getInfoMessages()).hasSize(25).contains("info0").contains("info24");
}
@Override
- protected void assertThatRestoredInstanceEqualsOriginalInstance(final FilteredLog original,
- final FilteredLog restored) {
- assertThat(original).usingRecursiveComparison(RecursiveComparisonConfiguration.builder().withIgnoredFields("lock").build()).isEqualTo(restored);
+ protected void assertThatRestoredInstanceEqualsOriginalInstance(
+ final FilteredLog original, final FilteredLog restored) {
+ assertThat(original)
+ .usingRecursiveComparison(RecursiveComparisonConfiguration.builder()
+ .withIgnoredFields("lock")
+ .build())
+ .isEqualTo(restored);
}
private FilteredLog createLogWith20Elements() {
diff --git a/src/test/java/edu/hm/hafner/util/LineRangeListTest.java b/src/test/java/edu/hm/hafner/util/LineRangeListTest.java
index 2257f5ac1..71ff86492 100644
--- a/src/test/java/edu/hm/hafner/util/LineRangeListTest.java
+++ b/src/test/java/edu/hm/hafner/util/LineRangeListTest.java
@@ -1,10 +1,9 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
-
-import static org.assertj.core.api.Assertions.*;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link LineRangeList}.
diff --git a/src/test/java/edu/hm/hafner/util/LineRangeTest.java b/src/test/java/edu/hm/hafner/util/LineRangeTest.java
index c81d30740..2f9b733e1 100644
--- a/src/test/java/edu/hm/hafner/util/LineRangeTest.java
+++ b/src/test/java/edu/hm/hafner/util/LineRangeTest.java
@@ -1,10 +1,9 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static edu.hm.hafner.util.assertions.Assertions.assertThat;
import nl.jqno.equalsverifier.EqualsVerifier;
-
-import static edu.hm.hafner.util.assertions.Assertions.*;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link LineRangeList}.
@@ -26,23 +25,30 @@ void shouldFindLinesInsideAndOutsideOfLineRange() {
assertThat(lineRange.contains(1)).isTrue();
assertThat(lineRange.contains(2)).isTrue();
assertThat(lineRange.contains(3)).isFalse();
- assertThat(lineRange).hasStart(1).hasEnd(2)
- .hasLines(1, 2).isNotSingleLine().hasToString("[1-2]");
+ assertThat(lineRange)
+ .hasStart(1)
+ .hasEnd(2)
+ .hasLines(1, 2)
+ .isNotSingleLine()
+ .hasToString("[1-2]");
var wrongOrder = new LineRange(2, 1);
assertThat(wrongOrder.contains(0)).isFalse();
assertThat(wrongOrder.contains(1)).isTrue();
assertThat(wrongOrder.contains(2)).isTrue();
assertThat(wrongOrder.contains(3)).isFalse();
- assertThat(wrongOrder).hasStart(1).hasEnd(2)
- .hasLines(1, 2).isNotSingleLine().hasToString("[1-2]");
+ assertThat(wrongOrder)
+ .hasStart(1)
+ .hasEnd(2)
+ .hasLines(1, 2)
+ .isNotSingleLine()
+ .hasToString("[1-2]");
var point = new LineRange(2);
assertThat(point.contains(1)).isFalse();
assertThat(point.contains(2)).isTrue();
assertThat(point.contains(3)).isFalse();
- assertThat(point).hasStart(2).hasEnd(2)
- .hasLines(2).isSingleLine().hasToString("[2-2]");
+ assertThat(point).hasStart(2).hasEnd(2).hasLines(2).isSingleLine().hasToString("[2-2]");
}
@Test
diff --git a/src/test/java/edu/hm/hafner/util/LookaheadStreamTest.java b/src/test/java/edu/hm/hafner/util/LookaheadStreamTest.java
index 8535d0816..f476871a7 100644
--- a/src/test/java/edu/hm/hafner/util/LookaheadStreamTest.java
+++ b/src/test/java/edu/hm/hafner/util/LookaheadStreamTest.java
@@ -1,13 +1,14 @@
package edu.hm.hafner.util;
-import org.apache.commons.lang3.StringUtils;
-import org.junit.jupiter.api.Test;
+import static edu.hm.hafner.util.assertions.Assertions.assertThat;
+import static edu.hm.hafner.util.assertions.Assertions.assertThatExceptionOfType;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
-
-import static edu.hm.hafner.util.assertions.Assertions.*;
-import static org.mockito.Mockito.*;
+import org.apache.commons.lang3.StringUtils;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link LookaheadStream}.
diff --git a/src/test/java/edu/hm/hafner/util/PackageDetectorRunnerTest.java b/src/test/java/edu/hm/hafner/util/PackageDetectorRunnerTest.java
index 4fe143af5..ead29d223 100644
--- a/src/test/java/edu/hm/hafner/util/PackageDetectorRunnerTest.java
+++ b/src/test/java/edu/hm/hafner/util/PackageDetectorRunnerTest.java
@@ -1,18 +1,18 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-import org.junit.jupiter.params.provider.ValueSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import edu.hm.hafner.util.PackageDetectorFactory.FileSystemFacade;
-
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests the class {@link PackageDetectorRunner}.
@@ -22,9 +22,10 @@
class PackageDetectorRunnerTest extends ResourceTest {
@ParameterizedTest(name = "{index} => file={0}, expected package={1}")
@CsvSource({
- "MavenJavaTest.txt.java, hudson.plugins.tasks.util",
- "ActionBinding.cs, Avaloq.SmartClient.Utilities",
- "KotlinTest.txt.kt, edu.hm.kersting"})
+ "MavenJavaTest.txt.java, hudson.plugins.tasks.util",
+ "ActionBinding.cs, Avaloq.SmartClient.Utilities",
+ "KotlinTest.txt.kt, edu.hm.kersting"
+ })
void shouldExtractPackageNames(final String fileName, final String expectedPackage) throws IOException {
assertThat(detect(fileName)).contains(expectedPackage);
}
@@ -57,6 +58,7 @@ void shouldHandleException() throws IOException {
when(fileSystem.openFile(anyString())).thenThrow(new IOException("Simulated"));
assertThat(PackageDetectorFactory.createPackageDetectors(fileSystem)
- .detectPackageName("file.java", StandardCharsets.UTF_8)).isEmpty();
+ .detectPackageName("file.java", StandardCharsets.UTF_8))
+ .isEmpty();
}
}
diff --git a/src/test/java/edu/hm/hafner/util/PathUtilTest.java b/src/test/java/edu/hm/hafner/util/PathUtilTest.java
index 724883551..72bced6ea 100644
--- a/src/test/java/edu/hm/hafner/util/PathUtilTest.java
+++ b/src/test/java/edu/hm/hafner/util/PathUtilTest.java
@@ -1,16 +1,15 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.DisplayName;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assumptions.assumeThat;
import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.assertj.core.api.Assumptions.*;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests the class {@link PathUtil}.
@@ -27,8 +26,7 @@ class PathUtilTest extends ResourceTest {
/**
* Ensures that illegal file names are processed without problems and the test for existence returns {@code false}.
*
- * @param fileName
- * the file name to check
+ * @param fileName the file name to check
*/
@ParameterizedTest(name = "[{index}] Illegal filename = {0}")
@ValueSource(strings = {"/does/not/exist", "\0 Null-Byte", "C:/!<>$&/&( \0", "/!<>$&/&( \0"})
@@ -63,18 +61,33 @@ void shouldFindResourceFolder() {
var pathUtil = new PathUtil();
assertThat(pathUtil.exists(getResourceAsFile(FILE_NAME).toString())).isTrue();
- assertThat(pathUtil.exists(getResourceAsFile(FILE_NAME).getParent().toString())).isTrue();
- assertThat(pathUtil.exists(FILE_NAME, getResourceAsFile(FILE_NAME).getParent().toString())).isTrue();
- assertThat(pathUtil.exists(getResourceAsFile(FILE_NAME).getRoot().toString())).isTrue();
+ assertThat(pathUtil.exists(getResourceAsFile(FILE_NAME).getParent().toString()))
+ .isTrue();
+ assertThat(pathUtil.exists(
+ FILE_NAME, getResourceAsFile(FILE_NAME).getParent().toString()))
+ .isTrue();
+ assertThat(pathUtil.exists(getResourceAsFile(FILE_NAME).getRoot().toString()))
+ .isTrue();
}
@DisplayName("Should verify valid absolute paths")
@ParameterizedTest(name = "[{index}] path={0}")
- @ValueSource(strings = {"/", "/tmp", "C:\\", "c:\\", "C:\\Tmp", "C:/tmp/absolute.txt", "file:///project/src/main/java/com/app/ui/model/Activity.kt"})
+ @ValueSource(
+ strings = {
+ "/",
+ "/tmp",
+ "C:\\",
+ "c:\\",
+ "C:\\Tmp",
+ "C:/tmp/absolute.txt",
+ "file:///project/src/main/java/com/app/ui/model/Activity.kt"
+ })
void shouldFindAbsolutePaths(final String path) {
var pathUtil = new PathUtil();
- assertThat(pathUtil.isAbsolute(path)).as("Show be detected as absolute path").isTrue();
+ assertThat(pathUtil.isAbsolute(path))
+ .as("Show be detected as absolute path")
+ .isTrue();
}
@Test
@@ -112,17 +125,19 @@ void shouldConvertToRelative() {
var absolutePath = getResourceAsFile(FILE_NAME);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent(), FILE_NAME)).isEqualTo(FILE_NAME);
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent(), FILE_NAME))
+ .isEqualTo(FILE_NAME);
assertThat(pathUtil.getRelativePath(FILE_NAME)).isEqualTo(FILE_NAME);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent(), NOT_EXISTING_RELATIVE)).isEqualTo(
- NOT_EXISTING_RELATIVE);
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent(), NOT_EXISTING_RELATIVE))
+ .isEqualTo(NOT_EXISTING_RELATIVE);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(), "util/" + FILE_NAME)).isEqualTo(
- "util/" + FILE_NAME);
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(), "util/" + FILE_NAME))
+ .isEqualTo("util/" + FILE_NAME);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent(), absolutePath.toString())).isEqualTo(FILE_NAME);
- assertThat(pathUtil.getRelativePath(Path.of(NOT_EXISTING), absolutePath.toString())).isEqualTo(
- pathUtil.getAbsolutePath(absolutePath));
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent(), absolutePath.toString()))
+ .isEqualTo(FILE_NAME);
+ assertThat(pathUtil.getRelativePath(Path.of(NOT_EXISTING), absolutePath.toString()))
+ .isEqualTo(pathUtil.getAbsolutePath(absolutePath));
assertThat(pathUtil.getRelativePath(Path.of(NOT_EXISTING), FILE_NAME)).isEqualTo(FILE_NAME);
assertThat(pathUtil.getRelativePath(NOT_EXISTING, FILE_NAME)).isEqualTo(FILE_NAME);
@@ -134,10 +149,10 @@ void shouldConvertNotResolvedToRelative() {
var absolutePath = getResourceAsFile(FILE_NAME);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(), "./util/" + FILE_NAME)).isEqualTo(
- "util/" + FILE_NAME);
- assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(),
- "../hafner/util/" + FILE_NAME)).isEqualTo("util/" + FILE_NAME);
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(), "./util/" + FILE_NAME))
+ .isEqualTo("util/" + FILE_NAME);
+ assertThat(pathUtil.getRelativePath(absolutePath.getParent().getParent(), "../hafner/util/" + FILE_NAME))
+ .isEqualTo("util/" + FILE_NAME);
}
@Test
@@ -171,7 +186,9 @@ void shouldStayInSymbolicLinks() throws IOException {
var real = current.toRealPath();
var realWithSymbolic = current.toRealPath(LinkOption.NOFOLLOW_LINKS);
- assumeThat(real).as("Current working directory path is not based on symbolic links").isNotEqualTo(realWithSymbolic);
+ assumeThat(real)
+ .as("Current working directory path is not based on symbolic links")
+ .isNotEqualTo(realWithSymbolic);
var fromUtil = new PathUtil().getAbsolutePath(current);
var unixStyle = realWithSymbolic.toString().replace('\\', '/');
diff --git a/src/test/java/edu/hm/hafner/util/PrefixLoggerTest.java b/src/test/java/edu/hm/hafner/util/PrefixLoggerTest.java
index f12ea5e0b..c7a1b37c7 100644
--- a/src/test/java/edu/hm/hafner/util/PrefixLoggerTest.java
+++ b/src/test/java/edu/hm/hafner/util/PrefixLoggerTest.java
@@ -1,13 +1,15 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.io.PrintStream;
import java.util.List;
-
-import static java.util.Arrays.*;
-import static java.util.Collections.*;
-import static org.mockito.Mockito.*;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link PrefixLogger}.
diff --git a/src/test/java/edu/hm/hafner/util/ResourceExtractorTest.java b/src/test/java/edu/hm/hafner/util/ResourceExtractorTest.java
index 38a5dab89..9ea3b8d90 100644
--- a/src/test/java/edu/hm/hafner/util/ResourceExtractorTest.java
+++ b/src/test/java/edu/hm/hafner/util/ResourceExtractorTest.java
@@ -1,5 +1,11 @@
package edu.hm.hafner.util;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
@@ -9,14 +15,10 @@
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.NoSuchElementException;
-
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
/**
* Tests the class {@link ResourceExtractor}.
*
@@ -49,8 +51,7 @@ void shouldLocateResourcesInJarFile() {
void shouldExtractFromFolder(@TempDir final Path targetFolder) {
var proxy = new ResourceExtractor(ResourceExtractor.class);
- proxy.extract(targetFolder, ASSERTJ_TEMPLATES, JENKINS_FILE,
- "edu/hm/hafner/util/ResourceExtractor.class");
+ proxy.extract(targetFolder, ASSERTJ_TEMPLATES, JENKINS_FILE, "edu/hm/hafner/util/ResourceExtractor.class");
assertThat(readToString(targetFolder.resolve(ASSERTJ_TEMPLATES)))
.contains("has${Property}(${propertyType} ${property_safe})");
@@ -70,19 +71,18 @@ void shouldThrowExceptionIfTargetIsFileInFolder() throws IOException {
void shouldThrowExceptionIfFileDoesNotExistInFolder(@TempDir final Path targetFolder) {
var proxy = new ResourceExtractor(ResourceExtractor.class);
- assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() ->
- proxy.extract(targetFolder, "does-not-exist"));
+ assertThatExceptionOfType(UncheckedIOException.class)
+ .isThrownBy(() -> proxy.extract(targetFolder, "does-not-exist"));
}
@Test
void shouldExtractFromJar(@TempDir final Path targetFolder) {
var proxy = new ResourceExtractor(StringUtils.class);
- proxy.extract(targetFolder, MANIFEST_MF,
- "org/apache/commons/lang3/StringUtils.class");
+ proxy.extract(targetFolder, MANIFEST_MF, "org/apache/commons/lang3/StringUtils.class");
- assertThat(readToString(targetFolder.resolve(MANIFEST_MF))).contains("Manifest-Version: 1.0",
- "Bundle-SymbolicName: org.apache.commons.lang3");
+ assertThat(readToString(targetFolder.resolve(MANIFEST_MF)))
+ .contains("Manifest-Version: 1.0", "Bundle-SymbolicName: org.apache.commons.lang3");
}
@Test
@@ -97,8 +97,8 @@ void shouldThrowExceptionIfTargetIsFileInJar() throws IOException {
void shouldThrowExceptionIfFileDoesNotExistInJar(@TempDir final Path targetFolder) {
var proxy = new ResourceExtractor(StringUtils.class);
- assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(() ->
- proxy.extract(targetFolder, "does-not-exist"));
+ assertThatExceptionOfType(NoSuchElementException.class)
+ .isThrownBy(() -> proxy.extract(targetFolder, "does-not-exist"));
}
@Test
@@ -131,8 +131,7 @@ void shouldHandleClassloaderProblems() {
private String readToString(final Path output) {
try {
return new String(Files.readAllBytes(output), StandardCharsets.UTF_8);
- }
- catch (IOException exception) {
+ } catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
diff --git a/src/test/java/edu/hm/hafner/util/ResourceTest.java b/src/test/java/edu/hm/hafner/util/ResourceTest.java
index da6647d6f..9c27501cd 100644
--- a/src/test/java/edu/hm/hafner/util/ResourceTest.java
+++ b/src/test/java/edu/hm/hafner/util/ResourceTest.java
@@ -1,11 +1,8 @@
package edu.hm.hafner.util;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.input.BOMInputStream;
-import org.opentest4j.TestAbortedException;
+import static org.assertj.core.api.Assumptions.assumeThat;
import com.google.errorprone.annotations.MustBeClosed;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
@@ -17,8 +14,9 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
-
-import static org.assertj.core.api.Assumptions.*;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.input.BOMInputStream;
+import org.opentest4j.TestAbortedException;
/**
* Base class for tests that need to read resource files from disk. Provides several useful methods that simplify
@@ -37,18 +35,15 @@ protected boolean isWindows() {
}
/**
- * Creates an empty file in the default temporary-file directory, using
- * the prefix and suffix "test" to generate its name. The resulting {@code
- * Path} is associated with the default {@code FileSystem}.
+ * Creates an empty file in the default temporary-file directory, using the prefix and suffix "test" to generate its
+ * name. The resulting {@code Path} is associated with the default {@code FileSystem}.
*
- * @return the path to the newly created file that did not exist before
- * this method was invoked
+ * @return the path to the newly created file that did not exist before this method was invoked
*/
protected Path createTempFile() {
try {
return Files.createTempFile("test", ".test");
- }
- catch (IOException | IllegalArgumentException | UnsupportedOperationException | SecurityException exception) {
+ } catch (IOException | IllegalArgumentException | UnsupportedOperationException | SecurityException exception) {
throw new AssertionError(exception);
}
}
@@ -57,14 +52,10 @@ protected Path createTempFile() {
* Reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an
* I/O error, or other runtime exception, is thrown.
*
- *
- * Note that this method is intended for simple cases where it is
- * convenient to read all bytes into a byte array. It is not intended for reading in large files.
- *
- *
- * @param fileName
- * name of the desired resource
+ * Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array.
+ * It is not intended for reading in large files.
*
+ * @param fileName name of the desired resource
* @return the content represented by a byte array
*/
protected byte[] readAllBytes(final String fileName) {
@@ -74,8 +65,7 @@ protected byte[] readAllBytes(final String fileName) {
ensureThatResourceExists(resource, fileName);
return IOUtils.toByteArray(resource);
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new AssertionError("Can't read resource " + fileName, e);
}
}
@@ -84,21 +74,16 @@ protected byte[] readAllBytes(final String fileName) {
* Reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an
* I/O error, or other runtime exception, is thrown.
*
- *
- * Note that this method is intended for simple cases where it is
- * convenient to read all bytes into a byte array. It is not intended for reading in large files.
- *
- *
- * @param path
- * path of the desired resource
+ * Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array.
+ * It is not intended for reading in large files.
*
+ * @param path path of the desired resource
* @return the content represented by a byte array
*/
protected byte[] readAllBytes(final Path path) {
try {
return Files.readAllBytes(path);
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new AssertionError("Can't read resource " + path, e);
}
}
@@ -113,14 +98,10 @@ private Path getPath(final String name) throws URISyntaxException {
* Read all lines from the desired resource as a {@code Stream}, i.e. this method populates lazily as the stream is
* consumed.
*
- *
- * Bytes from the resource are decoded into characters using UTF-8 and the same line terminators as specified by
+ *
Bytes from the resource are decoded into characters using UTF-8 and the same line terminators as specified by
* {@link Files#readAllLines(Path, Charset)} are supported.
- *
- *
- * @param fileName
- * name of the desired resource
*
+ * @param fileName name of the desired resource
* @return the content represented as a {@link Stream} of lines
*/
@MustBeClosed
@@ -132,24 +113,18 @@ protected Stream asStream(final String fileName) {
* Read all lines from the desired resource as a {@code Stream}, i.e. this method populates lazily as the stream is
* consumed.
*
- *
- * Bytes from the resource are decoded into characters using the specified charset and the same line terminators as
- * specified by {@link Files#readAllLines(Path, Charset)} are supported.
- *
- *
- * @param fileName
- * name of the desired resource
- * @param charset
- * the charset to use for decoding
+ * Bytes from the resource are decoded into characters using the specified charset and the same line terminators
+ * as specified by {@link Files#readAllLines(Path, Charset)} are supported.
*
+ * @param fileName name of the desired resource
+ * @param charset the charset to use for decoding
* @return the content represented as a {@link Stream} of lines
*/
@MustBeClosed
protected Stream asStream(final String fileName, final Charset charset) {
try {
return Files.lines(getPath(fileName), charset);
- }
- catch (IOException | URISyntaxException e) {
+ } catch (IOException | URISyntaxException e) {
throw new AssertionError("Can't read resource " + fileName, e);
}
}
@@ -157,9 +132,7 @@ protected Stream asStream(final String fileName, final Charset charset)
/**
* Finds a resource with the given name and returns an input stream with UTF-8 decoding.
*
- * @param fileName
- * name of the desired resource
- *
+ * @param fileName name of the desired resource
* @return the content represented as an {@link InputStream}
*/
protected InputStream asInputStream(final String fileName) {
@@ -188,9 +161,7 @@ protected Class> getTestResourceClass() {
/**
* Finds a resource with the given name and returns the content (decoded with UTF-8) as String.
*
- * @param fileName
- * name of the desired resource
- *
+ * @param fileName name of the desired resource
* @return the content represented as {@link String}
*/
protected String toString(final String fileName) {
@@ -200,9 +171,7 @@ protected String toString(final String fileName) {
/**
* Returns the content of the specified {@link Path} (decoded with UTF-8) as String.
*
- * @param file
- * the desired file
- *
+ * @param file the desired file
* @return the content represented as {@link String}
*/
protected String toString(final Path file) {
@@ -216,9 +185,7 @@ private String createString(final byte[] bytes) {
/**
* Read all lines from the specified text String as a {@code Stream}.
*
- * @param text
- * the text to return as {@link Stream} of lines
- *
+ * @param text the text to return as {@link Stream} of lines
* @return the content represented by a byte array
*/
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
@@ -227,11 +194,9 @@ protected Stream getTextLinesAsStream(final String text) {
}
/**
- * Returns the {@link Path} of the specified resource. The file name must be relative to the test class.
- *
- * @param fileName
- * the file to read (relative to this {@link ResourceTest} class)
+ * Returns the {@link Path} of the specified resource. The file name must be relative to the test class.
*
+ * @param fileName the file to read (relative to this {@link ResourceTest} class)
* @return an {@link BOMInputStream input stream} using character set UTF-8
* @see #getTestResourceClass()
*/
@@ -242,8 +207,7 @@ protected Path getResourceAsFile(final String fileName) {
ensureThatResourceExists(resource, fileName);
return Path.of(resource.toURI());
- }
- catch (URISyntaxException e) {
+ } catch (URISyntaxException e) {
throw new AssertionError("Can't open file " + fileName, e);
}
}
diff --git a/src/test/java/edu/hm/hafner/util/SecureXmlParserFactoryTest.java b/src/test/java/edu/hm/hafner/util/SecureXmlParserFactoryTest.java
index 12428b2f0..b335d6519 100644
--- a/src/test/java/edu/hm/hafner/util/SecureXmlParserFactoryTest.java
+++ b/src/test/java/edu/hm/hafner/util/SecureXmlParserFactoryTest.java
@@ -1,5 +1,18 @@
package edu.hm.hafner.util;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import edu.hm.hafner.util.SecureXmlParserFactory.ParsingException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
@@ -10,16 +23,10 @@
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
-
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
-import edu.hm.hafner.util.SecureXmlParserFactory.ParsingException;
-
-import static org.assertj.core.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
/**
* Tests the class {@link SecureXmlParserFactory}.
*
@@ -54,7 +61,8 @@ void shouldCreateDocumentBuilder() throws ParserConfigurationException {
var brokenDocumentBuilderFactory = createBrokenDocumentBuilderFactory();
when(factory.createDocumentBuilderFactory()).thenReturn(brokenDocumentBuilderFactory);
- assertThatIllegalArgumentException().isThrownBy(factory::createDocumentBuilder)
+ assertThatIllegalArgumentException()
+ .isThrownBy(factory::createDocumentBuilder)
.withMessage("Can't create instance of DocumentBuilder");
}
@@ -73,7 +81,8 @@ void shouldCreateSaxParser() throws ParserConfigurationException, SAXException {
var brokenSaxParserFactory = createBrokenSaxParserFactory();
when(factory.createSaxParserFactory()).thenReturn(brokenSaxParserFactory);
- assertThatIllegalArgumentException().isThrownBy(factory::createSaxParser)
+ assertThatIllegalArgumentException()
+ .isThrownBy(factory::createSaxParser)
.withMessage("Can't create instance of SAXParser");
}
@@ -106,10 +115,11 @@ void shouldParseEmptyDocument() throws SAXException {
void shouldFailWithParsingExceptionIfParsingBrokenDocument() throws SAXException {
var factory = new SecureXmlParserFactory();
- assertThatExceptionOfType(ParsingException.class).isThrownBy(() ->
- factory.parse(createBrokenXmlReader(), StandardCharsets.UTF_8, mock(DefaultHandler.class)));
- assertThatExceptionOfType(ParsingException.class).isThrownBy(() ->
- factory.readDocument(createBrokenXmlReader(), StandardCharsets.UTF_8));
+ assertThatExceptionOfType(ParsingException.class)
+ .isThrownBy(() ->
+ factory.parse(createBrokenXmlReader(), StandardCharsets.UTF_8, mock(DefaultHandler.class)));
+ assertThatExceptionOfType(ParsingException.class)
+ .isThrownBy(() -> factory.readDocument(createBrokenXmlReader(), StandardCharsets.UTF_8));
}
@Test
@@ -121,7 +131,8 @@ void shouldCreateXmlStreamReader() throws XMLStreamException {
var brokenXmlInputFactory = createBrokenXmlInputFactory();
when(factory.createXmlInputFactory()).thenReturn(brokenXmlInputFactory);
- assertThatIllegalArgumentException().isThrownBy(() -> factory.createXmlStreamReader(createEmptyXmlReader()))
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> factory.createXmlStreamReader(createEmptyXmlReader()))
.withMessage("Can't create instance of XMLStreamReader");
}
@@ -134,14 +145,17 @@ void shouldCreateXmlEventReader() throws XMLStreamException {
var brokenXmlInputFactory = createBrokenXmlInputFactory();
when(factory.createXmlInputFactory()).thenReturn(brokenXmlInputFactory);
- assertThatIllegalArgumentException().isThrownBy(() -> factory.createXmlEventReader(createEmptyXmlReader()))
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> factory.createXmlEventReader(createEmptyXmlReader()))
.withMessage("Can't create instance of XMLEventReader");
}
private XMLInputFactory createBrokenXmlInputFactory() throws XMLStreamException {
var xmlInputFactory = mock(XMLInputFactory.class);
- when(xmlInputFactory.createXMLStreamReader((Reader) any())).thenThrow(new XMLStreamException(EXPECTED_EXCEPTION));
- when(xmlInputFactory.createXMLEventReader((Reader) any())).thenThrow(new XMLStreamException(EXPECTED_EXCEPTION));
+ when(xmlInputFactory.createXMLStreamReader((Reader) any()))
+ .thenThrow(new XMLStreamException(EXPECTED_EXCEPTION));
+ when(xmlInputFactory.createXMLEventReader((Reader) any()))
+ .thenThrow(new XMLStreamException(EXPECTED_EXCEPTION));
return xmlInputFactory;
}
@@ -162,7 +176,8 @@ void shouldCreateTransformer() throws TransformerConfigurationException {
var brokenTransformerFactory = createBrokenTransformerFactory();
when(factory.createTransformerFactory()).thenReturn(brokenTransformerFactory);
- assertThatIllegalArgumentException().isThrownBy(factory::createTransformer)
+ assertThatIllegalArgumentException()
+ .isThrownBy(factory::createTransformer)
.withMessage("Can't create instance of Transformer");
}
diff --git a/src/test/java/edu/hm/hafner/util/SerializableTest.java b/src/test/java/edu/hm/hafner/util/SerializableTest.java
index 7c824f17b..299335806 100644
--- a/src/test/java/edu/hm/hafner/util/SerializableTest.java
+++ b/src/test/java/edu/hm/hafner/util/SerializableTest.java
@@ -1,8 +1,6 @@
package edu.hm.hafner.util;
-import org.assertj.core.api.ObjectAssert;
-import org.junit.jupiter.api.DisplayName;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -13,16 +11,15 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
-
-import static org.assertj.core.api.Assertions.*;
+import org.assertj.core.api.ObjectAssert;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
/**
* Base class to test the serialization of instances of {@link Serializable}. Note that the instances under test must
* override equals so that the test case can check the serialized instances for equality.
*
- * @param
- * concrete type of the {@link Serializable} under test
- *
+ * @param concrete type of the {@link Serializable} under test
* @author Ullrich Hafner
*/
public abstract class SerializableTest extends ResourceTest {
@@ -49,8 +46,7 @@ void shouldBeSerializable() {
* Resolves the subject under test from an array of bytes and compares the created instance with the original
* subject under test.
*
- * @param serializedInstance
- * the byte stream of the serializable
+ * @param serializedInstance the byte stream of the serializable
*/
protected void assertThatSerializableCanBeRestoredFrom(final byte... serializedInstance) {
assertThatRestoredInstanceEqualsOriginalInstance(createSerializable(), restore(serializedInstance));
@@ -59,14 +55,12 @@ protected void assertThatSerializableCanBeRestoredFrom(final byte... serializedI
/**
* Asserts that the instance restored from the serialization is equal to the original instance before the
* serialization. By default, the {@link ObjectAssert#usingRecursiveComparison() recursive comparison strategy} of
- * AssertJ is used to compare these instances. If your subject under test overrides
- * {@link Object#equals(Object) equals}, then you should override this method with {@code original.equals(restored)}
- * so the customized equals method will be used.
+ * AssertJ is used to compare these instances. If your subject under test overrides {@link Object#equals(Object)
+ * equals}, then you should override this method with {@code original.equals(restored)} so the customized equals
+ * method will be used.
*
- * @param original
- * the instance before the serialization
- * @param restored
- * the instance restored by the deserialization
+ * @param original the instance before the serialization
+ * @param restored the instance restored by the deserialization
*/
protected void assertThatRestoredInstanceEqualsOriginalInstance(final T original, final T restored) {
assertThat(restored).usingRecursiveComparison().isEqualTo(original);
@@ -75,9 +69,7 @@ protected void assertThatRestoredInstanceEqualsOriginalInstance(final T original
/**
* Deserializes the subject under test from an array of bytes.
*
- * @param serializedInstance
- * the byte stream of the serializable
- *
+ * @param serializedInstance the byte stream of the serializable
* @return the deserialized instance
*/
@SuppressWarnings({"unchecked", "BanSerializableRead"})
@@ -85,8 +77,7 @@ protected T restore(final byte[] serializedInstance) {
try (var inputStream = new ObjectInputStream(new ByteArrayInputStream(serializedInstance))) {
var object = inputStream.readObject();
return (T) object;
- }
- catch (IOException | ClassNotFoundException e) {
+ } catch (IOException | ClassNotFoundException e) {
throw new AssertionError("Can't resolve instance from byte array", e);
}
}
@@ -97,17 +88,14 @@ protected T restore(final byte[] serializedInstance) {
* supertypes are written. Objects referenced by this object are written transitively so that a complete equivalent
* graph of objects can be reconstructed by an ObjectInputStream.
*
- * @param object
- * the object to serialize
- *
+ * @param object the object to serialize
* @return the object serialization
*/
protected byte[] toByteArray(final Serializable object) {
var out = new ByteArrayOutputStream();
try (var stream = new ObjectOutputStream(out)) {
stream.writeObject(object);
- }
- catch (IOException exception) {
+ } catch (IOException exception) {
throw new IllegalStateException("Can't serialize object " + object, exception);
}
return out.toByteArray();
@@ -116,11 +104,9 @@ protected byte[] toByteArray(final Serializable object) {
/**
* Serializes an issue using an {@link ObjectOutputStream } to the file /tmp/serializable.ser.
*
- * @throws IOException
- * if the file could not be created
+ * @throws IOException if the file could not be created
*/
protected void createSerializationFile() throws IOException {
- Files.write(Path.of("/tmp/serializable.ser"), toByteArray(createSerializable()),
- StandardOpenOption.CREATE_NEW);
+ Files.write(Path.of("/tmp/serializable.ser"), toByteArray(createSerializable()), StandardOpenOption.CREATE_NEW);
}
}
diff --git a/src/test/java/edu/hm/hafner/util/StringComparableTest.java b/src/test/java/edu/hm/hafner/util/StringComparableTest.java
index b776e905c..c666dc915 100644
--- a/src/test/java/edu/hm/hafner/util/StringComparableTest.java
+++ b/src/test/java/edu/hm/hafner/util/StringComparableTest.java
@@ -1,8 +1,8 @@
package edu.hm.hafner.util;
/**
- * Example class that shows on how to verify that String instances comply with the contract in {@link
- * Comparable#compareTo(Object)}.
+ * Example class that shows on how to verify that String instances comply with the contract in
+ * {@link Comparable#compareTo(Object)}.
*
* @author Ullrich Hafner
*/
diff --git a/src/test/java/edu/hm/hafner/util/StringEqualsTest.java b/src/test/java/edu/hm/hafner/util/StringEqualsTest.java
index 5db9b4790..f091c69b8 100644
--- a/src/test/java/edu/hm/hafner/util/StringEqualsTest.java
+++ b/src/test/java/edu/hm/hafner/util/StringEqualsTest.java
@@ -1,8 +1,8 @@
package edu.hm.hafner.util;
/**
- * Example class that shows on how to verify that String instances comply with the contract in {@link
- * Object#equals(Object)}.
+ * Example class that shows on how to verify that String instances comply with the contract in
+ * {@link Object#equals(Object)}.
*
* @author Ullrich Hafner
*/
diff --git a/src/test/java/edu/hm/hafner/util/TreeStringBuilderTest.java b/src/test/java/edu/hm/hafner/util/TreeStringBuilderTest.java
index 3cbd4ccc8..26bfcb4ed 100644
--- a/src/test/java/edu/hm/hafner/util/TreeStringBuilderTest.java
+++ b/src/test/java/edu/hm/hafner/util/TreeStringBuilderTest.java
@@ -1,6 +1,7 @@
package edu.hm.hafner.util;
-import org.junit.jupiter.api.Test;
+import static edu.hm.hafner.util.assertions.Assertions.assertThat;
+import static edu.hm.hafner.util.assertions.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.List;
@@ -8,8 +9,7 @@
import java.util.Random;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
-
-import static edu.hm.hafner.util.assertions.Assertions.*;
+import org.junit.jupiter.api.Test;
/**
* Tests the class {@link TreeStringBuilder}.
@@ -78,9 +78,7 @@ void shouldThrowAssertionErrorIfLabelIsEmpty() {
assertThatThrownBy(() -> new TreeString(new TreeString(), "")).isInstanceOf(AssertionError.class);
}
- /**
- * Pseudo random (but deterministic) test.
- */
+ /** Pseudo random (but deterministic) test. */
@Test
void shouldCreateRandomTreeStrings() {
String[] dictionary = {"aa", "b", "aba", "ba"};