Skip to content

Instantly share code, notes, and snippets.

@brianm
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianm/90f2b992090e9d3f2e0d to your computer and use it in GitHub Desktop.
Save brianm/90f2b992090e9d3f2e0d to your computer and use it in GitHub Desktop.
package com.example.testing;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.rules.ExternalResource;
import java.io.File;
import java.net.URI;
public class TomcatRule extends ExternalResource
{
private final String mavenCoordinates;
private Tomcat tomcat;
private File tmp;
private int port;
public TomcatRule(String mavenCoordinates)
{
this.mavenCoordinates = mavenCoordinates;
}
@Override
protected void before() throws Throwable
{
tmp = Files.createTempDir();
Preconditions.checkState(new File(tmp, "webapps").mkdirs(), "unable to create exploded webapp root");
File war = Maven.resolver()
.resolve(mavenCoordinates)
.withTransitivity()
.asSingleFile();
port = NetUtil.findUnusedPort();
tomcat = new Tomcat();
tomcat.setBaseDir(tmp.getAbsolutePath());
tomcat.setPort(port);
tomcat.addWebapp("/", war.getAbsolutePath());
tomcat.start();
}
public URI getBaseUri()
{
return URI.create("http://localhost:" + port + "/");
}
@Override
protected void after()
{
try {
tomcat.stop();
}
catch (LifecycleException e) {
throw new IllegalStateException("Unable to stop tomcat", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment