Reputation: 4636
I am trying to start tomcat from within a simple java snippet but it is failing. I looked at the other questions and duplicated their answers but none worked.
What I'm doing is executing a command through the Runtime
:
Process process = Runtime.getRuntime().exec("startup.bat");
Please note that the command is simplified, I normally provide a fully qualified path, environment variables for CATALINA_HOME
and some CATALINA_OPTS
and made sure the system env variables are available.
What happens is that the process starts normally, but when it spawns the console it is immediately closed, as if Java itself kills it. I tried adding Thread.sleep(x)
to the main thread to see if keeping the application alive would let tomcat run but it didn't, the console still died even though the Java app kept running.
I even tried running Tomcat through an Ant
script to see if delegating to Ant
would work but again to no avail. Even trying through a third party .bat file didn't work
Please do not suggest Cargo, Maven or similar tools, I'm looking for a programmatic solution at the moment.
Upvotes: 1
Views: 97
Reputation: 4636
The problem was with how I was running the cmd script. The correct way is:
Runtime.getRuntime.exec("start /wait cmd /c catalina.bat run");
Upvotes: 1
Reputation: 158
Have a look at org.apache.tomcat.embed
.
This is how a minimal setup could look like:
package <yourpackage>
import java.io.File;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
public class Main {
public static void main(String[] args) throws Exception {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.valueOf(webPort));
StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
File additionWebInfClasses = new File("target/classes");
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClasses.getAbsolutePath(), "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
}
Upvotes: 0