MigrationsRunner.java

  1. package de.dlr.shepard.neo4j;

  2. import org.neo4j.driver.AuthTokens;
  3. import org.neo4j.driver.Driver;
  4. import org.neo4j.driver.GraphDatabase;
  5. import org.neo4j.driver.exceptions.ServiceUnavailableException;

  6. import ac.simons.neo4j.migrations.core.Migrations;
  7. import ac.simons.neo4j.migrations.core.MigrationsConfig;
  8. import ac.simons.neo4j.migrations.core.MigrationsException;
  9. import de.dlr.shepard.util.PropertiesHelper;
  10. import lombok.extern.slf4j.Slf4j;

  11. @Slf4j
  12. public class MigrationsRunner {

  13.     private Migrations migrations;
  14.     private Driver driver;

  15.     public MigrationsRunner() {
  16.         var pHelper = new PropertiesHelper();
  17.         String username = pHelper.getProperty("neo4j.username");
  18.         String password = pHelper.getProperty("neo4j.password");
  19.         String host = "neo4j://" + pHelper.getProperty("neo4j.host");
  20.         var path = this.getClass().getClassLoader().getResource("neo4j/migrations");

  21.         driver = GraphDatabase.driver(host, AuthTokens.basic(username, password));
  22.         var config = MigrationsConfig.builder().withTransactionMode(MigrationsConfig.TransactionMode.PER_STATEMENT)
  23.                 .withPackagesToScan("de.dlr.shepard.neo4j.migrations").withLocationsToScan("file://" + path.toString())
  24.                 .build();

  25.         migrations = new Migrations(config, driver);
  26.     }

  27.     public void waitForConnection() {
  28.         while (true) {
  29.             try {
  30.                 driver.verifyConnectivity();
  31.                 break;
  32.             } catch (Exception e) {
  33.                 log.warn("Cannot connect to neo4j database. Retrying...");
  34.             }
  35.             try {
  36.                 Thread.sleep(1000);
  37.             } catch (InterruptedException e) {
  38.                 log.error("Cannot sleep while waiting for neo4j Connection");
  39.                 Thread.currentThread().interrupt();
  40.             }
  41.         }
  42.     }

  43.     public void apply() {
  44.         try {
  45.             migrations.apply();
  46.         } catch (ServiceUnavailableException e) {
  47.             log.error("Migrations cannot be executed because the neo4j database is not available");
  48.         } catch (MigrationsException e) {
  49.             log.error("An error occurred during the execution of the migrations: ", e);
  50.         }
  51.     }

  52. }