Lautaro Paskevicius
Lautaro Paskevicius

Reputation: 196

Run java method to start database before Tomcat deploy

I am developing a web project with HSQLDB persistence. My database instance is on server mode, therefore, I need to run a cmd script/ Java method to access my schema.

Tomcat is the container I use to drop my war on port 8080. Gradle is my build system.

Currently I am using the following main method before I deploy my app to properly access my database on runtime:

public static void main(String[] args) throws IOException, ServerAcl.AclFormatException {

    final String URL = "file:~/db/cursago";
    String user = "user";
    String password = "password";
    HsqlProperties p = new HsqlProperties();
    p.setProperty("server.database.0",URL+";user="+user+";password="+password);
    p.setProperty("server.dbname.0","cursago");

    Server server = new Server();
    server.setProperties(p);
    server.setLogWriter(null);
    server.setErrWriter(null);
    server.start();
    System.out.println("Database is running with path: " + URL);
    System.out.println("Username: " + user+", Password: " + password);

}

I would like to know if there's a way of making Tomcat/Gradle/IntelliJ IDEA run this main method before a project deploy, instead of running this script by hand.

Upvotes: 1

Views: 303

Answers (1)

sschrass
sschrass

Reputation: 7166

from here:

you could run the content of your main in the onApplicationEvent like:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
        final String URL = "file:~/db/cursago";
        String user = "user";
        String password = "password";
        HsqlProperties p = new HsqlProperties();
        p.setProperty("server.database.0",URL+";user="+user+";password="+password);
        p.setProperty("server.dbname.0","cursago");

        Server server = new Server();
        server.setProperties(p);
        server.setLogWriter(null);
        server.setErrWriter(null);
        server.start();
        System.out.println("Database is running with path: " + URL);
        System.out.println("Username: " + user+", Password: " + password);               
    }
}

This will trigger on every event, that could be application started or redeployed and happens before your application handles requests.

You also can wire in your properties.

There are some difficulties if the server is already running and it can't run in this scope only.

Upvotes: 0

Related Questions