views:

413

answers:

3

I have a Maven project that starts a tomcat container for pre-integration-tests (jUnit Tests). Most of my tests require that the web-application under tests is restarted. So I'd like to restart the Tomcat container before each jUnit test is executed.

As for now I use the cargo-maven2-plugin to configure the tomcat container.

So, is it possible to start and stop the container with a java statement?

+1  A: 

Yes it is. But I am afriad, how much time will your tests take. You must fix your tests to not depend on server startup and shutdown. Its fine to run tests inside container, but container should be started once before tests.

Well to answer your question, you can execute the relevant .sh or .bat files from Java using system calls. Something like below,

Runtime r = Runtime.getRuntime();
Process p = r.exec("start.sh");
p.waitFor();
Adeel Ansari
+2  A: 

bootstrap.jar and commons-logging-api-1.1.1 from tomcat\bin to your classpath and the following snippet may help,

Bootstrap bootstrap=new Bootstrap();
bootstrap.setCatalinaHome("D:/apache-tomcat-5.5.28");

bootstrap.start();

Thread.sleep(60000);

bootstrap.stop();
Adi
+1  A: 

So, is it possible to start and stop the container with a java statement?

Your use case looks extremely weird (having to restart the container between tests) but let's not discuss this. To answer your question, yes it is possible and this can be done using Cargo's Java API.

To start a Tomcat container and deploy your war, you can do something like this in the setUp() method:

// (1) Optional step to install the container from a URL pointing to its distribution
Installer installer = new ZipURLInstaller(new URL("http://www.apache.org/dist/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.zip"));
installer.install();

// (2) Create the Cargo Container instance wrapping our physical container
LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory()
        .createConfiguration("tomcat6x"), ContainerType.INSTALLED, ConfigurationType.STANDALONE);
container = (InstalledLocalContainer) new DefaultContainerFactory()
        .createContainer("tomcat6x", ContainerType.INSTALLED, configuration);
container.setHome(installer.getHome());

// (3) Statically deploy some WAR (optional)
WAR deployable = new WAR("./webapp-testing-webapp/target/webapp-testing-webapp-1.0.war");
deployable.setContext("ROOT");
configuration.addDeployable(deployable);

// (4) Start the container
container.start();

And stop it in the tearDown() method.

// (6) Stop the container
container.stop();
Pascal Thivent
Thanks, didn't think of Cargo for this.
Adeel Ansari
@Vinegar It's more usual to use Cargo through plugins (at least I think so) but Cargo *is* actually a Java API before all. And this can be handy (more and more containers do offer an embedded API but Cargo's API is "unified").
Pascal Thivent
Yes, I tend to agree. Thanks.
Adeel Ansari