Skip to content

Commit

Permalink
pmd fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hgschmie committed Oct 21, 2023
1 parent 09374ab commit 9df87bc
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public final class DatabaseManager implements AutoCloseable {

private static final String PG_DEFAULT_ENCODING = "utf8";

public static final Logger LOG = LoggerFactory.getLogger(DatabaseManager.class);
private static final Logger LOG = LoggerFactory.getLogger(DatabaseManager.class);

private final AtomicBoolean closed = new AtomicBoolean();
private final AtomicBoolean started = new AtomicBoolean();
Expand Down Expand Up @@ -185,6 +185,7 @@ default void start() {
default void close() {
}

@Override
DatabaseInfo get();
}

Expand Down Expand Up @@ -238,8 +239,8 @@ public void run() {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} catch (Throwable t) {
LOG.warn("Caught Throwable in instance provider loop:", t);
} catch (Exception e) {
LOG.warn("Caught exception in instance provider loop:", e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,24 @@
import static de.softwareforge.testing.postgres.embedded.DatabaseInfo.PG_DEFAULT_USER;
import static de.softwareforge.testing.postgres.embedded.EmbeddedUtil.formatDuration;
import static java.lang.String.format;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;

import de.softwareforge.testing.postgres.embedded.ProcessOutputLogger.StreamCapture;

import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -75,7 +79,7 @@ public final class EmbeddedPostgres implements AutoCloseable {
*/
public static final String DEFAULT_POSTGRES_VERSION = "13";

static final String[] LOCALHOST_SERVER_NAMES = new String[]{"localhost"};
static final String[] LOCALHOST_SERVER_NAMES = {"localhost"};

private static final String PG_TEMPLATE_DB = "template1";

Expand All @@ -92,6 +96,7 @@ public final class EmbeddedPostgres implements AutoCloseable {
private static final String PG_STOP_WAIT_SECONDS = "5";
static final String LOCK_FILE_NAME = "epg-lock";

@SuppressWarnings("PMD.ProperLogger")
private final Logger logger;

private final String instanceId;
Expand All @@ -108,7 +113,7 @@ public final class EmbeddedPostgres implements AutoCloseable {
private final ImmutableMap<String, String> connectionProperties;

private final File lockFile;
private volatile FileOutputStream lockStream;
private volatile FileChannel lockChannel;
private volatile FileLock lock;

private final boolean removeDataOnShutdown;
Expand Down Expand Up @@ -306,7 +311,7 @@ public String getPostgresVersion() throws IOException {
version = s.substring(s.lastIndexOf(' ')).trim();

} catch (ExecutionException e) {
throw new IOException(format("Process '%s' failed%n%s", Joiner.on(" ").join(commandAndArgs)), e);
throw new IOException(format("Process '%s' failed%n", Joiner.on(" ").join(commandAndArgs)), e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Expand Down Expand Up @@ -357,16 +362,16 @@ private void boot() throws IOException {


private synchronized void lock() throws IOException {
this.lockStream = new FileOutputStream(this.lockFile);
this.lock = lockStream.getChannel().tryLock();
this.lockChannel = FileChannel.open(this.lockFile.toPath(), CREATE, WRITE, TRUNCATE_EXISTING, DELETE_ON_CLOSE);
this.lock = this.lockChannel.tryLock();
checkState(lock != null, "could not lock %s", lockFile);
}

private synchronized void unlock() throws IOException {
if (lock != null) {
lock.release();
}
Closeables.close(lockStream, true);
Closeables.close(lockChannel, true);
}

private void initDatabase() throws IOException {
Expand Down Expand Up @@ -426,7 +431,7 @@ private List<String> createInitOptions() {

serverConfiguration.forEach((key, value) -> {
initOptions.add("-c");
if (value.length() > 0) {
if (!value.isEmpty()) {
initOptions.add(key + "=" + value);
} else {
initOptions.add(key + "=true");
Expand All @@ -441,7 +446,7 @@ List<String> createInitDbOptions() {
final ImmutableList.Builder<String> localeOptions = ImmutableList.builder();

localeConfiguration.forEach((key, value) -> {
if (value.length() > 0) {
if (!value.isEmpty()) {
localeOptions.add("--" + key + "=" + value);
} else {
localeOptions.add("--" + key);
Expand Down Expand Up @@ -498,7 +503,7 @@ private boolean verifyReady() throws IOException, SQLException {
private Thread newCloserThread() {
final Thread closeThread = new Thread(() -> {
try {
EmbeddedPostgres.this.close();
this.close();
} catch (IOException e) {
logger.trace("while closing instance:", e);
}
Expand Down Expand Up @@ -575,8 +580,8 @@ private void cleanOldDataDirectories(File parentDirectory) {
continue;
}

try (FileOutputStream fos = new FileOutputStream(lockFile);
FileLock lock = fos.getChannel().tryLock()) {
try (FileChannel fileChannel = FileChannel.open(lockFile.toPath(), CREATE, WRITE, TRUNCATE_EXISTING, DELETE_ON_CLOSE);
FileLock lock = fileChannel.tryLock()) {
if (lock != null) {
logger.debug(format("found stale data directory %s", dir));
if (new File(dir, "postmaster.pid").exists()) {
Expand Down Expand Up @@ -621,7 +626,7 @@ private Process spawn(@Nullable String processName, List<String> commandAndArgs,
}

private Stopwatch system(List<String> commandAndArgs, StreamCapture logCapture) throws IOException {
checkArgument(commandAndArgs.size() > 0, "No commandAndArgs given!");
checkArgument(!commandAndArgs.isEmpty(), "No commandAndArgs given!");
String prefix = EmbeddedUtil.getFileBaseName(commandAndArgs.get(0));

Stopwatch watch = Stopwatch.createStarted();
Expand Down Expand Up @@ -664,7 +669,7 @@ public static class Builder {
private ProcessBuilder.Redirect errorRedirector = ProcessBuilder.Redirect.PIPE;
private ProcessBuilder.Redirect outputRedirector = ProcessBuilder.Redirect.PIPE;

private boolean bootInstance;
private final boolean bootInstance;

private Builder(boolean bootInstance) {
this.bootInstance = bootInstance;
Expand Down Expand Up @@ -843,7 +848,7 @@ public Builder setInstallationBaseDirectory(@Nonnull File installationBaseDirect
*/
@Nonnull
public Builder setPort(int port) {
checkState(port > 1023 && port < 65535, "Port %s is not within 1024..65535", port);
checkState(port > 1_023 && port < 65_535, "Port %s is not within 1024..65535", port);
this.port = port;
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,13 @@
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* An {@link EmbeddedPostgresPreparer<DataSource>} that uses the <a href="https://flywaydb.org/">Flyway version control for your database</a> framework to
* migrate a data source to a known state.
*/
public final class FlywayPreparer implements EmbeddedPostgresPreparer<DataSource> {

private static final Logger LOG = LoggerFactory.getLogger(FlywayPreparer.class);

private final ImmutableList.Builder<Consumer<FluentConfiguration>> customizers = ImmutableList.builder();

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
import jakarta.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.CheckForNull;

import com.google.common.hash.Hashing;
import com.google.common.hash.HashingInputStream;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import javax.annotation.CheckForNull;

/**
* Locates a native binary on the Filesystem. If necessary, it should download the binary first from the network.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package de.softwareforge.testing.postgres.embedded;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
Expand All @@ -24,7 +26,6 @@
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import com.google.common.io.Closeables;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
Expand Down Expand Up @@ -83,28 +84,30 @@ public Future<?> getCompletion() {

private class LogRunnable implements Runnable {

private final BufferedReader reader;
private final InputStream inputStream;
private final String name;
private final Consumer<String> consumer;

private LogRunnable(String name, InputStream inputStream, Consumer<String> consumer) {
this.name = name;
this.reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
this.inputStream = inputStream;
this.consumer = consumer;
}

@Override
public void run() {
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
try (InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
try {
reader.lines().forEach(consumer::accept);
} catch (final UncheckedIOException e) {
logger.error("while reading output:", e);
}
} catch (IOException e) {
logger.error("while opening log stream", e);
} finally {
Closeables.closeQuietly(reader);
Thread.currentThread().setName(oldName + " (" + name + ")");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,19 @@
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;

import jakarta.annotation.Nonnull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.Channel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileSystems;
import java.nio.file.Files;
Expand Down Expand Up @@ -114,8 +116,8 @@ public File getLocation() throws IOException {
final File installationExistsFile = new File(installationDirectory, ".exists");

if (!installationExistsFile.exists()) {
try (FileOutputStream lockStream = new FileOutputStream(unpackLockFile);
FileLock unpackLock = lockStream.getChannel().tryLock()) {
try (FileChannel lockChannel = FileChannel.open(unpackLockFile.toPath(), CREATE, WRITE, TRUNCATE_EXISTING, DELETE_ON_CLOSE);
FileLock unpackLock = lockChannel.tryLock()) {
if (unpackLock != null) {
checkState(!installationExistsFile.exists(), "unpack lock acquired but .exists file is present " + installationExistsFile);
LOG.info("extracting archive...");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public final class ZonkyIOPostgresLocator implements NativeBinaryLocator {
private static final String ZONKY_GROUP_ID = "io.zonky.test.postgres";
private static final String ZONKY_ARTIFACT_ID_TEMPLATE = "embedded-postgres-binaries-%s-%s";

public static final Logger LOG = LoggerFactory.getLogger(ZonkyIOPostgresLocator.class);
private static final Logger LOG = LoggerFactory.getLogger(ZonkyIOPostgresLocator.class);

private static final boolean PREFER_NATIVE = Boolean.getBoolean("pg-embedded.prefer-native");

Expand Down Expand Up @@ -145,7 +145,8 @@ public void close() throws IOException {

@Override
public String toString() {
return format("ZonkyIO Stream locator for PostgreSQL (machine: %s os: %s, arch: %s, version: %s)", EmbeddedUtil.OS_ARCH, os, architecture, serverVersion);
return format("ZonkyIO Stream locator for PostgreSQL (machine: %s os: %s, arch: %s, version: %s)",
EmbeddedUtil.OS_ARCH, os, architecture, serverVersion);
}

@Override
Expand Down
Loading

0 comments on commit 9df87bc

Please sign in to comment.