[36] | 1 | package geniusweb.runserver;
|
---|
| 2 |
|
---|
| 3 | import java.io.File;
|
---|
| 4 |
|
---|
| 5 | import org.apache.catalina.LifecycleException;
|
---|
| 6 | import org.apache.catalina.startup.Tomcat;
|
---|
| 7 |
|
---|
| 8 | class EmbeddedTomcat {
|
---|
| 9 | private Tomcat tomcat = new Tomcat();
|
---|
| 10 |
|
---|
| 11 | public void start() {
|
---|
| 12 | try {
|
---|
| 13 | // If I don't want to copy files around then the base directory must
|
---|
| 14 | // be '.'
|
---|
| 15 | String baseDir = ".";
|
---|
| 16 | tomcat.setPort(8080);
|
---|
| 17 | tomcat.setBaseDir(baseDir);
|
---|
| 18 | tomcat.getHost().setAppBase(baseDir);
|
---|
| 19 | tomcat.getHost().setDeployOnStartup(true);
|
---|
| 20 | tomcat.getHost().setAutoDeploy(true);
|
---|
| 21 | tomcat.start();
|
---|
| 22 | } catch (LifecycleException e) {
|
---|
| 23 | throw new RuntimeException(e);
|
---|
| 24 | }
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | public void stop() {
|
---|
| 28 | try {
|
---|
| 29 | tomcat.stop();
|
---|
| 30 | tomcat.destroy();
|
---|
| 31 | // Tomcat creates a work folder where the temporary files are stored
|
---|
| 32 | } catch (LifecycleException e) {
|
---|
| 33 | throw new RuntimeException(e);
|
---|
| 34 | }
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 | /**
|
---|
| 38 | * Deploys the webapp contained in this project
|
---|
| 39 | *
|
---|
| 40 | * @param appName the name to use on the server
|
---|
| 41 | */
|
---|
| 42 | public void deploy(String appName) {
|
---|
| 43 | deployWar(appName, new File("src/main/webapp"));
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | /**
|
---|
| 47 | * Deploys the webapp in the given war
|
---|
| 48 | *
|
---|
| 49 | * @param appName the name to use on the server
|
---|
| 50 | * @param warfile the warfile to deploy. Should include ".war" extension.
|
---|
| 51 | */
|
---|
| 52 | public void deployWar(String appName, File warfile) {
|
---|
| 53 | tomcat.addWebapp(tomcat.getHost(), "/" + appName,
|
---|
| 54 | warfile.getAbsolutePath());
|
---|
| 55 |
|
---|
| 56 | }
|
---|
| 57 |
|
---|
| 58 | public String getApplicationUrl(String appName) {
|
---|
| 59 | return String.format("http://%s:%d/%s", tomcat.getHost().getName(),
|
---|
| 60 | tomcat.getConnector().getLocalPort(), appName);
|
---|
| 61 | }
|
---|
| 62 | }
|
---|