http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/ProcessStreamReader.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessStreamReader.java b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessStreamReader.java index b514c6a..39b900a 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessStreamReader.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessStreamReader.java @@ -14,15 +14,12 @@ */ package org.apache.geode.internal.process; -import java.io.BufferedReader; -import java.io.IOException; +import static org.apache.commons.lang.Validate.isTrue; +import static org.apache.commons.lang.Validate.notNull; + import java.io.InputStream; -import java.io.InputStreamReader; import org.apache.commons.lang.SystemUtils; -import org.apache.logging.log4j.Logger; - -import org.apache.geode.internal.logging.LogService; /** * Reads the output stream of a Process. @@ -30,8 +27,8 @@ import org.apache.geode.internal.logging.LogService; * @since GemFire 7.0 */ public abstract class ProcessStreamReader implements Runnable { - private static final int DEFAULT_PROCESS_OUTPUT_WAIT_TIME_MILLISECONDS = 5000; - private static final Logger logger = LogService.getLogger(); + + private static final int DEFAULT_PROCESS_OUTPUT_WAIT_TIME_MILLIS = 5000; protected final Process process; protected final InputStream inputStream; @@ -40,8 +37,11 @@ public abstract class ProcessStreamReader implements Runnable { private Thread thread; protected ProcessStreamReader(final Builder builder) { + notNull(builder, "Invalid builder '" + builder + "' specified"); + this.process = builder.process; this.inputStream = builder.inputStream; + if (builder.inputListener == null) { this.inputListener = new InputListener() { @Override @@ -59,44 +59,13 @@ public abstract class ProcessStreamReader implements Runnable { } } - @Override - public void run() { - final boolean isDebugEnabled = logger.isDebugEnabled(); - if (isDebugEnabled) { - logger.debug("Running {}", this); - } - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(inputStream)); - String line; - while ((line = reader.readLine()) != null) { - this.inputListener.notifyInputLine(line); - } - } catch (IOException e) { - if (isDebugEnabled) { - logger.debug("Failure reading from buffered input stream: {}", e.getMessage(), e); - } - } finally { - try { - reader.close(); - } catch (IOException e) { - if (isDebugEnabled) { - logger.debug("Failure closing buffered input stream reader: {}", e.getMessage(), e); - } - } - if (isDebugEnabled) { - logger.debug("Terminating {}", this); - } - } - } - public ProcessStreamReader start() { synchronized (this) { - if (this.thread == null) { - this.thread = new Thread(this, createThreadName()); - this.thread.setDaemon(true); - this.thread.start(); - } else if (this.thread.isAlive()) { + if (thread == null) { + thread = new Thread(this, createThreadName()); + thread.setDaemon(true); + thread.start(); + } else if (thread.isAlive()) { throw new IllegalStateException(this + " has already started"); } else { throw new IllegalStateException(this + " was stopped and cannot be restarted"); @@ -107,33 +76,23 @@ public abstract class ProcessStreamReader implements Runnable { public ProcessStreamReader stop() { synchronized (this) { - if (this.thread != null && this.thread.isAlive()) { - this.thread.interrupt(); - } else if (this.thread != null) { - if (logger.isDebugEnabled()) { - logger.debug("{} has already been stopped", this); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("{} has not been started", this); - } + if (thread != null && thread.isAlive()) { + thread.interrupt(); } } return this; } public ProcessStreamReader stopAsync(final long delayMillis) { - Runnable delayedStop = new Runnable() { - @Override - public void run() { - try { - Thread.sleep(delayMillis); - } catch (InterruptedException e) { - } finally { - stop(); - } + Runnable delayedStop = () -> { + try { + Thread.sleep(delayMillis); + } catch (InterruptedException ignored) { + } finally { + stop(); } }; + String threadName = getClass().getSimpleName() + " stopAfterDelay Thread @" + Integer.toHexString(hashCode()); Thread thread = new Thread(delayedStop, threadName); @@ -144,14 +103,14 @@ public abstract class ProcessStreamReader implements Runnable { public boolean isRunning() { synchronized (this) { - if (this.thread != null) { - return this.thread.isAlive(); + if (thread != null) { + return thread.isAlive(); } } return false; } - public void join() throws InterruptedException { + public ProcessStreamReader join() throws InterruptedException { Thread thread; synchronized (this) { thread = this.thread; @@ -159,9 +118,10 @@ public abstract class ProcessStreamReader implements Runnable { if (thread != null) { thread.join(); } + return this; } - public void join(final long millis) throws InterruptedException { + public ProcessStreamReader join(final long millis) throws InterruptedException { Thread thread; synchronized (this) { thread = this.thread; @@ -169,9 +129,10 @@ public abstract class ProcessStreamReader implements Runnable { if (thread != null) { thread.join(millis); } + return this; } - public void join(final long millis, final int nanos) throws InterruptedException { + public ProcessStreamReader join(final long millis, final int nanos) throws InterruptedException { Thread thread; synchronized (this) { thread = this.thread; @@ -179,47 +140,44 @@ public abstract class ProcessStreamReader implements Runnable { if (thread != null) { thread.join(millis, nanos); } + return this; } @Override public String toString() { - final StringBuilder sb = new StringBuilder(getClass().getSimpleName()); + StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append(" Thread").append(" #").append(System.identityHashCode(this)); - sb.append(" alive=").append(isRunning()); // this.thread == null ? false : - // this.thread.isAlive()); - sb.append(" listener=").append(this.inputListener); + sb.append(" alive=").append(isRunning()); + sb.append(" listener=").append(inputListener); return sb.toString(); } private String createThreadName() { - return getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()); + return getClass().getSimpleName() + '@' + Integer.toHexString(hashCode()); } /** * Defines the callback for lines of output found in the stream. */ - public static interface InputListener { - public void notifyInputLine(String line); + public interface InputListener { + void notifyInputLine(final String line); } /** Default ReadingMode is BLOCKING */ - public static enum ReadingMode { - BLOCKING, NON_BLOCKING; - } - - public static String waitAndCaptureProcessStandardOutputStream(final Process process) { - return waitAndCaptureProcessStandardOutputStream(process, - DEFAULT_PROCESS_OUTPUT_WAIT_TIME_MILLISECONDS); + public enum ReadingMode { + BLOCKING, NON_BLOCKING } - public static String waitAndCaptureProcessStandardOutputStream(final Process process, + private static String waitAndCaptureProcessStandardOutputStream(final Process process, final long waitTimeMilliseconds) { + notNull(process, "Invalid process '" + process + "' specified"); + return waitAndCaptureProcessStream(process, process.getInputStream(), waitTimeMilliseconds); } public static String waitAndCaptureProcessStandardErrorStream(final Process process) { return waitAndCaptureProcessStandardErrorStream(process, - DEFAULT_PROCESS_OUTPUT_WAIT_TIME_MILLISECONDS); + DEFAULT_PROCESS_OUTPUT_WAIT_TIME_MILLIS); } public static String waitAndCaptureProcessStandardErrorStream(final Process process, @@ -228,8 +186,8 @@ public abstract class ProcessStreamReader implements Runnable { } private static String waitAndCaptureProcessStream(final Process process, - final InputStream processInputStream, long waitTimeMilliseconds) { - final StringBuffer buffer = new StringBuffer(); + final InputStream processInputStream, final long waitTimeMilliseconds) { + StringBuffer buffer = new StringBuffer(); InputListener inputListener = line -> { buffer.append(line); @@ -242,7 +200,7 @@ public abstract class ProcessStreamReader implements Runnable { try { reader.start(); - final long endTime = (System.currentTimeMillis() + waitTimeMilliseconds); + long endTime = System.currentTimeMillis() + waitTimeMilliseconds; while (System.currentTimeMillis() < endTime) { try { @@ -259,15 +217,16 @@ public abstract class ProcessStreamReader implements Runnable { /** * Builds a ProcessStreamReader. - * + * * @since GemFire 8.2 */ public static class Builder { - protected Process process; - protected InputStream inputStream; - protected InputListener inputListener; - protected long continueReadingMillis = 0; - protected ReadingMode readingMode = ReadingMode.BLOCKING; + + final Process process; + InputStream inputStream; + InputListener inputListener; + long continueReadingMillis = 0; + ReadingMode readingMode = ReadingMode.BLOCKING; public Builder(final Process process) { this.process = process; @@ -297,16 +256,12 @@ public abstract class ProcessStreamReader implements Runnable { } public ProcessStreamReader build() { - if (process == null) { - throw new NullPointerException("process may not be null"); - } - if (inputStream == null) { - throw new NullPointerException("inputStream may not be null"); - } - if (continueReadingMillis < 0) { - throw new IllegalArgumentException("continueReadingMillis must zero or positive"); - } - switch (this.readingMode) { + notNull(process, "Invalid process '" + process + "' specified"); + notNull(inputStream, "Invalid inputStream '" + inputStream + "' specified"); + isTrue(continueReadingMillis >= 0, + "Invalid continueReadingMillis '" + continueReadingMillis + "' specified"); + + switch (readingMode) { case NON_BLOCKING: return new NonBlockingProcessStreamReader(this); default:
http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/ProcessTerminatedAbnormallyException.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessTerminatedAbnormallyException.java b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessTerminatedAbnormallyException.java deleted file mode 100644 index 510353c..0000000 --- a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessTerminatedAbnormallyException.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package org.apache.geode.internal.process; - -import org.apache.geode.GemFireException; - -/** - * The ProcessTerminatedAbnormallyException class is a GemFireException (or RuntimeException) - * indicating that a process terminated abnormally, and it's exit code is captured along with this - * RuntimeException. - * </p> - * - * @see org.apache.geode.GemFireException - * @since GemFire 7.0 - */ -public class ProcessTerminatedAbnormallyException extends GemFireException { - private static final long serialVersionUID = -1181367425266595492L; - private final int exitValue; - - /** - * Constructs an instance of the ProcessTerminatedAbnormallyException class with the given exit - * value of the process. - * </p> - * - * @param exitValue an integer value indicating the exit value of the terminated process. - */ - public ProcessTerminatedAbnormallyException(final int exitValue) { - this.exitValue = exitValue; - } - - /** - * Constructs an instance of the ProcessTerminatedAbnormallyException class with the given exit - * value of the process and a message indicating the reason of the abnormal termination. - * </p> - * - * @param exitValue an integer value indicating the exit value of the terminated process. - * @param message a String indicating the reason the process terminated abnormally. - */ - public ProcessTerminatedAbnormallyException(final int exitValue, final String message) { - super(message); - this.exitValue = exitValue; - } - - /** - * Constructs an instance of the ProcessTerminatedAbnormallyException class with the given exit - * value of the process and a Throwable representing the underlying cause of the process - * termination. - * </p> - * - * @param exitValue an integer value indicating the exit value of the terminated process. - * @param cause a Throwable encapsulating the undelrying cause of the process termination. - */ - public ProcessTerminatedAbnormallyException(final int exitValue, final Throwable cause) { - super(cause); - this.exitValue = exitValue; - } - - /** - * Constructs an instance of the ProcessTerminatedAbnormallyException class with the given exit - * value of the process as well as a message indicating the reason of the abnormal termination - * along with a Throwable representing the underlying cause of the process termination. - * </p> - * - * @param exitValue an integer value indicating the exit value of the terminated process. - * @param message a String indicating the reason the process terminated abnormally. - * @param cause a Throwable encapsulating the undelrying cause of the process termination. - */ - public ProcessTerminatedAbnormallyException(final int exitValue, final String message, - final Throwable cause) { - super(message, cause); - this.exitValue = exitValue; - } - - /** - * Gets the exit value returned by the process when it terminated. - * </p> - * - * @return an integer value indicating the exit value of the terminated process. - */ - public int getExitValue() { - return exitValue; - } - -} http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/ProcessType.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessType.java b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessType.java index b15030d..86f9dc1 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessType.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessType.java @@ -14,6 +14,8 @@ */ package org.apache.geode.internal.process; +import static org.apache.commons.lang.StringUtils.EMPTY; + import org.apache.geode.distributed.internal.DistributionConfig; /** @@ -25,7 +27,7 @@ import org.apache.geode.distributed.internal.DistributionConfig; public enum ProcessType { LOCATOR("LOCATOR", "vf.gf.locator"), SERVER("SERVER", "vf.gf.server"); - public static final String TEST_PREFIX_PROPERTY = + public static final String PROPERTY_TEST_PREFIX = DistributionConfig.GEMFIRE_PREFIX + "test.ProcessType.TEST_PREFIX"; private static final String SUFFIX_PID = "pid"; @@ -36,33 +38,33 @@ public enum ProcessType { private final String name; private final String fileName; - private ProcessType(final String name, final String fileName) { + ProcessType(final String name, final String fileName) { this.name = name; this.fileName = fileName; } public String getPidFileName() { - return new StringBuilder(System.getProperty(TEST_PREFIX_PROPERTY, "")).append(this.fileName) - .append(".").append(SUFFIX_PID).toString(); + return new StringBuilder(System.getProperty(PROPERTY_TEST_PREFIX, EMPTY)).append(fileName) + .append('.').append(SUFFIX_PID).toString(); } public String getStopRequestFileName() { - return new StringBuilder(System.getProperty(TEST_PREFIX_PROPERTY, "")).append(this.fileName) - .append(".").append(SUFFIX_STOP_REQUEST).toString(); + return new StringBuilder(System.getProperty(PROPERTY_TEST_PREFIX, EMPTY)).append(fileName) + .append('.').append(SUFFIX_STOP_REQUEST).toString(); } public String getStatusRequestFileName() { - return new StringBuilder(System.getProperty(TEST_PREFIX_PROPERTY, "")).append(this.fileName) - .append(".").append(SUFFIX_STATUS_REQUEST).toString(); + return new StringBuilder(System.getProperty(PROPERTY_TEST_PREFIX, EMPTY)).append(fileName) + .append('.').append(SUFFIX_STATUS_REQUEST).toString(); } public String getStatusFileName() { - return new StringBuilder(System.getProperty(TEST_PREFIX_PROPERTY, "")).append(this.fileName) - .append(".").append(SUFFIX_STATUS).toString(); + return new StringBuilder(System.getProperty(PROPERTY_TEST_PREFIX, EMPTY)).append(fileName) + .append('.').append(SUFFIX_STATUS).toString(); } @Override public String toString() { - return this.name; + return name; } } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/ProcessUtils.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessUtils.java b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessUtils.java index 3ff74d8..3cf850f 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/process/ProcessUtils.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/ProcessUtils.java @@ -14,14 +14,16 @@ */ package org.apache.geode.internal.process; +import static org.apache.commons.lang.Validate.isTrue; +import static org.apache.commons.lang.Validate.notEmpty; +import static org.apache.commons.lang.Validate.notNull; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.management.ManagementFactory; -import org.apache.geode.internal.util.IOUtils; - /** * Utility operations for processes such as identifying the process id (pid). * @@ -31,7 +33,9 @@ public class ProcessUtils { private static InternalProcessUtils internal = initializeInternalProcessUtils(); - private ProcessUtils() {} + private ProcessUtils() { + // nothing + } /** * Returns the pid for this process. @@ -50,8 +54,11 @@ public class ProcessUtils { * @throws PidUnavailableException if parsing the pid from the RuntimeMXBean name fails */ public static int identifyPid(final String name) throws PidUnavailableException { + notEmpty(name, "Invalid name '" + name + "' specified"); + + try { - final int index = name.indexOf("@"); + final int index = name.indexOf('@'); if (index < 0) { throw new PidUnavailableException("Unable to parse pid from " + name); } @@ -69,6 +76,8 @@ public class ProcessUtils { * @return true if the pid matches a currently running process */ public static boolean isProcessAlive(final int pid) { + isTrue(pid > 0, "Invalid pid '" + pid + "' specified"); + return internal.isProcessAlive(pid); } @@ -80,6 +89,8 @@ public class ProcessUtils { * @return true if the Process is a currently running process */ public static boolean isProcessAlive(final Process process) { + notNull(process, "Invalid process '" + process + "' specified"); + return process.isAlive(); } @@ -91,16 +102,17 @@ public class ProcessUtils { * @return true if the process was terminated by this operation */ public static boolean killProcess(final int pid) { + isTrue(pid > 0, "Invalid pid '" + pid + "' specified"); + return internal.killProcess(pid); } public static int readPid(final File pidFile) throws IOException { - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(pidFile)); + notNull(pidFile, "Invalid pidFile '" + pidFile + "' specified"); + isTrue(pidFile.exists(), "Nonexistent pidFile '" + pidFile + "' specified"); + + try (BufferedReader reader = new BufferedReader(new FileReader(pidFile))) { return Integer.parseInt(reader.readLine()); - } finally { - IOUtils.close(reader); } } @@ -125,40 +137,33 @@ public class ProcessUtils { Class.forName("com.sun.tools.attach.VirtualMachine"); Class.forName("com.sun.tools.attach.VirtualMachineDescriptor"); return new AttachProcessUtils(); - } catch (ClassNotFoundException e) { - // fall through - } catch (LinkageError e) { + } catch (ClassNotFoundException | LinkageError ignored) { // fall through } // 2) try NativeCalls but make sure it doesn't throw UnsupportedOperationException try { - // TODO: get rid of Class.forName usage if NativeCalls always safely loads + // consider getting rid of Class.forName usage if NativeCalls always safely loads Class.forName("org.apache.geode.internal.shared.NativeCalls"); - NativeProcessUtils inst = new NativeProcessUtils(); - boolean result = inst.isProcessAlive(identifyPid()); + NativeProcessUtils nativeProcessUtils = new NativeProcessUtils(); + boolean result = nativeProcessUtils.isProcessAlive(identifyPid()); if (result) { - return inst; + return nativeProcessUtils; } - } catch (ClassNotFoundException e) { - // fall through - } catch (LinkageError e) { - // fall through - } catch (PidUnavailableException e) { - // fall through (log warning??) - } catch (UnsupportedOperationException e) { + } catch (ClassNotFoundException | LinkageError | PidUnavailableException + | UnsupportedOperationException ignored) { // fall through } - // 3) TODO: log warning and then proceed with no-op + // 3) consider logging warning and then proceed with no-op return new InternalProcessUtils() { @Override - public boolean isProcessAlive(int pid) { + public boolean isProcessAlive(final int pid) { return false; } @Override - public boolean killProcess(int pid) { + public boolean killProcess(final int pid) { return false; } @@ -178,12 +183,13 @@ public class ProcessUtils { * Defines the SPI for ProcessUtils */ interface InternalProcessUtils { - public boolean isProcessAlive(int pid); - public boolean killProcess(int pid); + boolean isProcessAlive(final int pid); + + boolean killProcess(final int pid); - public boolean isAvailable(); + boolean isAvailable(); - public boolean isAttachApiAvailable(); + boolean isAttachApiAvailable(); } } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatus.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatus.java b/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatus.java index a207994..ede0bdc 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatus.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatus.java @@ -14,14 +14,15 @@ */ package org.apache.geode.internal.process; +import static org.apache.commons.lang.Validate.notNull; + import org.apache.logging.log4j.Logger; -import org.apache.geode.internal.logging.LogService; import org.apache.geode.i18n.StringId; +import org.apache.geode.internal.logging.LogService; /** * Extracted from LogWriterImpl and changed to static. - * */ public class StartupStatus { private static final Logger logger = LogService.getLogger(); @@ -29,14 +30,21 @@ public class StartupStatus { /** protected by static synchronized */ private static StartupStatusListener listener; + private StartupStatus() { + // do nothing + } + /** * Writes both a message and exception to this writer. If a startup listener is registered, the * message will be written to the listener as well to be reported to a user. - * + * * @since GemFire 7.0 */ - public static synchronized void startup(StringId msgID, Object[] params) { - String message = msgID.toLocalizedString(params); + public static synchronized void startup(final StringId msgId, final Object... params) { + notNull(msgId, "Invalid msgId '" + msgId + "' specified"); + notNull(params, "Invalid params '" + params + "' specified"); + + String message = msgId.toLocalizedString(params); if (listener != null) { listener.setStatus(message); @@ -45,7 +53,7 @@ public class StartupStatus { logger.info(message); } - public static synchronized void setListener(StartupStatusListener listener) { + public static synchronized void setListener(final StartupStatusListener listener) { StartupStatus.listener = listener; } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatusListener.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatusListener.java b/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatusListener.java index 0e3abb7..07a20fc 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatusListener.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/StartupStatusListener.java @@ -24,5 +24,5 @@ public interface StartupStatusListener { * Report the current status of system startup. The status message reported to this method should * already be internationalized. */ - public void setStatus(String status); + void setStatus(final String status); } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/UnableToControlProcessException.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/UnableToControlProcessException.java b/geode-core/src/main/java/org/apache/geode/internal/process/UnableToControlProcessException.java index ac4e4c8..3e8daec 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/process/UnableToControlProcessException.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/UnableToControlProcessException.java @@ -24,23 +24,23 @@ public class UnableToControlProcessException extends Exception { private static final long serialVersionUID = 7579463534993125290L; /** - * Creates a new <code>UnableToControlProcessException</code>. + * Creates a new {@code UnableToControlProcessException}. */ public UnableToControlProcessException(final String message) { super(message); } /** - * Creates a new <code>UnableToControlProcessException</code> that was caused by a given exception + * Creates a new {@code UnableToControlProcessException} that was caused by a given exception */ - public UnableToControlProcessException(final String message, final Throwable thr) { - super(message, thr); + public UnableToControlProcessException(final String message, final Throwable cause) { + super(message, cause); } /** - * Creates a new <code>UnableToControlProcessException</code> that was caused by a given exception + * Creates a new {@code UnableToControlProcessException} that was caused by a given exception */ - public UnableToControlProcessException(final Throwable thr) { - super(thr.getMessage(), thr); + public UnableToControlProcessException(final Throwable cause) { + super(cause.getMessage(), cause); } } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/signal/AbstractSignalNotificationHandler.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/signal/AbstractSignalNotificationHandler.java b/geode-core/src/main/java/org/apache/geode/internal/process/signal/AbstractSignalNotificationHandler.java index 6a44558..2658d5f 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/signal/AbstractSignalNotificationHandler.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/signal/AbstractSignalNotificationHandler.java @@ -12,9 +12,10 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package org.apache.geode.internal.process.signal; +import static org.apache.commons.lang.StringUtils.EMPTY; + import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -25,44 +26,34 @@ import java.util.Set; /** * The AbstractSignalNotificationHandler class... - * </p> - * - * @see org.apache.geode.internal.process.signal.Signal - * @see org.apache.geode.internal.process.signal.SignalEvent - * @see org.apache.geode.internal.process.signal.SignalListener + * * @since GemFire 7.0 */ -@SuppressWarnings("unused") public abstract class AbstractSignalNotificationHandler { - // NOTE use the enumerated type instead... + /** + * @deprecated use the enumerated type instead... + */ @Deprecated protected static final List<String> SIGNAL_NAMES; // Based on Open BSD OS Signals... static { - final String[] SIGNAL_NAMES_ARRAY = - new String[] {"", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "EMT", "FPE", "KILL", "BUS", - "SEGV", "SYS", "PIPE", "ALRM", "TERM", "URG", "STOP", "TSTP", "CONT", "CHLD", "TTIN", - "TTOU", "IO", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "INFO", "USR1", "USR2"}; + String[] SIGNAL_NAMES_ARRAY = new String[] {EMPTY, "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", + "EMT", "FPE", "KILL", "BUS", "SEGV", "SYS", "PIPE", "ALRM", "TERM", "URG", "STOP", "TSTP", + "CONT", "CHLD", "TTIN", "TTOU", "IO", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "INFO", + "USR1", "USR2"}; SIGNAL_NAMES = Collections.unmodifiableList(Arrays.asList(SIGNAL_NAMES_ARRAY)); } - protected static final SignalListener LOGGING_SIGNAL_LISTENER = new SignalListener() { - public void handle(final SignalEvent event) { - System.out.printf("Logging SignalListener Received Signal '%1$s' (%2$d)%n", + private static final SignalListener LOGGING_SIGNAL_LISTENER = + event -> System.out.printf("Logging SignalListener Received Signal '%1$s' (%2$d)%n", event.getSignal().getName(), event.getSignal().getNumber()); - } - }; - protected static final SignalListener NO_OP_SIGNAL_LISTENER = new SignalListener() { - public void handle(final SignalEvent event) { - // no op - } - }; - - // Map used to register SignalListeners with SignalHandlers... + /** + * Map used to register SignalListeners with SignalHandlers... + */ private final Map<Signal, Set<SignalListener>> signalListeners = Collections.synchronizedMap(new HashMap<Signal, Set<SignalListener>>(Signal.values().length)); @@ -80,52 +71,52 @@ public abstract class AbstractSignalNotificationHandler { } } - protected static void assertValidArgument(final boolean valid, final String message, + static void assertValidArgument(final boolean valid, final String message, final Object... arguments) { if (!valid) { throw new IllegalArgumentException(String.format(message, arguments)); } } - public AbstractSignalNotificationHandler() { - for (final Signal signal : Signal.values()) { - signalListeners.put(signal, Collections.synchronizedSet(new HashSet<SignalListener>())); + protected AbstractSignalNotificationHandler() { + for (Signal signal : Signal.values()) { + signalListeners.put(signal, Collections.synchronizedSet(new HashSet<>())); } // NOTE uncomment for debugging purposes... - // registerListener(LOGGING_SIGNAL_LISTENER); + // debug(); } - public boolean hasListeners(final Signal signal) { + boolean hasListeners(final Signal signal) { return !signalListeners.get(signal).isEmpty(); } - public boolean isListening(final SignalListener listener) { + boolean isListening(final SignalListener listener) { boolean registered = false; - for (final Signal signal : Signal.values()) { + for (Signal signal : Signal.values()) { registered |= isListening(listener, signal); } return registered; } - public boolean isListening(final SignalListener listener, final Signal signal) { + boolean isListening(final SignalListener listener, final Signal signal) { assertNotNull(signal, "The signal to determine whether the listener is registered listening for cannot be null!"); return signalListeners.get(signal).contains(listener); } protected void notifyListeners(final SignalEvent event) { - final Set<SignalListener> listeners = signalListeners.get(event.getSignal()); + Set<SignalListener> listeners = signalListeners.get(event.getSignal()); Set<SignalListener> localListeners = Collections.emptySet(); if (listeners != null) { synchronized (listeners) { - localListeners = new HashSet<SignalListener>(listeners); + localListeners = new HashSet<>(listeners); } } - for (final SignalListener listener : localListeners) { + for (SignalListener listener : localListeners) { listener.handle(event); } } @@ -136,14 +127,14 @@ public abstract class AbstractSignalNotificationHandler { boolean registered = false; - for (final Signal signal : Signal.values()) { + for (Signal signal : Signal.values()) { registered |= registerListener(listener, signal); } return registered; } - public boolean registerListener(final SignalListener listener, final Signal signal) { + boolean registerListener(final SignalListener listener, final Signal signal) { assertNotNull(signal, "The signal to register the listener for cannot be null!"); assertNotNull(listener, "The SignalListener being registered to listen for '%1$s' signals cannot be null!", @@ -155,23 +146,23 @@ public abstract class AbstractSignalNotificationHandler { public boolean unregisterListener(final SignalListener listener) { boolean unregistered = false; - for (final Signal signal : Signal.values()) { + for (Signal signal : Signal.values()) { unregistered |= unregisterListener(listener, signal); } return unregistered; } - public boolean unregisterListener(final SignalListener listener, final Signal signal) { + boolean unregisterListener(final SignalListener listener, final Signal signal) { assertNotNull(signal, "The signal from which to unregister the listener cannot be null!"); return signalListeners.get(signal).remove(listener); } - public boolean unregisterListeners(final Signal signal) { + boolean unregisterListeners(final Signal signal) { assertNotNull(signal, "The signal from which to unregister all listeners cannot be null!"); - final Set<SignalListener> listeners = signalListeners.get(signal); + Set<SignalListener> listeners = signalListeners.get(signal); synchronized (listeners) { listeners.clear(); @@ -179,4 +170,10 @@ public abstract class AbstractSignalNotificationHandler { } } + /** + * Do not delete. + */ + private void debug() { + registerListener(LOGGING_SIGNAL_LISTENER); + } } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/signal/Signal.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/signal/Signal.java b/geode-core/src/main/java/org/apache/geode/internal/process/signal/Signal.java index 78b19db..9dfdfef 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/signal/Signal.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/signal/Signal.java @@ -12,17 +12,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package org.apache.geode.internal.process.signal; import org.apache.commons.lang.StringUtils; /** * Signals defined in the enumerated type were based on Open BSD and the IBM JVM... - * </p> - * - * @see org.apache.geode.internal.process.signal.SignalType + * * @since GemFire 7.0 + * * @see <a href= * "http://www.fromdual.com/operating-system-signals">http://www.fromdual.com/operating-system-signals</a> * @see <a href= @@ -30,7 +28,6 @@ import org.apache.commons.lang.StringUtils; * @see <a href= * "http://publib.boulder.ibm.com/infocenter/java7sdk/v7r0/index.jsp?topic=%2Fcom.ibm.java.aix.70.doc%2Fuser%2Fsighand.html">http://publib.boulder.ibm.com/infocenter/java7sdk/v7r0/index.jsp?topic=%2Fcom.ibm.java.aix.70.doc%2Fuser%2Fsighand.html</a> */ -@SuppressWarnings("unused") public enum Signal { SIGHUP(1, "HUP", SignalType.INTERRUPT, "Hang up. JVM exits normally."), SIGINT(2, "INT", SignalType.INTERRUPT, "Interactive attention (CTRL-C). JVM exits normally."), @@ -93,7 +90,7 @@ public enum Signal { } public static Signal valueOfName(final String name) { - for (final Signal signal : values()) { + for (Signal signal : values()) { if (signal.getName().equalsIgnoreCase(name)) { return signal; } @@ -102,16 +99,6 @@ public enum Signal { return null; } - public static Signal valueOfNumber(final int number) { - for (final Signal signal : values()) { - if (signal.getNumber() == number) { - return signal; - } - } - - return null; - } - public String getDescription() { return description; } @@ -132,5 +119,4 @@ public enum Signal { public String toString() { return "SIG".concat(getName()); } - } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalEvent.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalEvent.java b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalEvent.java index 7038337..d012afa 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalEvent.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalEvent.java @@ -12,19 +12,17 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package org.apache.geode.internal.process.signal; import java.util.EventObject; /** * The SignalEvent class... - * </p> - * + * * @see java.util.EventObject + * * @since GemFire 7.0 */ -@SuppressWarnings("unused") public class SignalEvent extends EventObject { private final Signal signal; @@ -36,16 +34,15 @@ public class SignalEvent extends EventObject { } public Signal getSignal() { - return this.signal; + return signal; } @Override public String toString() { - final StringBuilder buffer = new StringBuilder(getClass().getSimpleName()); + StringBuilder buffer = new StringBuilder(getClass().getSimpleName()); buffer.append("{ signal = ").append(getSignal()); buffer.append(", source = ").append(getSource()); buffer.append("}"); return buffer.toString(); } - } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalListener.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalListener.java b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalListener.java index 501b9db..e874480 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalListener.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalListener.java @@ -12,20 +12,18 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package org.apache.geode.internal.process.signal; import java.util.EventListener; /** - * <p> * The SignalListener class... - * </p> - * + * * @see java.util.EventListener + * * @since GemFire 7.0 */ -@SuppressWarnings("unused") public interface SignalListener extends EventListener { + void handle(SignalEvent event); } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalType.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalType.java b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalType.java index 9545dab..f29dc35 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalType.java +++ b/geode-core/src/main/java/org/apache/geode/internal/process/signal/SignalType.java @@ -12,13 +12,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package org.apache.geode.internal.process.signal; /** * The SignalType class... - * </p> - * + * * @since GemFire 7.0 */ public enum SignalType { @@ -38,7 +36,6 @@ public enum SignalType { @Override public String toString() { - return this.description; + return description; } - } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java ---------------------------------------------------------------------- diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java index 9b743c8..8080e3f 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java @@ -35,7 +35,6 @@ import org.apache.geode.internal.OSProcess; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.lang.StringUtils; import org.apache.geode.internal.lang.SystemUtils; -import org.apache.geode.internal.process.ClusterConfigurationNotAvailableException; import org.apache.geode.internal.process.ProcessStreamReader; import org.apache.geode.internal.process.ProcessType; import org.apache.geode.internal.util.IOUtils; @@ -407,8 +406,6 @@ public class StartServerCommand implements GfshCommand { return ResultBuilder.createUserErrorResult(message); } catch (IllegalStateException e) { return ResultBuilder.createUserErrorResult(e.getMessage()); - } catch (ClusterConfigurationNotAvailableException e) { - return ResultBuilder.createShellClientErrorResult(e.getMessage()); } catch (VirtualMachineError e) { SystemFailure.initiateFailure(e); throw e; http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTest.java index 4766653..9b0bedf 100755 --- a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTest.java +++ b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTest.java @@ -14,8 +14,16 @@ */ package org.apache.geode.distributed; -import org.apache.geode.distributed.internal.DistributionConfig; -import org.apache.geode.test.junit.categories.IntegrationTest; +import static org.apache.geode.distributed.AbstractLauncher.loadGemFireProperties; +import static org.apache.geode.distributed.ConfigurationProperties.GROUPS; +import static org.apache.geode.distributed.ConfigurationProperties.NAME; +import static org.apache.geode.distributed.internal.DistributionConfig.GEMFIRE_PREFIX; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.FileWriter; +import java.util.Properties; + import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -23,21 +31,16 @@ import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestName; -import java.io.File; -import java.io.FileWriter; -import java.util.Properties; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.apache.geode.distributed.ConfigurationProperties.*; +import org.apache.geode.test.junit.categories.IntegrationTest; /** - * Integration tests for AbstractLauncher class. These tests require file system I/O. + * Integration tests for {@link AbstractLauncher} that require file system I/O. */ @Category(IntegrationTest.class) public class AbstractLauncherIntegrationTest { - private File gemfirePropertiesFile; - private Properties expectedGemfireProperties; + private File propertiesFile; + private Properties expectedProperties; @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -47,26 +50,20 @@ public class AbstractLauncherIntegrationTest { @Before public void setUp() throws Exception { - this.gemfirePropertiesFile = - this.temporaryFolder.newFile(DistributionConfig.GEMFIRE_PREFIX + "properties"); + propertiesFile = temporaryFolder.newFile(GEMFIRE_PREFIX + "properties"); - this.expectedGemfireProperties = new Properties(); - this.expectedGemfireProperties.setProperty(NAME, "memberOne"); - this.expectedGemfireProperties.setProperty(GROUPS, "groupOne, groupTwo"); - this.expectedGemfireProperties.store(new FileWriter(this.gemfirePropertiesFile, false), - this.testName.getMethodName()); + expectedProperties = new Properties(); + expectedProperties.setProperty(NAME, "memberOne"); + expectedProperties.setProperty(GROUPS, "groupOne, groupTwo"); + expectedProperties.store(new FileWriter(propertiesFile, false), testName.getMethodName()); - assertThat(this.gemfirePropertiesFile).isNotNull(); - assertThat(this.gemfirePropertiesFile.exists()).isTrue(); - assertThat(this.gemfirePropertiesFile.isFile()).isTrue(); + assertThat(propertiesFile).exists().isFile(); } @Test - public void testLoadGemFirePropertiesFromFile() throws Exception { - final Properties actualGemFireProperties = - AbstractLauncher.loadGemFireProperties(this.gemfirePropertiesFile.toURI().toURL()); + public void loadGemFirePropertiesFromFile() throws Exception { + Properties loadedProperties = loadGemFireProperties(propertiesFile.toURI().toURL()); - assertThat(actualGemFireProperties).isNotNull(); - assertThat(actualGemFireProperties).isEqualTo(this.expectedGemfireProperties); + assertThat(loadedProperties).isEqualTo(expectedProperties); } } http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTestCase.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTestCase.java b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTestCase.java deleted file mode 100755 index bf6a854..0000000 --- a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherIntegrationTestCase.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.distributed; - -import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; -import static org.junit.Assert.assertTrue; - -import org.apache.commons.lang.StringUtils; -import org.apache.geode.distributed.internal.DistributionConfig; -import org.apache.geode.distributed.internal.InternalDistributedSystem; -import org.apache.geode.internal.logging.LogService; -import org.apache.geode.internal.process.PidUnavailableException; -import org.apache.geode.internal.process.ProcessStreamReader.InputListener; -import org.apache.geode.internal.process.ProcessUtils; -import org.apache.geode.internal.util.IOUtils; -import org.apache.geode.internal.util.StopWatch; -import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.TestName; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.net.ServerSocket; -import java.nio.file.Files; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @since GemFire 8.0 - */ -public abstract class AbstractLauncherIntegrationTestCase { - protected static final Logger logger = LogService.getLogger(); - - protected static final int WAIT_FOR_PROCESS_TO_DIE_TIMEOUT = 5 * 60 * 1000; // 5 minutes - protected static final int TIMEOUT_MILLISECONDS = WAIT_FOR_PROCESS_TO_DIE_TIMEOUT; - protected static final int WAIT_FOR_FILE_CREATION_TIMEOUT = 10 * 1000; // 10s - protected static final int WAIT_FOR_FILE_DELETION_TIMEOUT = 10 * 1000; // 10s - protected static final int WAIT_FOR_MBEAN_TIMEOUT = 10 * 1000; // 10s - protected static final int INTERVAL_MILLISECONDS = 100; - - private static final String EXPECTED_EXCEPTION_ADD = - "<ExpectedException action=add>{}</ExpectedException>"; - private static final String EXPECTED_EXCEPTION_REMOVE = - "<ExpectedException action=remove>{}</ExpectedException>"; - private static final String EXPECTED_EXCEPTION_MBEAN_NOT_REGISTERED = - "MBean Not Registered In GemFire Domain"; - - protected volatile ServerSocket socket; - - protected volatile File pidFile; - protected volatile File stopRequestFile; - protected volatile File statusRequestFile; - protected volatile File statusFile; - - @Rule - public TestName testName = new TestName(); - - @Rule - public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); - - @Before - public final void setUpAbstractLauncherIntegrationTestCase() throws Exception { - System.setProperty(DistributionConfig.GEMFIRE_PREFIX + MCAST_PORT, Integer.toString(0)); - logger.info(EXPECTED_EXCEPTION_ADD, EXPECTED_EXCEPTION_MBEAN_NOT_REGISTERED); - } - - @After - public final void tearDownAbstractLauncherIntegrationTestCase() throws Exception { - logger.info(EXPECTED_EXCEPTION_REMOVE, EXPECTED_EXCEPTION_MBEAN_NOT_REGISTERED); - if (this.socket != null) { - this.socket.close(); - this.socket = null; - } - delete(this.pidFile); - this.pidFile = null; - delete(this.stopRequestFile); - this.stopRequestFile = null; - delete(this.statusRequestFile); - this.statusRequestFile = null; - delete(this.statusFile); - this.statusFile = null; - } - - protected void delete(final File file) throws Exception { - assertEventuallyTrue("deleting " + file, new Callable<Boolean>() { - @Override - public Boolean call() throws Exception { - if (file == null) { - return true; - } - try { - Files.delete(file.toPath()); - } catch (IOException e) { - } - return !file.exists(); - } - }, WAIT_FOR_FILE_DELETION_TIMEOUT, INTERVAL_MILLISECONDS); - } - - protected void waitForPidToStop(final int pid, boolean throwOnTimeout) throws Exception { - assertEventuallyFalse("Process never died", new Callable<Boolean>() { - @Override - public Boolean call() throws Exception { - return ProcessUtils.isProcessAlive(pid); - } - }, WAIT_FOR_PROCESS_TO_DIE_TIMEOUT, INTERVAL_MILLISECONDS); - } - - protected void waitForPidToStop(final int pid) throws Exception { - waitForPidToStop(pid, true); - } - - protected void waitForFileToDelete(final File file, boolean throwOnTimeout) throws Exception { - if (file == null) { - return; - } - assertEventuallyTrue("waiting for file " + file + " to delete", new Callable<Boolean>() { - @Override - public Boolean call() throws Exception { - return !file.exists(); - } - }, WAIT_FOR_FILE_DELETION_TIMEOUT, INTERVAL_MILLISECONDS); - } - - protected void waitForFileToDelete(final File file) throws Exception { - waitForFileToDelete(file, true); - } - - protected static int getPid() throws PidUnavailableException { - return ProcessUtils.identifyPid(); - } - - protected InputListener createLoggingListener(final String name, final String header) { - return new InputListener() { - @Override - public void notifyInputLine(String line) { - logger.info(new StringBuilder("[").append(header).append("]").append(line).toString()); - } - - @Override - public String toString() { - return name; - } - }; - } - - protected InputListener createCollectionListener(final String name, final String header, - final List<String> lines) { - return new InputListener() { - @Override - public void notifyInputLine(String line) { - lines.add(line); - } - - @Override - public String toString() { - return name; - } - }; - } - - protected InputListener createExpectedListener(final String name, final String header, - final String expected, final AtomicBoolean atomic) { - return new InputListener() { - @Override - public void notifyInputLine(String line) { - if (line.contains(expected)) { - atomic.set(true); - } - } - - @Override - public String toString() { - return name; - } - }; - } - - protected void writeGemfireProperties(final Properties gemfireProperties, - final File gemfirePropertiesFile) throws IOException { - if (!gemfirePropertiesFile.exists()) { - gemfireProperties.store(new FileWriter(gemfirePropertiesFile), - "Configuration settings for the GemFire Server"); - } - } - - protected int readPid(final File pidFile) throws IOException { - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(pidFile)); - return Integer.parseInt(StringUtils.trim(reader.readLine())); - } finally { - IOUtils.close(reader); - } - } - - protected void writePid(final File pidFile, final int pid) throws IOException { - FileWriter writer = new FileWriter(pidFile); - writer.write(String.valueOf(pid)); - writer.write("\n"); - writer.flush(); - writer.close(); - } - - protected void waitForFileToExist(final File file, boolean throwOnTimeout) throws Exception { - assertEventuallyTrue("waiting for file " + file + " to exist", new Callable<Boolean>() { - @Override - public Boolean call() throws Exception { - return file.exists(); - } - }, WAIT_FOR_FILE_CREATION_TIMEOUT, INTERVAL_MILLISECONDS); - } - - protected void waitForFileToExist(final File file) throws Exception { - waitForFileToExist(file, true); - } - - protected String getUniqueName() { - return getClass().getSimpleName() + "_" + testName.getMethodName(); - } - - protected static void assertEventuallyTrue(final String message, final Callable<Boolean> callable, - final int timeout, final int interval) throws Exception { - boolean done = false; - for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < timeout; done = - (callable.call())) { - Thread.sleep(interval); - } - assertTrue(message, done); - } - - protected static void assertEventuallyFalse(final String message, - final Callable<Boolean> callable, final int timeout, final int interval) throws Exception { - boolean done = false; - for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < timeout; done = - (!callable.call())) { - Thread.sleep(interval); - } - assertTrue(message, done); - } - - protected static void disconnectFromDS() { - InternalDistributedSystem ids = InternalDistributedSystem.getConnectedInstance(); - if (ids != null) { - ids.disconnect(); - } - } -} http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java new file mode 100755 index 0000000..4b03c92 --- /dev/null +++ b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStateTest.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. You may obtain a + * copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.geode.distributed; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.net.InetAddress; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import org.apache.geode.internal.GemFireVersion; +import org.apache.geode.internal.process.ProcessUtils; +import org.apache.geode.management.internal.cli.json.GfJsonArray; +import org.apache.geode.management.internal.cli.json.GfJsonException; +import org.apache.geode.management.internal.cli.json.GfJsonObject; +import org.apache.geode.test.junit.categories.UnitTest; + +/** + * Unit tests for {@link AbstractLauncher.ServiceState}. Tests marshalling of ServiceState to and + * from JSON. + * + * @since GemFire 7.0 + */ +@Category(UnitTest.class) +public class AbstractLauncherServiceStateTest { + + private static String serviceName; + private static String name; + private static int pid; + private static long uptime; + private static String workingDirectory; + private static List<String> jvmArguments; + private static String classpath; + private static String gemfireVersion; + private static String javaVersion; + + private TestLauncher launcher; + + @Before + public void setUp() throws Exception { + serviceName = "Test"; + pid = ProcessUtils.identifyPid(); + uptime = 123456789; + name = AbstractLauncherServiceStateTest.class.getSimpleName(); + workingDirectory = new File(System.getProperty("user.dir")).getAbsolutePath(); + jvmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); + classpath = ManagementFactory.getRuntimeMXBean().getClassPath(); + gemfireVersion = GemFireVersion.getGemFireVersion(); + javaVersion = System.getProperty("java.version"); + + int port = 12345; + InetAddress host = InetAddress.getLocalHost(); + + launcher = new TestLauncher(host, port, name); + } + + @After + public void tearDown() throws Exception { + serviceName = null; + name = null; + workingDirectory = null; + jvmArguments = null; + classpath = null; + gemfireVersion = null; + javaVersion = null; + } + + @Test + public void serviceStateCanBeMarshalledToAndFromJson() throws Exception { + TestLauncher.TestState status = launcher.status(); + String json = status.toJson(); + validateJson(status, json); + validateStatus(status, TestLauncher.TestState.fromJson(json)); + } + + private void validateStatus(final TestLauncher.TestState expected, + final TestLauncher.TestState actual) { + assertThat(actual.getClasspath()).isEqualTo(expected.getClasspath()); + assertThat(actual.getGemFireVersion()).isEqualTo(expected.getGemFireVersion()); + assertThat(actual.getJavaVersion()).isEqualTo(expected.getJavaVersion()); + assertThat(actual.getJvmArguments()).isEqualTo(expected.getJvmArguments()); + assertThat(actual.getPid()).isEqualTo(expected.getPid()); + assertThat(actual.getStatus()).isEqualTo(expected.getStatus()); + assertThat(actual.getTimestamp()).isEqualTo(expected.getTimestamp()); + assertThat(actual.getUptime()).isEqualTo(expected.getUptime()); + assertThat(actual.getWorkingDirectory()).isEqualTo(expected.getWorkingDirectory()); + assertThat(actual.getHost()).isEqualTo(expected.getHost()); + assertThat(actual.getPort()).isEqualTo(expected.getPort()); + assertThat(actual.getMemberName()).isEqualTo(expected.getMemberName()); + } + + private void validateJson(final TestLauncher.TestState expected, final String json) { + TestLauncher.TestState actual = TestLauncher.TestState.fromJson(json); + validateStatus(expected, actual); + } + + private static class TestLauncher extends AbstractLauncher<String> { + + private final InetAddress bindAddress; + private final int port; + private final String memberName; + private final File logFile; + + TestLauncher(final InetAddress bindAddress, final int port, final String memberName) { + this.bindAddress = bindAddress; + this.port = port; + this.memberName = memberName; + this.logFile = new File(memberName + ".log"); + } + + public TestState status() { + return new TestState(Status.ONLINE, null, System.currentTimeMillis(), getId(), pid, uptime, + workingDirectory, jvmArguments, classpath, gemfireVersion, javaVersion, getLogFileName(), + getBindAddressAsString(), getPortAsString(), name); + } + + @Override + public void run() { + // nothing + } + + public String getId() { + return getServiceName() + "@" + getBindAddress() + "[" + getPort() + "]"; + } + + @Override + public String getLogFileName() { + try { + return logFile.getCanonicalPath(); + } catch (IOException e) { + return logFile.getAbsolutePath(); + } + } + + @Override + public String getMemberName() { + return memberName; + } + + @Override + public Integer getPid() { + return null; + } + + @Override + public String getServiceName() { + return serviceName; + } + + InetAddress getBindAddress() { + return bindAddress; + } + + String getBindAddressAsString() { + return bindAddress.getCanonicalHostName(); + } + + int getPort() { + return port; + } + + String getPortAsString() { + return String.valueOf(getPort()); + } + + private static class TestState extends ServiceState<String> { + + protected static TestState fromJson(final String json) { + try { + GfJsonObject gfJsonObject = new GfJsonObject(json); + + Status status = Status.valueOfDescription(gfJsonObject.getString(JSON_STATUS)); + List<String> jvmArguments = Arrays + .asList(GfJsonArray.toStringArray(gfJsonObject.getJSONArray(JSON_JVMARGUMENTS))); + + return new TestState(status, gfJsonObject.getString(JSON_STATUSMESSAGE), + gfJsonObject.getLong(JSON_TIMESTAMP), gfJsonObject.getString(JSON_LOCATION), + gfJsonObject.getInt(JSON_PID), gfJsonObject.getLong(JSON_UPTIME), + gfJsonObject.getString(JSON_WORKINGDIRECTORY), jvmArguments, + gfJsonObject.getString(JSON_CLASSPATH), gfJsonObject.getString(JSON_GEMFIREVERSION), + gfJsonObject.getString(JSON_JAVAVERSION), gfJsonObject.getString(JSON_LOGFILE), + gfJsonObject.getString(JSON_HOST), gfJsonObject.getString(JSON_PORT), + gfJsonObject.getString(JSON_MEMBERNAME)); + } catch (GfJsonException e) { + throw new IllegalArgumentException("Unable to create TestState from JSON: " + json); + } + } + + protected TestState(final Status status, final String statusMessage, final long timestamp, + final String location, final Integer pid, final Long uptime, + final String workingDirectory, final List<String> jvmArguments, final String classpath, + final String gemfireVersion, final String javaVersion, final String logFile, + final String host, final String port, final String name) { + super(status, statusMessage, timestamp, location, pid, uptime, workingDirectory, + jvmArguments, classpath, gemfireVersion, javaVersion, logFile, host, port, name); + } + + @Override + protected String getServiceName() { + return serviceName; + } + } + } +} http://git-wip-us.apache.org/repos/asf/geode/blob/894f3ee7/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStatusTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStatusTest.java b/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStatusTest.java deleted file mode 100755 index 1aa449e..0000000 --- a/geode-core/src/test/java/org/apache/geode/distributed/AbstractLauncherServiceStatusTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license - * agreements. See the NOTICE file distributed with this work for additional information regarding - * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. You may obtain a - * copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.apache.geode.distributed; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.net.InetAddress; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import org.apache.geode.internal.GemFireVersion; -import org.apache.geode.internal.process.ProcessUtils; -import org.apache.geode.management.internal.cli.json.GfJsonArray; -import org.apache.geode.management.internal.cli.json.GfJsonException; -import org.apache.geode.management.internal.cli.json.GfJsonObject; -import org.apache.geode.test.junit.categories.UnitTest; - -/** - * Tests marshaling of ServiceStatus to and from JSON. - * - * @since GemFire 7.0 - */ -@Category(UnitTest.class) -public class AbstractLauncherServiceStatusTest { - - private static String serviceName; - private static InetAddress host; - private static int port; - private static String name; - private static int pid; - private static long uptime; - private static String workingDirectory; - private static List<String> jvmArguments; - private static String classpath; - private static String gemfireVersion; - private static String javaVersion; - - private TestLauncher launcher; - - @Before - public void setUp() throws Exception { - serviceName = "Test"; - port = 12345; - host = InetAddress.getLocalHost(); - pid = ProcessUtils.identifyPid(); - uptime = 123456789; - name = AbstractLauncherServiceStatusTest.class.getSimpleName(); - workingDirectory = new File(System.getProperty("user.dir")).getAbsolutePath(); - jvmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); - classpath = ManagementFactory.getRuntimeMXBean().getClassPath(); - gemfireVersion = GemFireVersion.getGemFireVersion(); - javaVersion = System.getProperty("java.version"); - - this.launcher = new TestLauncher(host, port, name); - } - - @After - public void tearDown() throws Exception { - serviceName = null; - host = null; - name = null; - workingDirectory = null; - jvmArguments = null; - classpath = null; - gemfireVersion = null; - javaVersion = null; - } - - @Test - public void testMarshallingTestStatusToAndFromJson() { - final TestLauncher.TestState status = this.launcher.status(); - final String json = status.toJson(); - validateJson(status, json); - validateStatus(status, TestLauncher.TestState.fromJson(json)); - } - - private void validateStatus(final TestLauncher.TestState expected, - final TestLauncher.TestState actual) { - assertEquals(expected.getClasspath(), actual.getClasspath()); - assertEquals(expected.getGemFireVersion(), actual.getGemFireVersion()); - assertEquals(expected.getJavaVersion(), actual.getJavaVersion()); - assertEquals(expected.getJvmArguments(), actual.getJvmArguments()); - assertEquals(expected.getPid(), actual.getPid()); - assertEquals(expected.getStatus(), actual.getStatus()); - assertEquals(expected.getTimestamp(), actual.getTimestamp()); - assertEquals(expected.getUptime(), actual.getUptime()); - assertEquals(expected.getWorkingDirectory(), actual.getWorkingDirectory()); - assertEquals(expected.getHost(), actual.getHost()); - assertEquals(expected.getPort(), actual.getPort()); - assertEquals(expected.getMemberName(), actual.getMemberName()); - } - - private void validateJson(final TestLauncher.TestState expected, final String json) { - final TestLauncher.TestState actual = TestLauncher.TestState.fromJson(json); - validateStatus(expected, actual); - } - - private static class TestLauncher extends AbstractLauncher<String> { - - private final InetAddress bindAddress; - private final int port; - private final String memberName; - private final File logFile; - - TestLauncher(InetAddress bindAddress, int port, String memberName) { - this.bindAddress = bindAddress; - this.port = port; - this.memberName = memberName; - this.logFile = new File(memberName + ".log"); - } - - public TestState status() { - return new TestState(Status.ONLINE, null, System.currentTimeMillis(), getId(), pid, uptime, - workingDirectory, jvmArguments, classpath, gemfireVersion, javaVersion, getLogFileName(), - getBindAddressAsString(), getPortAsString(), name); - } - - @Override - public void run() {} - - public String getId() { - return getServiceName() + "@" + getBindAddress() + "[" + getPort() + "]"; - } - - @Override - public String getLogFileName() { - try { - return this.logFile.getCanonicalPath(); - } catch (IOException e) { - return this.logFile.getAbsolutePath(); - } - } - - @Override - public String getMemberName() { - return this.memberName; - } - - @Override - public Integer getPid() { - return null; - } - - @Override - public String getServiceName() { - return serviceName; - } - - InetAddress getBindAddress() { - return this.bindAddress; - } - - String getBindAddressAsString() { - return this.bindAddress.getCanonicalHostName(); - } - - int getPort() { - return this.port; - } - - String getPortAsString() { - return String.valueOf(getPort()); - } - - private static class TestState extends ServiceState<String> { - - protected static TestState fromJson(final String json) { - try { - final GfJsonObject gfJsonObject = new GfJsonObject(json); - - final Status status = Status.valueOfDescription(gfJsonObject.getString(JSON_STATUS)); - final List<String> jvmArguments = Arrays - .asList(GfJsonArray.toStringArray(gfJsonObject.getJSONArray(JSON_JVMARGUMENTS))); - - return new TestState(status, gfJsonObject.getString(JSON_STATUSMESSAGE), - gfJsonObject.getLong(JSON_TIMESTAMP), gfJsonObject.getString(JSON_LOCATION), - gfJsonObject.getInt(JSON_PID), gfJsonObject.getLong(JSON_UPTIME), - gfJsonObject.getString(JSON_WORKINGDIRECTORY), jvmArguments, - gfJsonObject.getString(JSON_CLASSPATH), gfJsonObject.getString(JSON_GEMFIREVERSION), - gfJsonObject.getString(JSON_JAVAVERSION), gfJsonObject.getString(JSON_LOGFILE), - gfJsonObject.getString(JSON_HOST), gfJsonObject.getString(JSON_PORT), - gfJsonObject.getString(JSON_MEMBERNAME)); - } catch (GfJsonException e) { - throw new IllegalArgumentException("Unable to create TestState from JSON: " + json); - } - } - - protected TestState(final Status status, final String statusMessage, final long timestamp, - final String location, final Integer pid, final Long uptime, - final String workingDirectory, final List<String> jvmArguments, final String classpath, - final String gemfireVersion, final String javaVersion, final String logFile, - final String host, final String port, final String name) { - super(status, statusMessage, timestamp, location, pid, uptime, workingDirectory, - jvmArguments, classpath, gemfireVersion, javaVersion, logFile, host, port, name); - } - - @Override - protected String getServiceName() { - return serviceName; - } - } - } - -}