Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deploy *.war file with parameters

I have web project with REST API. I want to deploy 5 copies of it on tomcat server. For example:
test1.war => URL: http://localhost:8080/test1/api
test2.war => URL: http://localhost:8080/test2/api
test3.war => URL: http://localhost:8080/test3/api
...
The problem is that each war file should use different config file. I know that I can set env variables using export CATALINA_OPTs="Dparam1=/usr/config1.txt". Then I need to change source code inside each war file in order to read param1 for test1.war, param2 for test2.war. But each war file should be the same (only different names). Theoretically the perfect solution is something like this:

    deploy test1.war -conf <path1>
    deploy test2.war -conf <path2>
    deploy test3.war -conf <path3>


Is it possible to do it in the tomcat? Is there any alternative for doing this?

like image 977
Maksym Avatar asked Oct 25 '17 08:10

Maksym


1 Answers

I decided to get appropriate configuration file for app at the run time.

1) Get the path of the current running MainApp.class inside war (e.g. warname.war) file with such code:

String path = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = java.net.URLDecoder.decode(path, "UTF-8");
// decodedPath - "D:/apache-tomcat-7.0.81/apache-tomcat-7.0.81/webapps/warname/WEB-INF/classes/com/gieseckedevrient/rsp/servertester/MainApp.class"


2) Parse this decoded path in order to get only "warname":

String parentName = "";
java.io.File parentFile = null;
while (!"WEB-INF".equals(parentName)) {
  File file = new File(decodedPath);
  parentFile = file.getParentFile();
  parentName = parentFile.getName();
  decodedPath = parentFile.getAbsolutePath();               
  }
String realWarName = parentFile.getParentFile().getName();


3) Create file "setenv.bat" in the TOMCAT_HOME}/bin/ and insert this code there (warname.config.file for warname.war and warname2.config.file for warname2.war):

set CATALINA_OPTS=-Dwarname.config.file=D:\app.properties -Dwarname2.config.file=D:\app2.properties


4) Read appropriate env variable with such code:

String configFile = System.getProperty(realWarName + ".config.file");
// configFile - "D:\app.properties" for warname.war
// configFile - "D:\app2.properties" for warname2.war
like image 93
Maksym Avatar answered Sep 30 '22 14:09

Maksym