This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git


The following commit(s) were added to refs/heads/develop by this push:
     new 9cdc63c   GEODE-4240: Fix testCreateBuckets on windows (#3660)
9cdc63c is described below

commit 9cdc63c0ae8cd6acd2bb5f41167970298eaedeaf
Author: Kirk Lund <[email protected]>
AuthorDate: Mon Jun 3 09:12:40 2019 -0700

     GEODE-4240: Fix testCreateBuckets on windows (#3660)
    
    * Move gemfire config to properties file
    * Reformat code to improve readability
    * Add directory option to ProcessWrapper to inject TemporaryFolder
    
    The -J-Dgemfire.locator="" with quotes was breaking the next argument
    on windows. Moving the config to properties file works around this.
---
 ...precatedCacheServerLauncherIntegrationTest.java | 105 +++++----
 .../apache/geode/test/process/ProcessWrapper.java  | 240 ++++++++++-----------
 2 files changed, 177 insertions(+), 168 deletions(-)

diff --git 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DeprecatedCacheServerLauncherIntegrationTest.java
 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DeprecatedCacheServerLauncherIntegrationTest.java
index d96dde1..31845fb 100755
--- 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DeprecatedCacheServerLauncherIntegrationTest.java
+++ 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DeprecatedCacheServerLauncherIntegrationTest.java
@@ -16,6 +16,7 @@ package org.apache.geode.internal.cache;
 
 import static java.lang.System.lineSeparator;
 import static java.util.Arrays.asList;
+import static org.apache.geode.cache.client.ClientRegionShortcut.PROXY;
 import static 
org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
 import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
 import static 
org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
@@ -28,6 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.net.InetAddress;
@@ -42,6 +44,7 @@ import java.rmi.registry.Registry;
 import java.rmi.server.UnicastRemoteObject;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Properties;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -59,8 +62,6 @@ import org.apache.geode.cache.Declarable;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
 import org.apache.geode.cache.client.Pool;
 import org.apache.geode.cache.client.PoolManager;
 import org.apache.geode.cache.util.CacheListenerAdapter;
@@ -100,6 +101,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
   private File directory;
   private File logFile;
   private File cacheXmlFile;
+  private File configPropertiesFile;
 
   private String directoryPath;
   private String logFileName;
@@ -115,7 +117,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
   public TestName testName = new TestName();
 
   @Before
-  public void setUp() {
+  public void setUp() throws Exception {
     classpath = System.getProperty("java.class.path");
     assertThat(classpath).isNotEmpty();
 
@@ -123,7 +125,9 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
     directoryPath = directory.getAbsolutePath();
     logFileName = testName.getMethodName() + ".log";
     cacheXmlFileName = testName.getMethodName() + ".xml";
+    String configPropertiesFileName = testName.getMethodName() + ".properties";
 
+    configPropertiesFile = new File(directory, configPropertiesFileName);
     cacheXmlFile = new File(directory, cacheXmlFileName);
     logFile = new File(directory, logFileName);
 
@@ -133,6 +137,14 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
     cacheServerNamingPort = tcpPorts[2];
     commandPort = tcpPorts[3];
     xmlPort = tcpPorts[4];
+
+    Properties configProperties = new Properties();
+    configProperties.setProperty(HTTP_SERVICE_PORT, "0");
+    configProperties.setProperty(LOCATORS, "");
+    configProperties.setProperty(USE_CLUSTER_CONFIGURATION, "false");
+    try (FileOutputStream fileOutputStream = new 
FileOutputStream(configPropertiesFile)) {
+      configProperties.store(fileOutputStream, null);
+    }
   }
 
   @After
@@ -163,7 +175,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
         asList(
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath));
 
     execWithDirAndValidate(Operation.STATUS, "CacheServer pid: \\d+ status: 
running");
@@ -181,7 +193,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
         asList(
             "cache-xml-file=" + cacheXmlFile.getAbsolutePath(),
             "log-file=" + logFile.getAbsolutePath(),
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directory.getAbsolutePath(),
             "-server-port=" + serverPort));
 
@@ -204,7 +216,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
         asList(
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath,
             "-rebalance"));
 
@@ -229,7 +241,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
             "-J-D" + CacheServerLauncher.ASSIGN_BUCKETS_PROPERTY + "=true",
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath,
             "-rebalance"));
 
@@ -249,23 +261,26 @@ public class DeprecatedCacheServerLauncherIntegrationTest 
{
         asList(
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath));
 
     execWithDirAndValidate(Operation.STATUS, "CacheServer pid: \\d+ status: 
running");
 
-    ClientCache cache = new ClientCacheFactory().create();
-    ClientRegionFactory<Integer, Integer> regionFactory =
-        cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
-    Pool pool = PoolManager.createFactory().addServer("localhost", 
xmlPort).create("cslPool");
-    regionFactory.setPoolName(pool.getName());
-    Region<Integer, Integer> region = regionFactory.create("rgn");
-    List<InetSocketAddress> servers = pool.getServers();
+    ClientCache cache = new ClientCacheFactory()
+        .create();
+    Pool pool = PoolManager.createFactory()
+        .addServer("localhost", xmlPort)
+        .create("cslPool");
+    Region<Integer, Integer> region = cache.<Integer, 
Integer>createClientRegionFactory(PROXY)
+        .setPoolName(pool.getName())
+        .create("rgn");
 
+    List<InetSocketAddress> servers = pool.getServers();
     assertThat(servers).hasSize(1);
     assertThat(servers.iterator().next().getPort()).isEqualTo(xmlPort);
 
-    region.put(1, 1); // put should be successful
+    // put should be successful
+    region.put(1, 1);
 
     execWithDirAndValidate(Operation.STOP, "The CacheServer has stopped\\.");
   }
@@ -278,26 +293,27 @@ public class DeprecatedCacheServerLauncherIntegrationTest 
{
         asList(
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath,
             "-server-port=" + commandPort));
 
     execWithDirAndValidate(Operation.STATUS, "CacheServer pid: \\d+ status: 
running");
 
-    ClientCache cache = new ClientCacheFactory().create();
+    ClientCache cache = new ClientCacheFactory()
+        .create();
+    Pool pool = PoolManager.createFactory()
+        .addServer("localhost", commandPort)
+        .create("cslPool");
+    Region<Integer, Integer> region = cache.<Integer, 
Integer>createClientRegionFactory(PROXY)
+        .setPoolName(pool.getName())
+        .create("rgn");
 
-    ClientRegionFactory<Integer, Integer> regionFactory =
-        cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
-    Pool pool =
-        PoolManager.createFactory().addServer("localhost", 
commandPort).create("cslPool");
-    regionFactory.setPoolName(pool.getName());
-    Region<Integer, Integer> region = regionFactory.create("rgn");
     List<InetSocketAddress> servers = pool.getServers();
-
     assertThat(servers).hasSize(1);
     assertThat(servers.iterator().next().getPort()).isEqualTo(commandPort);
 
-    region.put(1, 1); // put should be successful
+    // put should be successful
+    region.put(1, 1);
 
     execWithDirAndValidate(Operation.STOP, "The CacheServer has stopped\\.");
   }
@@ -310,33 +326,35 @@ public class DeprecatedCacheServerLauncherIntegrationTest 
{
         asList(
             "cache-xml-file=" + cacheXmlFileName,
             "log-file=" + logFileName,
-            "-classpath=" + getManifestJarFromClasspath(),
+            "-classpath=" + createManifestJar(),
             "-dir=" + directoryPath,
             "-server-bind-address=" + InetAddress.getLocalHost().getHostName(),
             "-server-port=" + commandPort));
 
     execWithDirAndValidate(Operation.STATUS, "CacheServer pid: \\d+ status: 
running");
 
-    ClientCache cache = new ClientCacheFactory().create();
-    ClientRegionFactory<Integer, Integer> regionFactory =
-        cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
+    ClientCache cache = new ClientCacheFactory()
+        .create();
     Pool pool = PoolManager.createFactory()
-        .addServer(InetAddress.getLocalHost().getHostName(), 
commandPort).create("cslPool");
-    regionFactory.setPoolName(pool.getName());
-    Region<Integer, Integer> region = regionFactory.create("rgn");
-    List<InetSocketAddress> servers = pool.getServers();
+        .addServer(InetAddress.getLocalHost().getHostName(), commandPort)
+        .create("cslPool");
+    Region<Integer, Integer> region = cache.<Integer, 
Integer>createClientRegionFactory(PROXY)
+        .setPoolName(pool.getName())
+        .create("rgn");
 
+    List<InetSocketAddress> servers = pool.getServers();
     assertThat(servers).hasSize(1);
     assertThat(servers.iterator().next().getPort()).isEqualTo(commandPort);
 
-    region.put(1, 1); // put should be successful
+    // put should be successful
+    region.put(1, 1);
 
     execWithDirAndValidate(Operation.STOP, "The CacheServer has stopped\\.");
   }
 
-  private String getManifestJarFromClasspath() throws IOException {
+  private String createManifestJar() throws IOException {
     List<String> parts = asList(classpath.split(File.pathSeparator));
-    return ProcessWrapper.createManifestJar(parts, 
temporaryFolder.newFolder().getAbsolutePath());
+    return ProcessWrapper.createManifestJar(parts, directoryPath);
   }
 
   private void unexportObject(final Remote object) {
@@ -361,7 +379,7 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
       FailSafeRemote failSafe = (FailSafeRemote) 
registry.lookup(FAIL_SAFE_BINDING);
       failSafe.kill();
     } catch (RemoteException | NotBoundException ignore) {
-      // cacheserver was probably stopped already
+      // cacheserver process was probably stopped already
     }
   }
 
@@ -369,12 +387,10 @@ public class DeprecatedCacheServerLauncherIntegrationTest 
{
       throws TimeoutException, InterruptedException {
     List<String> newArguments = new ArrayList<>();
     newArguments.add(operation.value);
+    newArguments.add("-J-Xmx" + Runtime.getRuntime().maxMemory());
     newArguments.add("-J-D" + CONTROLLER_NAMING_PORT_PROP + "=" + 
controllerNamingPort);
     newArguments.add("-J-D" + CACHESERVER_NAMING_PORT_PROP + "=" + 
cacheServerNamingPort);
-    newArguments.add("-J-Xmx" + Runtime.getRuntime().maxMemory());
-    newArguments.add("-J-Dgemfire." + USE_CLUSTER_CONFIGURATION + "=false");
-    newArguments.add("-J-Dgemfire." + HTTP_SERVICE_PORT + "=0");
-    newArguments.add("-J-Dgemfire." + LOCATORS + "=\"\"");
+    newArguments.add("-J-DgemfirePropertyFile=" + 
configPropertiesFile.getAbsolutePath());
     newArguments.addAll(arguments);
     execAndValidate(regex, newArguments);
   }
@@ -392,7 +408,10 @@ public class DeprecatedCacheServerLauncherIntegrationTest {
   private void execAndValidate(final String regex, final String[] args)
       throws InterruptedException, TimeoutException {
     ProcessWrapper processWrapper = new ProcessWrapper.Builder()
-        .mainClass(CacheServerLauncher.class).mainArguments(args).build();
+        .mainClass(CacheServerLauncher.class)
+        .mainArguments(args)
+        .directory(directory)
+        .build();
     processWrapper.setConsumer(c -> logger.info(c));
     processWrapper.execute();
     if (regex != null) {
diff --git 
a/geode-junit/src/main/java/org/apache/geode/test/process/ProcessWrapper.java 
b/geode-junit/src/main/java/org/apache/geode/test/process/ProcessWrapper.java
index 982b030..1bcd0f0 100644
--- 
a/geode-junit/src/main/java/org/apache/geode/test/process/ProcessWrapper.java
+++ 
b/geode-junit/src/main/java/org/apache/geode/test/process/ProcessWrapper.java
@@ -14,13 +14,13 @@
  */
 package org.apache.geode.test.process;
 
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
 import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
 import java.io.PrintStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -35,7 +35,6 @@ import java.util.Properties;
 import java.util.UUID;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Consumer;
@@ -52,8 +51,7 @@ import org.apache.geode.internal.logging.LogService;
 import org.apache.geode.test.awaitility.GeodeAwaitility;
 
 /**
- * Wraps spawned {@link java.lang.Process} to capture output and provide 
interaction with the
- * process.
+ * Wraps spawned {@link Process} to capture output and provide interaction 
with the process.
  *
  * @since GemFire 4.1.1
  */
@@ -65,6 +63,7 @@ public class ProcessWrapper implements Consumer<String> {
 
   private final boolean headless;
   private final long timeoutMillis;
+  private final File directory;
 
   private final String[] jvmArguments;
 
@@ -81,10 +80,10 @@ public class ProcessWrapper implements Consumer<String> {
   private final BlockingQueue<String> lineBuffer;
 
   private final AtomicInteger exitValue = new AtomicInteger(-1);
-  private boolean starting = false;
-  private boolean started = false;
-  private boolean stopped = false;
-  private boolean interrupted = false;
+  private boolean starting;
+  private boolean started;
+  private boolean stopped;
+  private boolean interrupted;
   private Thread processThread;
   private ProcessStreamReader stdout;
   private ProcessStreamReader stderr;
@@ -92,16 +91,17 @@ public class ProcessWrapper implements Consumer<String> {
 
   private ProcessWrapper(final String[] jvmArguments, final Class<?> mainClass,
       final String[] mainArguments, final boolean useMainLauncher, final 
boolean headless,
-      final long timeoutMillis) {
+      final long timeoutMillis, final File directory) {
     this.jvmArguments = jvmArguments;
     this.mainClass = mainClass;
     this.mainArguments = mainArguments;
     this.useMainLauncher = useMainLauncher;
     this.headless = headless;
     this.timeoutMillis = timeoutMillis;
+    this.directory = directory;
 
-    this.lineBuffer = new LinkedBlockingQueue<>();
-    this.allLines = Collections.synchronizedList(new ArrayList<>());
+    lineBuffer = new LinkedBlockingQueue<>();
+    allLines = Collections.synchronizedList(new ArrayList<>());
   }
 
   public void setConsumer(Consumer<String> consumer) {
@@ -110,8 +110,8 @@ public class ProcessWrapper implements Consumer<String> {
 
   @Override
   public void accept(String line) {
-    this.lineBuffer.offer(line);
-    this.allLines.add(line);
+    allLines.add(line);
+    lineBuffer.offer(line);
 
     if (consumer != null) {
       consumer.accept(line);
@@ -119,13 +119,13 @@ public class ProcessWrapper implements Consumer<String> {
   }
 
   public ProcessStreamReader getStandardOutReader() {
-    synchronized (this.exitValue) {
+    synchronized (exitValue) {
       return stdout;
     }
   }
 
   public ProcessStreamReader getStandardErrorReader() {
-    synchronized (this.exitValue) {
+    synchronized (exitValue) {
       return stderr;
     }
   }
@@ -134,9 +134,9 @@ public class ProcessWrapper implements Consumer<String> {
     final long start = System.currentTimeMillis();
     boolean done = false;
     while (!done) {
-      synchronized (this.exitValue) {
-        done = (this.process != null || this.processException != null)
-            && (this.started || this.exitValue.get() > -1 || this.interrupted);
+      synchronized (exitValue) {
+        done = (process != null || processException != null)
+            && (started || exitValue.get() > -1 || interrupted);
       }
       if (!done && System.currentTimeMillis() > start + timeoutMillis) {
         throw new TimeoutException("Timed out launching process");
@@ -149,18 +149,18 @@ public class ProcessWrapper implements Consumer<String> {
     checkStarting();
     waitForProcessStart();
 
-    synchronized (this.exitValue) {
-      if (this.interrupted) { // TODO: do we want to do this?
+    synchronized (exitValue) {
+      if (interrupted) {
         throw new InterruptedException("Process was interrupted");
       }
-      return this.exitValue.get() == -1 && this.started && !this.stopped && 
!this.interrupted
-          && this.processThread.isAlive();
+      return exitValue.get() == -1 && started && !stopped && !interrupted
+          && processThread.isAlive();
     }
   }
 
   public ProcessWrapper destroy() {
-    if (this.process != null) {
-      this.process.destroy();
+    if (process != null) {
+      process.destroy();
     }
     return this;
   }
@@ -169,11 +169,11 @@ public class ProcessWrapper implements Consumer<String> {
     checkStarting();
     final Thread thread = getThread();
     thread.join(timeout);
-    synchronized (this.exitValue) {
+    synchronized (exitValue) {
       if (throwOnTimeout) {
         checkStopped();
       }
-      return this.exitValue.get();
+      return exitValue.get();
     }
   }
 
@@ -199,9 +199,9 @@ public class ProcessWrapper implements Consumer<String> {
       checkStopped();
     }
     final StringBuffer sb = new StringBuffer();
-    final Iterator<String> iterator = this.allLines.iterator();
+    final Iterator<String> iterator = allLines.iterator();
     while (iterator.hasNext()) {
-      sb.append(iterator.next() + "\n");
+      sb.append(iterator.next() + System.lineSeparator());
     }
     return sb.toString();
   }
@@ -214,7 +214,7 @@ public class ProcessWrapper implements Consumer<String> {
 
   public ProcessWrapper sendInput(final String input) {
     checkStarting();
-    final PrintStream ps = new PrintStream(this.process.getOutputStream());
+    final PrintStream ps = new PrintStream(process.getOutputStream());
     ps.println(input);
     ps.flush();
     return this;
@@ -230,10 +230,10 @@ public class ProcessWrapper implements Consumer<String> {
     final long start = System.currentTimeMillis();
 
     while (System.currentTimeMillis() <= start + timeoutMillis) {
-      final String line = lineBuffer.poll(timeoutMillis, 
TimeUnit.MILLISECONDS);
+      final String line = lineBuffer.poll(timeoutMillis, MILLISECONDS);
       if (line != null && pattern.matcher(line).matches()) {
         fail("failIfOutputMatches Matched pattern \"" + patternString + "\" 
against output \""
-            + line + "\". Output: " + this.allLines);
+            + line + "\". Output: " + allLines);
       }
     }
     return this;
@@ -248,11 +248,11 @@ public class ProcessWrapper implements Consumer<String> {
     checkStarting();
     checkOk();
 
-    final Pattern pattern = Pattern.compile(patternString);
     logger.debug("ProcessWrapper:waitForOutputToMatch waiting for \"{}\"...", 
patternString);
+    final Pattern pattern = Pattern.compile(patternString);
 
     while (true) {
-      final String line = this.lineBuffer.poll(timeoutMillis, 
TimeUnit.MILLISECONDS);
+      final String line = lineBuffer.poll(timeoutMillis, MILLISECONDS);
       if (line == null) {
         fail("Timed out waiting for output \"" + patternString + "\" after " + 
timeoutMillis +
             " ms from process \"" + toString(process) + "\" in \"" + this + 
"\". Output: " +
@@ -264,11 +264,10 @@ public class ProcessWrapper implements Consumer<String> {
             "ProcessWrapper:waitForOutputToMatch Matched pattern \"{}\" 
against output \"{}\"",
             patternString, line);
         break;
-      } else {
-        logger.debug(
-            "ProcessWrapper:waitForOutputToMatch Did not match pattern \"{}\" 
against output \"{}\"",
-            patternString, line);
       }
+      logger.debug(
+          "ProcessWrapper:waitForOutputToMatch Did not match pattern \"{}\" 
against output \"{}\"",
+          patternString, line);
     }
     return this;
   }
@@ -291,47 +290,44 @@ public class ProcessWrapper implements Consumer<String> {
   }
 
   public ProcessWrapper execute() throws InterruptedException, 
TimeoutException {
-    return execute(null, new File(System.getProperty("user.dir")));
+    return execute(null, directory);
   }
 
   public ProcessWrapper execute(final Properties properties)
       throws InterruptedException, TimeoutException {
-    return execute(properties, new File(System.getProperty("user.dir")));
+    return execute(properties, directory);
   }
 
   public ProcessWrapper execute(final Properties properties, final File 
workingDirectory)
       throws InterruptedException, TimeoutException {
-    synchronized (this.exitValue) {
-      if (this.starting) {
+    synchronized (exitValue) {
+      if (starting) {
         throw new IllegalStateException("ProcessWrapper can only be executed 
once");
       }
-      this.starting = true;
-      this.processThread = new Thread(new Runnable() {
-        @Override
-        public void run() {
-          start(properties, workingDirectory);
-        }
-      }, "ProcessWrapper Process Thread");
+      starting = true;
+      processThread =
+          new Thread(() -> start(properties, workingDirectory), 
"ProcessWrapper Process Thread");
     }
-    this.processThread.start();
+    processThread.start();
 
     waitForProcessStart();
 
-    synchronized (this.exitValue) {
-      if (this.processException != null) {
-        logger.error("ProcessWrapper:execute failed with " + 
this.processException);
-        this.processException.printStackTrace();
+    synchronized (exitValue) {
+      if (processException != null) {
+        logger.error("ProcessWrapper:execute failed with " + processException);
+        processException.printStackTrace();
       }
     }
 
-    if (this.useMainLauncher) {
-      sendInput(); // to trigger MainLauncher delegation to inner main
+    if (useMainLauncher) {
+      // to trigger MainLauncher delegation to inner main
+      sendInput();
     }
     return this;
   }
 
   private void start(final Properties properties, final File workingDirectory) 
{
-    final List<String> jvmArgumentsList = new ArrayList<String>();
+    final List<String> jvmArgumentsList = new ArrayList<>();
 
     if (properties != null) {
       for (Map.Entry<Object, Object> entry : properties.entrySet()) {
@@ -341,22 +337,20 @@ public class ProcessWrapper implements Consumer<String> {
       }
     }
 
-    if (this.headless) {
+    if (headless) {
       jvmArgumentsList.add("-Djava.awt.headless=true");
     }
 
-    if (this.jvmArguments != null) {
-      for (String jvmArgument : this.jvmArguments) {
-        jvmArgumentsList.add(jvmArgument);
-      }
+    if (jvmArguments != null) {
+      Collections.addAll(jvmArgumentsList, jvmArguments);
     }
 
     try {
-      synchronized (this.exitValue) {
+      synchronized (exitValue) {
         final String[] command =
             defineCommand(jvmArgumentsList.toArray(new 
String[jvmArgumentsList.size()]),
                 workingDirectory.getCanonicalPath());
-        this.process = new 
ProcessBuilder(command).directory(workingDirectory).start();
+        process = new 
ProcessBuilder(command).directory(workingDirectory).start();
 
         final StringBuilder processCommand = new StringBuilder();
         boolean addSpace = false;
@@ -373,33 +367,33 @@ public class ProcessWrapper implements Consumer<String> {
         logger.info("Starting " + commandString);
 
         final ProcessStreamReader stdOut = new 
ProcessStreamReader(commandString,
-            this.process.getInputStream(), this);
+            process.getInputStream(), this);
         final ProcessStreamReader stdErr = new 
ProcessStreamReader(commandString,
-            this.process.getErrorStream(), this);
+            process.getErrorStream(), this);
 
-        this.stdout = stdOut;
-        this.stderr = stdErr;
-        this.outputReader = new ProcessOutputReader(this.process, stdOut, 
stdErr);
-        this.started = true;
+        stdout = stdOut;
+        stderr = stdErr;
+        outputReader = new ProcessOutputReader(process, stdOut, stdErr);
+        started = true;
       }
 
-      this.outputReader.start();
-      this.outputReader.waitFor(PROCESS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
-      boolean exited = process.waitFor(PROCESS_TIMEOUT_MILLIS, 
TimeUnit.MILLISECONDS);
+      outputReader.start();
+      outputReader.waitFor(PROCESS_TIMEOUT_MILLIS, MILLISECONDS);
+      boolean exited = process.waitFor(PROCESS_TIMEOUT_MILLIS, MILLISECONDS);
 
-      synchronized (this.exitValue) {
-        this.exitValue.set(exited ? process.exitValue() : 0);
-        this.stopped = exited;
+      synchronized (exitValue) {
+        exitValue.set(exited ? process.exitValue() : 0);
+        stopped = exited;
       }
 
     } catch (InterruptedException e) {
-      synchronized (this.exitValue) {
-        this.interrupted = true;
-        this.processException = e;
+      synchronized (exitValue) {
+        interrupted = true;
+        processException = e;
       }
     } catch (Throwable t) {
-      synchronized (this.exitValue) {
-        this.processException = t;
+      synchronized (exitValue) {
+        processException = t;
       }
     }
   }
@@ -420,8 +414,8 @@ public class ProcessWrapper implements Consumer<String> {
 
     // -d64 is not a valid option for windows and results in failure
     // -d64 is not a valid option for java 9 and above
-    final int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
-    if (bits == 64 && 
!(System.getProperty("os.name").toLowerCase().contains("windows"))
+    final int bits = Integer.getInteger("sun.arch.data.model", 0);
+    if (bits == 64 && 
!System.getProperty("os.name").toLowerCase().contains("windows")
         && !SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_9)) {
       argumentList.add("-d64");
     }
@@ -432,7 +426,7 @@ public class ProcessWrapper implements Consumer<String> {
       argumentList.addAll(Arrays.asList(jvmArguments));
     }
 
-    if (this.useMainLauncher) {
+    if (useMainLauncher) {
       argumentList.add(MainLauncher.class.getName());
     }
     argumentList.add(mainClass.getName());
@@ -441,35 +435,34 @@ public class ProcessWrapper implements Consumer<String> {
       argumentList.addAll(Arrays.asList(mainArguments));
     }
 
-    final String[] command = argumentList.toArray(new 
String[argumentList.size()]);
-    return command;
+    return argumentList.toArray(new String[0]);
   }
 
   private void checkStarting() throws IllegalStateException {
-    synchronized (this.exitValue) {
-      if (!this.starting) {
+    synchronized (exitValue) {
+      if (!starting) {
         throw new IllegalStateException("Process has not been launched");
       }
     }
   }
 
   private void checkStopped() throws IllegalStateException {
-    synchronized (this.exitValue) {
-      if (!this.stopped) {
+    synchronized (exitValue) {
+      if (!stopped) {
         throw new IllegalStateException("Process has not stopped");
       }
     }
   }
 
   private void checkOk() throws RuntimeException {
-    if (this.processException != null) {
-      throw new RuntimeException("Failed to launch process", 
this.processException);
+    if (processException != null) {
+      throw new RuntimeException("Failed to launch process", processException);
     }
   }
 
   private Thread getThread() {
-    synchronized (this.exitValue) {
-      return this.processThread;
+    synchronized (exitValue) {
+      return processThread;
     }
   }
 
@@ -485,7 +478,7 @@ public class ProcessWrapper implements Consumer<String> {
   }
 
   public Process getProcess() {
-    return this.process;
+    return process;
   }
 
   /**
@@ -505,53 +498,45 @@ public class ProcessWrapper implements Consumer<String> {
     Files.createDirectories(locationPath);
 
     List<String> manifestEntries = new ArrayList<>();
-    for (String jar : entries) {
-      Path absPath = Paths.get(jar).toAbsolutePath();
-      Path relPath = locationPath.relativize(absPath);
-      if (absPath.toFile().isDirectory()) {
-        manifestEntries.add(relPath.toString() + "/");
+    for (String jarEntry : entries) {
+      Path jarEntryAbsolutePath = Paths.get(jarEntry).toAbsolutePath();
+      Path jarEntryRelativizedPath = 
locationPath.relativize(jarEntryAbsolutePath);
+      if (jarEntryAbsolutePath.toFile().isDirectory()) {
+        manifestEntries.add(jarEntryRelativizedPath + File.separator);
       } else {
-        manifestEntries.add(relPath.toString());
+        manifestEntries.add(jarEntryRelativizedPath.toString());
       }
     }
 
     Manifest manifest = new Manifest();
-    Attributes global = manifest.getMainAttributes();
-    global.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
-    global.put(new Attributes.Name("Class-Path"), String.join(" ", 
manifestEntries));
+    Attributes attributes = manifest.getMainAttributes();
+    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
+    attributes.put(new Attributes.Name("Class-Path"), String.join(" ", 
manifestEntries));
 
     // Generate a 'unique' 8 char name
     String uuid = UUID.randomUUID().toString().substring(0, 8);
-    Path manifestJar = Paths.get(location, "manifest-" + uuid + ".jar");
-    JarOutputStream jos = null;
-    try {
-      File jarFile = manifestJar.toFile();
-      jarFile.deleteOnExit();
-      OutputStream os = new FileOutputStream(jarFile);
-      jos = new JarOutputStream(os, manifest);
-    } catch (IOException e) {
-      e.printStackTrace();
-    } finally {
-      if (jos != null) {
-        jos.close();
-      }
+    Path manifestJarPath = Paths.get(location, "manifest-" + uuid + ".jar");
+    File manifestJarFile = manifestJarPath.toFile();
+    manifestJarFile.deleteOnExit();
+
+    try (JarOutputStream jos =
+        new JarOutputStream(new FileOutputStream(manifestJarFile), manifest)) {
+      // the above try-with-resource writes the manifest to the manifestJarFile
     }
 
-    return manifestJar.toString();
+    return manifestJarPath.toFile().getAbsolutePath();
   }
 
   public static class Builder {
-    private String[] jvmArguments = null;
+
+    private String[] jvmArguments;
     private Class<?> mainClass;
-    private String[] mainArguments = null;
+    private String[] mainArguments;
     private boolean useMainLauncher = true;
     private boolean headless = true;
     private long timeoutMillis = PROCESS_TIMEOUT_MILLIS;
-    private boolean inline = false;
-
-    public Builder() {
-      // nothing
-    }
+    private boolean inline;
+    private File directory = new File(System.getProperty("user.dir"));
 
     public Builder jvmArguments(final String[] jvmArguments) {
       this.jvmArguments = jvmArguments;
@@ -588,9 +573,14 @@ public class ProcessWrapper implements Consumer<String> {
       return this;
     }
 
+    public Builder directory(final File directory) {
+      this.directory = directory;
+      return this;
+    }
+
     public ProcessWrapper build() {
       return new ProcessWrapper(jvmArguments, mainClass, mainArguments, 
useMainLauncher, headless,
-          timeoutMillis);
+          timeoutMillis, directory);
     }
   }
 }

Reply via email to