geode-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kl...@apache.org
Subject geode git commit: GEODE-2325: Improve tests for JarDeployer
Date Mon, 30 Jan 2017 18:30:41 GMT
Repository: geode
Updated Branches:
  refs/heads/develop f5228833a -> 917dfa038


GEODE-2325: Improve tests for JarDeployer

This closes #361


Project: http://git-wip-us.apache.org/repos/asf/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/917dfa03
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/917dfa03
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/917dfa03

Branch: refs/heads/develop
Commit: 917dfa0385e1637f5993df3280319ec127162f32
Parents: f522883
Author: Jared Stewart <jstewart@pivotal.io>
Authored: Wed Jan 25 15:52:41 2017 -0800
Committer: Kirk Lund <klund@apache.org>
Committed: Mon Jan 30 10:23:09 2017 -0800

----------------------------------------------------------------------
 .../org/apache/geode/internal/JarDeployer.java  |  38 +--
 .../geode/internal/JarDeployerDUnitTest.java    | 236 +++----------------
 .../apache/geode/internal/JarDeployerTest.java  | 197 ++++++++++++++++
 3 files changed, 246 insertions(+), 225 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/917dfa03/geode-core/src/main/java/org/apache/geode/internal/JarDeployer.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/internal/JarDeployer.java b/geode-core/src/main/java/org/apache/geode/internal/JarDeployer.java
index e7afeda..18d4b42 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/JarDeployer.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/JarDeployer.java
@@ -14,6 +14,10 @@
  */
 package org.apache.geode.internal;
 
+import org.apache.geode.SystemFailure;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.logging.log4j.Logger;
+
 import java.io.BufferedInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -38,19 +42,16 @@ import java.util.concurrent.locks.ReentrantLock;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import org.apache.logging.log4j.Logger;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.internal.logging.LogService;
-
 public class JarDeployer implements Serializable {
   private static final long serialVersionUID = 1L;
   private static final Logger logger = LogService.getLogger();
   public static final String JAR_PREFIX = "vf.gf#";
+  public static final String JAR_PREFIX_FOR_REGEX = "^vf\\.gf#";
   private static final Lock lock = new ReentrantLock();
 
   // Split a versioned filename into its name and version
-  public static final Pattern versionedPattern = Pattern.compile("^(.*)#(\\d++)$");
+  public static final Pattern versionedPattern =
+      Pattern.compile(JAR_PREFIX_FOR_REGEX + "(.*)#(\\d++)$");
 
   private final File deployDirectory;
 
@@ -341,17 +342,17 @@ public class JarDeployer implements Serializable {
   /**
    * Figure out the next version of a JAR file
    * 
-   * @param latestJarName The previous most recent version of the JAR file or original name
if there
-   *        wasn't one
+   * @param latestVersionedJarName The previous most recent version of the JAR file or original
name
+   *        if there wasn't one
    * @return The file that represents the next version
    */
-  private File getNextVersionJarFile(final String latestJarName) {
+  protected File getNextVersionJarFile(final String latestVersionedJarName) {
     String newFileName;
-    final Matcher matcher = versionedPattern.matcher(latestJarName);
+    final Matcher matcher = versionedPattern.matcher(latestVersionedJarName);
     if (matcher.find()) {
-      newFileName = matcher.group(1) + "#" + (Integer.parseInt(matcher.group(2)) + 1);
+      newFileName = JAR_PREFIX + matcher.group(1) + "#" + (Integer.parseInt(matcher.group(2))
+ 1);
     } else {
-      newFileName = JAR_PREFIX + latestJarName + "#1";
+      newFileName = JAR_PREFIX + latestVersionedJarName + "#1";
     }
 
     if (logger.isDebugEnabled()) {
@@ -529,26 +530,25 @@ public class JarDeployer implements Serializable {
    * @return The version number embedded in the filename
    */
   int extractVersionFromFilename(final File file) {
-    final Matcher matcher = versionedPattern.matcher(file.getAbsolutePath());
+    final Matcher matcher = versionedPattern.matcher(file.getName());
     matcher.find();
     return Integer.parseInt(matcher.group(2));
   }
 
-  private Set<String> findDistinctDeployedJars() {
-    final Pattern pattern = Pattern.compile("^" + JAR_PREFIX + "(.*)#\\d++$");
+  protected Set<String> findDistinctDeployedJars() {
 
     // Find all deployed JAR files
     final File[] oldFiles = this.deployDirectory.listFiles(new FilenameFilter() {
       @Override
       public boolean accept(final File file, final String name) {
-        return pattern.matcher(name).matches();
+        return versionedPattern.matcher(name).matches();
       }
     });
 
     // Now add just the original JAR name to the set
     final Set<String> jarNames = new HashSet<String>();
     for (File oldFile : oldFiles) {
-      Matcher matcher = pattern.matcher(oldFile.getName());
+      Matcher matcher = versionedPattern.matcher(oldFile.getName());
       matcher.find();
       jarNames.add(matcher.group(1));
     }
@@ -562,9 +562,9 @@ public class JarDeployer implements Serializable {
    * @param jarFilename Name of the JAR file that we want old versions of
    * @return Sorted array of files that are older versions of the given JAR
    */
-  private File[] findSortedOldVersionsOfJar(final String jarFilename) {
+  protected File[] findSortedOldVersionsOfJar(final String jarFilename) {
     // Find all matching files
-    final Pattern pattern = Pattern.compile("^" + JAR_PREFIX + jarFilename + "#\\d++$");
+    final Pattern pattern = Pattern.compile(JAR_PREFIX_FOR_REGEX + jarFilename + "#\\d++$");
     final File[] oldJarFiles = this.deployDirectory.listFiles(new FilenameFilter() {
       @Override
       public boolean accept(final File file, final String name) {

http://git-wip-us.apache.org/repos/asf/geode/blob/917dfa03/geode-core/src/test/java/org/apache/geode/internal/JarDeployerDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/JarDeployerDUnitTest.java
b/geode-core/src/test/java/org/apache/geode/internal/JarDeployerDUnitTest.java
index bcf4177..22f66a3 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/JarDeployerDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/JarDeployerDUnitTest.java
@@ -14,30 +14,9 @@
  */
 package org.apache.geode.internal;
 
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.RandomAccessFile;
-import java.nio.channels.FileLock;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.CyclicBarrier;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
 
 import org.apache.geode.cache.execute.Execution;
 import org.apache.geode.cache.execute.FunctionService;
@@ -51,6 +30,22 @@ import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileLock;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * Unit tests for the JarDeployer class
@@ -81,83 +76,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     deleteSavedJarFiles();
   }
 
-  @Test
-  public void testDeployFileAndChange() throws IOException, ClassNotFoundException {
-    final JarDeployer jarDeployer = new JarDeployer();
-    final File currentDir = new File(".").getAbsoluteFile();
-
-    // First deploy of the JAR file
-    File jarFile = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
-    byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDFACA");
-    jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-
-    try {
-      ClassPathLoader.getLatest().forName("JarDeployerDUnitDFACA");
-    } catch (ClassNotFoundException cnfex) {
-      fail("JAR file not correctly added to Classpath");
-    }
-
-    if (!jarFile.exists()) {
-      fail("JAR file not found where expected: " + jarFile.getName());
-    }
-
-    if (!doesFileMatchBytes(jarFile, jarBytes)) {
-      fail("Contents of JAR file do not match those provided: " + jarFile.getName());
-    }
-
-    // Now deploy an updated JAR file and make sure that the next version of the JAR file
-    // was created and the first one was deleted.
-    jarFile = getNextVersionJarFile(jarFile);
-    jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDFACB");
-    jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-
-    if (!jarFile.exists()) {
-      fail("JAR file not found where expected: " + jarFile.getName());
-    }
-
-    if (!doesFileMatchBytes(jarFile, jarBytes)) {
-      fail("Contents of JAR file do not match those provided: " + jarFile.getName());
-    }
-
-    try {
-      ClassPathLoader.getLatest().forName("JarDeployerDUnitDFACB");
-    } catch (ClassNotFoundException cnfex) {
-      fail("JAR file not correctly added to Classpath");
-    }
-
-    try {
-      ClassPathLoader.getLatest().forName("JarDeployerDUnitDFACA");
-      fail("Class should not be found on Classpath: JarDeployerDUnitDFACA");
-    } catch (ClassNotFoundException expected) { // expected
-    }
-  }
-
-  @Test
-  public void testDeployNoUpdateWhenNoChange() throws IOException, ClassNotFoundException
{
-    final JarDeployer jarDeployer = new JarDeployer();
-    final File currentDir = new File(".").getAbsoluteFile();
 
-    // First deploy of the JAR file
-    File jarFile = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
-    byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDNUWNC");
-    jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-
-    if (!jarFile.exists()) {
-      fail("JAR file not found where expected: " + jarFile.getName());
-    }
-
-    // Now deploy the same JAR file
-    jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-
-    if (!jarFile.exists()) {
-      fail("JAR file not found where expected: " + jarFile.getName());
-    }
-
-    jarFile = getNextVersionJarFile(jarFile);
-    if (jarFile.exists()) {
-      fail("JAR file should not have been created: " + jarFile.getName());
-    }
-  }
 
   @Test
   public void testDeployExclusiveLock() throws IOException, ClassNotFoundException {
@@ -166,7 +85,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     final VM vm = Host.getHost(0).getVM(0);
 
     // Deploy the Class JAR file
-    final File jarFile1 = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
+    final File jarFile1 = jarDeployer.getNextVersionJarFile("JarDeployerDUnit.jar");
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDELA");
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
 
@@ -223,7 +142,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     final VM vm = Host.getHost(0).getVM(0);
 
     // Deploy the JAR file
-    final File jarFile1 = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
+    final File jarFile1 = jarDeployer.getNextVersionJarFile("JarDeployerDUnit.jar");
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDSLA");
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
 
@@ -287,7 +206,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     final VM vm = Host.getHost(0).getVM(0);
 
     // Deploy the JAR file
-    final File jarFile1 = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
+    final File jarFile1 = jarDeployer.getNextVersionJarFile("JarDeployerDUnit.jar");
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitUSL");
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
 
@@ -337,7 +256,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     final File currentDir = new File(".").getAbsoluteFile();
     final VM vm = Host.getHost(0).getVM(0);
 
-    final File jarFile1 = getFirstVersionForTest(currentDir, "JarDeployerDUnit.jar");
+    final File jarFile1 = jarDeployer.getNextVersionJarFile("JarDeployerDUnit.jar");
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDUBAVMA");
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
 
@@ -347,7 +266,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
       fail("JAR file not correctly added to Classpath");
     }
 
-    final File jarFile2 = getNextVersionJarFile(jarFile1);
+    final File jarFile2 = jarDeployer.getNextVersionJarFile(jarFile1.getName());
     final byte[] vmJarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDUBAVMB");
     vm.invoke(new SerializableRunnable() {
       @Override
@@ -385,7 +304,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     }
 
     // Make sure the second deploy didn't create a 3rd version of the JAR file.
-    final File jarFile3 = getNextVersionJarFile(jarFile2);
+    final File jarFile3 = jarDeployer.getNextVersionJarFile(jarFile2.getName());
     if (jarFile3.exists()) {
       fail("JAR file should not have been created: " + jarFile3.getName());
     }
@@ -473,7 +392,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     final JarDeployer jarDeployer =
         new JarDeployer(distributedSystem.getConfig().getDeployWorkingDir());
 
-    File jarFile = getFirstVersionForTest(alternateDir, "JarDeployerDUnit.jar");
+    File jarFile = jarDeployer.getNextVersionJarFile("JarDeployerDUnit.jar");
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDTAC");
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
 
@@ -492,64 +411,12 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     }
   }
 
-  @Test
-  public void testDeployToInvalidDirectory() throws IOException, ClassNotFoundException {
-    final File alternateDir = new File("JarDeployerDUnit");
-    FileUtil.delete(new File("JarDeployerDUnit"));
-
-    final JarDeployer jarDeployer = new JarDeployer(alternateDir);
-    final CyclicBarrier barrier = new CyclicBarrier(2);
-    final byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDTID");
 
-    // Test to verify that deployment fails if the directory doesn't exist.
-    try {
-      jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-      fail("Exception should have been thrown due to missing deployment directory.");
-    } catch (IOException expected) {
-      // Expected.
-    }
-
-    // Test to verify that deployment succeeds if the directory doesn't
-    // initially exist, but is then created while the JarDeployer is looping
-    // looking for a valid directory.
-    Thread thread = new Thread() {
-      @Override
-      public void run() {
-        try {
-          barrier.await();
-        } catch (InterruptedException iex) {
-          fail("Interrupted while waiting.");
-        } catch (BrokenBarrierException bbex) {
-          fail("Broken barrier.");
-        }
-
-        try {
-          jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-        } catch (IOException ioex) {
-          fail("IOException received unexpectedly.");
-        } catch (ClassNotFoundException cnfex) {
-          fail("ClassNotFoundException received unexpectedly.");
-        }
-      }
-    };
-    thread.start();
-
-    try {
-      barrier.await();
-      Thread.sleep(500);
-      alternateDir.mkdir();
-      thread.join();
-    } catch (InterruptedException iex) {
-      fail("Interrupted while waiting.");
-    } catch (BrokenBarrierException bbex) {
-      fail("Broken barrier.");
-    }
-  }
-
-  boolean okayToResume;
 
   @Test
   public void testSuspendAndResume() throws IOException, ClassNotFoundException {
+    AtomicReference<Boolean> okayToResume = new AtomicReference<>(false);
+
     final JarDeployer jarDeployer = new JarDeployer();
     byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitSAR");
     final JarDeployer suspendingJarDeployer = new JarDeployer();
@@ -565,7 +432,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
         } catch (InterruptedException iex) {
           // It doesn't matter, just fail the test
         }
-        JarDeployerDUnitTest.this.okayToResume = true;
+        okayToResume.set(true);
         suspendingJarDeployer.resumeAll();
       }
     };
@@ -577,7 +444,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
       // It doesn't matter, just fail the test
     }
     jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
-    if (!this.okayToResume) {
+    if (!okayToResume.get()) {
       fail("JarDeployer did not suspend as expected");
     }
   }
@@ -701,50 +568,7 @@ public class JarDeployerDUnitTest extends JUnit4CacheTestCase {
     FileUtil.delete(new File("JarDeployerDUnit"));
   }
 
-  private File getFirstVersionForTest(final File saveDirfile, final String jarFilename) {
-    final File[] oldJarFiles = findSortedOldVersionsOfJar(saveDirfile, jarFilename);
-    if (oldJarFiles.length == 0) {
-      return new File(saveDirfile, JarDeployer.JAR_PREFIX + jarFilename + "#1");
-    }
-    return getNextVersionJarFile(oldJarFiles[0]);
-  }
-
-  private File getNextVersionJarFile(final File oldJarFile) {
-    final Matcher matcher = JarDeployer.versionedPattern.matcher(oldJarFile.getName());
-    matcher.find();
-    String newFileName = matcher.group(1) + "#" + (Integer.parseInt(matcher.group(2)) + 1);
-
-    return new File(oldJarFile.getParentFile(), newFileName);
-  }
-
-  private File[] findSortedOldVersionsOfJar(final File saveDirfile, final String jarFilename)
{
-    // Find all matching files
-    final Pattern pattern = Pattern.compile("^" + JarDeployer.JAR_PREFIX + jarFilename +
"#\\d++$");
-    final File[] oldJarFiles = saveDirfile.listFiles(new FilenameFilter() {
-      @Override
-      public boolean accept(final File file, final String name) {
-        return pattern.matcher(name).matches();
-      }
-    });
-
-    // Sort them in order from newest (highest version) to oldest
-    Arrays.sort(oldJarFiles, new Comparator<File>() {
-      @Override
-      public int compare(final File file1, final File file2) {
-        int file1Version = extractVersionFromFilename(file1);
-        int file2Version = extractVersionFromFilename(file2);
-        return file2Version - file1Version;
-      }
-    });
-
-    return oldJarFiles;
-  }
 
-  int extractVersionFromFilename(final File file) {
-    final Matcher matcher = JarDeployer.versionedPattern.matcher(file.getName());
-    matcher.find();
-    return Integer.parseInt(matcher.group(2));
-  }
 
   void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
     final OutputStream outStream = new FileOutputStream(jarFile);

http://git-wip-us.apache.org/repos/asf/geode/blob/917dfa03/geode-core/src/test/java/org/apache/geode/internal/JarDeployerTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/JarDeployerTest.java b/geode-core/src/test/java/org/apache/geode/internal/JarDeployerTest.java
new file mode 100644
index 0000000..9392838
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/JarDeployerTest.java
@@ -0,0 +1,197 @@
+/*
+ * 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;
+
+
+import static org.apache.geode.internal.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.apache.geode.test.junit.categories.UnitTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CyclicBarrier;
+
+@Category(UnitTest.class)
+public class JarDeployerTest {
+
+  private ClassBuilder classBuilder;
+
+  @Rule
+  public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+  @Rule
+  public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
+
+  @Before
+  public void setup() {
+    System.setProperty("user.dir", temporaryFolder.getRoot().getAbsolutePath());
+    classBuilder = new ClassBuilder();
+    ClassPathLoader.setLatestToDefault();
+  }
+
+  @Test
+  public void testDeployFileAndChange() throws IOException, ClassNotFoundException {
+    final JarDeployer jarDeployer = new JarDeployer();
+
+    // First deploy of the JAR file
+    byte[] jarBytes = this.classBuilder.createJarFromName("ClassA");
+    JarClassLoader jarClassLoader =
+        jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes})[0];
+    File deployedJar = new File(jarClassLoader.getFileCanonicalPath());
+
+    assertThat(deployedJar).exists();
+    assertThat(deployedJar.getName()).contains("#1");
+    assertThat(deployedJar.getName()).doesNotContain("#2");
+
+    assertThat(ClassPathLoader.getLatest().forName("ClassA")).isNotNull();
+
+    assertThat(doesFileMatchBytes(deployedJar, jarBytes));
+
+    // Now deploy an updated JAR file and make sure that the next version of the JAR file
+    // was created and the first one was deleted.
+    jarBytes = this.classBuilder.createJarFromName("ClassB");
+    JarClassLoader newJarClassLoader =
+        jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes})[0];
+    File nextDeployedJar = new File(newJarClassLoader.getFileCanonicalPath());
+
+    assertThat(nextDeployedJar.exists());
+    assertThat(nextDeployedJar.getName()).contains("#2");
+    assertThat(doesFileMatchBytes(nextDeployedJar, jarBytes));
+
+    assertThat(ClassPathLoader.getLatest().forName("ClassB")).isNotNull();
+
+    assertThatThrownBy(() -> ClassPathLoader.getLatest().forName("ClassA"))
+        .isExactlyInstanceOf(ClassNotFoundException.class);
+
+
+    assertThat(jarDeployer.findSortedOldVersionsOfJar("JarDeployerDUnit.jar")).hasSize(1);
+    assertThat(jarDeployer.findDistinctDeployedJars()).hasSize(1);
+  }
+
+  @Test
+  public void testDeployNoUpdateWhenNoChange() throws IOException, ClassNotFoundException
{
+    final JarDeployer jarDeployer = new JarDeployer();
+
+    // First deploy of the JAR file
+    byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDNUWNC");
+    JarClassLoader jarClassLoader =
+        jarDeployer.deploy(new String[] {"JarDeployerDUnit2.jar"}, new byte[][] {jarBytes})[0];
+    File deployedJar = new File(jarClassLoader.getFileCanonicalPath());
+
+    assertThat(deployedJar).exists();
+    assertThat(deployedJar.getName()).contains("#1");
+    JarClassLoader newJarClassLoader =
+        jarDeployer.deploy(new String[] {"JarDeployerDUnit2.jar"}, new byte[][] {jarBytes})[0];
+    assertThat(newJarClassLoader).isNull();
+  }
+
+  @Test
+  public void testDeployToInvalidDirectory() throws IOException, ClassNotFoundException {
+    final File alternateDir = new File(temporaryFolder.getRoot(), "JarDeployerDUnit");
+    FileUtil.delete(alternateDir);
+
+    final JarDeployer jarDeployer = new JarDeployer(alternateDir);
+    final CyclicBarrier barrier = new CyclicBarrier(2);
+    final byte[] jarBytes = this.classBuilder.createJarFromName("JarDeployerDUnitDTID");
+
+    // Test to verify that deployment fails if the directory doesn't exist.
+    assertThatThrownBy(() -> {
+      jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
+    }).isInstanceOf(IOException.class);
+
+    // Test to verify that deployment succeeds if the directory doesn't
+    // initially exist, but is then created while the JarDeployer is looping
+    // looking for a valid directory.
+    Thread thread = new Thread() {
+      @Override
+      public void run() {
+        try {
+          barrier.await();
+        } catch (InterruptedException iex) {
+          fail("Interrupted while waiting.");
+        } catch (BrokenBarrierException bbex) {
+          fail("Broken barrier.");
+        }
+
+        try {
+          jarDeployer.deploy(new String[] {"JarDeployerDUnit.jar"}, new byte[][] {jarBytes});
+        } catch (IOException ioex) {
+          fail("IOException received unexpectedly.");
+        } catch (ClassNotFoundException cnfex) {
+          fail("ClassNotFoundException received unexpectedly.");
+        }
+      }
+    };
+    thread.start();
+
+    try {
+      barrier.await();
+      Thread.sleep(500);
+      alternateDir.mkdir();
+      thread.join();
+    } catch (InterruptedException iex) {
+      fail("Interrupted while waiting.");
+    } catch (BrokenBarrierException bbex) {
+      fail("Broken barrier.");
+    }
+  }
+
+  @Test
+  public void testVersionNumberCreation() throws IOException, ClassNotFoundException {
+    JarDeployer jarDeployer = new JarDeployer();
+
+    File versionedName = jarDeployer.getNextVersionJarFile("myJar.jar");
+    assertThat(versionedName.getName()).isEqualTo(JarDeployer.JAR_PREFIX + "myJar.jar" +
"#1");
+
+    byte[] jarBytes = this.classBuilder.createJarFromName("ClassA");
+    JarClassLoader jarClassLoader =
+        jarDeployer.deploy(new String[] {"myJar.jar"}, new byte[][] {jarBytes})[0];
+    File deployedJar = new File(jarClassLoader.getFileCanonicalPath());
+
+    assertThat(deployedJar.getName()).isEqualTo(JarDeployer.JAR_PREFIX + "myJar.jar" + "#1");
+    assertThat(jarDeployer.getNextVersionJarFile(deployedJar.getName()).getName())
+        .isEqualTo(JarDeployer.JAR_PREFIX + "myJar.jar" + "#2");
+
+  }
+
+  @Test
+  public void testVersionNumberMatcher() throws IOException {
+
+    JarDeployer jarDeployer = new JarDeployer();
+    int version = jarDeployer.extractVersionFromFilename(
+        temporaryFolder.newFile(JarDeployer.JAR_PREFIX + "MyJar.jar" + "#1"));
+
+    assertThat(version).isEqualTo(1);
+  }
+
+  protected boolean doesFileMatchBytes(final File file, final byte[] bytes) throws IOException
{
+    return bytes == Files.readAllBytes(file.toPath());
+  }
+
+}


Mime
View raw message