Java Code Examples for org.testcontainers.containers.PostgreSQLContainer

The following examples show how to use org.testcontainers.containers.PostgreSQLContainer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: waltz   Source File: DITestingConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() {
    HikariConfig dsConfig = new HikariConfig();
    postgreSQLContainer.start();
    dsConfig.setJdbcUrl(format("jdbc:postgresql://%s:%s/%s",
            postgreSQLContainer.getContainerIpAddress(),
            postgreSQLContainer.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT),
            postgreSQLContainer.getDatabaseName()));
    dsConfig.setUsername(postgreSQLContainer.getUsername());
    dsConfig.setPassword(postgreSQLContainer.getPassword());
    dsConfig.setSchema("test");
    dsConfig.setDriverClassName("org.postgresql.Driver");
    dsConfig.setMaximumPoolSize(5);
    dsConfig.setMinimumIdle(2);
    return new HikariDataSource(dsConfig);
}
 
Example 2
Source Project: presto   Source File: TestingPostgreSqlServer.java    License: Apache License 2.0 5 votes vote down vote up
public TestingPostgreSqlServer()
{
    dockerContainer = new PostgreSQLContainer("postgres:10.3")
            .withDatabaseName(DATABASE)
            .withUsername(USER)
            .withPassword(PASSWORD);
    dockerContainer.start();
}
 
Example 3
@Override
protected PostgreSQLContainer createContainer() {
    return new PostgreSQLContainer<>(POSTGRES_IMAGE)
            .withUsername(DB_USERNAME)
            .withPassword(DB_PASSWORD)
            .withDatabaseName(DebeziumPostgresResource.DB_NAME)
            .withInitScript("initPostgres.sql");
}
 
Example 4
Source Project: pgadba   Source File: ConnectUtil.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Opens a DataSource to the supplied database.
 * @param postgres the docker database
 * @return a datasource
 */
public static DataSource openDb(PostgreSQLContainer postgres) {
  return DataSourceFactory.newFactory("org.postgresql.adba.PgDataSourceFactory")
      .builder()
      .url("jdbc:postgresql://" + postgres.getContainerIpAddress() + ":" + postgres.getMappedPort(5432)
          + "/" + postgres.getDatabaseName())
      .username(postgres.getUsername())
      .password(postgres.getPassword())
      .sessionProperty(AdbaSessionProperty.TRANSACTION_ISOLATION,
          AdbaSessionProperty.TransactionIsolation.REPEATABLE_READ)
      .build();
}
 
Example 5
Source Project: pgadba   Source File: ConnectUtil.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Opens a DataSource to the supplied database that sends all traffic over tls.
 * @param postgres the docker database
 * @return a datasource
 */
public static DataSource openDbWithTls(PostgreSQLContainer postgres) {
  return DataSourceFactory.newFactory("org.postgresql.adba.PgDataSourceFactory")
      .builder()
      .url("jdbc:postgresql://" + postgres.getContainerIpAddress() + ":" + postgres.getMappedPort(5432)
          + "/" + postgres.getDatabaseName())
      .username(postgres.getUsername())
      .password(postgres.getPassword())
      .sessionProperty(AdbaSessionProperty.TRANSACTION_ISOLATION,
          AdbaSessionProperty.TransactionIsolation.REPEATABLE_READ)
      .sessionProperty(PgSessionProperty.SSL, true)
      .build();
}
 
Example 6
Source Project: pgadba   Source File: DatabaseHolder.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * returns a new database, instead of the cached one.
 * @return a docker instance running a postgresql database
 */
public static PostgreSQLContainer getNew() {
  PostgreSQLContainer container = new PostgreSQLContainer();
  container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw"));
  container.start();
  return container;
}
 
Example 7
Source Project: pgadba   Source File: DatabaseHolder.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * returns a new database that requires TLS, instead of the cached one.
 * @return a docker instance running a postgresql database
 */
public static PostgreSQLContainer getNewWithTls() {
  PostgreSQLContainer container = new PostgreSQLContainer("capitol/postgresql-tls:debian-stretch-postgresql10");
  container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw"));
  container.start();

  return container;
}
 
Example 8
Source Project: pgadba   Source File: DatabaseHolder.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * returns a new database that that runs postgresql 11.
 * @return a docker instance running a postgresql 11 database
 */
public static PostgreSQLContainer getNew11() {
  PostgreSQLContainer container = new PostgreSQLContainer("capitol/debian-buster-postgresql11-tls:latest");
  container.withTmpFs(singletonMap("/var/lib/postgresql/data", "rw"));
  container.start();

  return container;
}
 
Example 9
Source Project: syndesis   Source File: SqlMetaDataITCase.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
@Parameters
public static Collection<Object> databaseContainerImages() {
    return Arrays.asList(
            //new DerbyContainer(),  //
            new PostgreSQLContainer<>(),
            new MariaDBContainer<>()
            );
}
 
Example 10
private DatabaseInstance(DatabaseConfig config) {
    String initdbArgs = config.initdbProperties.entrySet().stream()
            .map(e -> String.format("--%s=%s", e.getKey(), e.getValue()))
            .collect(Collectors.joining(" "));

    Map<String, String> serverProperties = new HashMap<>(config.configProperties);

    serverProperties.putIfAbsent("fsync", "off");
    serverProperties.putIfAbsent("full_page_writes", "off");
    serverProperties.putIfAbsent("max_connections", "300");

    String postgresArgs = serverProperties.entrySet().stream()
            .map(e -> String.format("-c %s=%s", e.getKey(), e.getValue()))
            .collect(Collectors.joining(" "));

    container = new PostgreSQLContainer(config.dockerImage) {
        @Override
        protected void configure() {
            super.configure();
            addEnv("POSTGRES_INITDB_ARGS", "--nosync " + initdbArgs);
            setCommand("postgres " + postgresArgs);
        }
    };

    if (config.tmpfsEnabled) {
        Consumer<CreateContainerCmd> consumer = cmd -> cmd.getHostConfig()
                .withTmpFs(ImmutableMap.of("/var/lib/postgresql/data", config.tmpfsOptions));
        container.withCreateContainerCmdModifier(consumer);
    }

    container.withUsername(DEFAULT_POSTGRES_USERNAME);
    container.withPassword(DEFAULT_POSTGRES_PASSWORD);

    config.customizers.forEach(c -> c.customize(container));

    container.start();
    container.followOutput(new Slf4jLogConsumer(LoggerFactory.getLogger(DockerPostgresDatabaseProvider.class)));

    semaphore = new Semaphore(Integer.parseInt(serverProperties.get("max_connections")));
}
 
Example 11
Source Project: vertx-sql-client   Source File: ContainerPgRule.java    License: Apache License 2.0 5 votes vote down vote up
private void initServer(String version) throws Exception {
  File setupFile = getTestResource("resources" + File.separator + "create-postgres.sql");
  
  server = (PostgreSQLContainer) new PostgreSQLContainer("postgres:" + version)
      .withDatabaseName("postgres")
      .withUsername("postgres")
      .withPassword("postgres")
      .withCopyFileToContainer(MountableFile.forHostPath(setupFile.toPath()), "/docker-entrypoint-initdb.d/create-postgres.sql");
  if(ssl) {
    server.withCopyFileToContainer(MountableFile.forHostPath(getTestResource("resources" +File.separator + "server.crt").toPath()), "/server.crt")
          .withCopyFileToContainer(MountableFile.forHostPath(getTestResource("resources" +File.separator + "server.key").toPath()), "/server.key")
          .withCopyFileToContainer(MountableFile.forHostPath(getTestResource("ssl.sh").toPath()), "/docker-entrypoint-initdb.d/ssl.sh");
  }
}
 
Example 12
Source Project: vertx-sql-client   Source File: ContainerPgRule.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized PgConnectOptions startServer(String databaseVersion) throws Exception {
  initServer(databaseVersion);
  server.start();

  return new PgConnectOptions()
      .setPort(server.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT))
      .setHost(server.getContainerIpAddress())
      .setDatabase("postgres")
      .setUser("postgres")
      .setPassword("postgres");
}
 
Example 13
Source Project: vertx-sql-client   Source File: PgTemplateTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startDatabase() {
  server = new PostgreSQLContainer("postgres:" + "10.10")
    .withDatabaseName("postgres")
    .withUsername("postgres")
    .withPassword("postgres");
  server.start();
}
 
Example 14
Source Project: vertx-sql-client   Source File: PgTemplateTestBase.java    License: Apache License 2.0 5 votes vote down vote up
public static PgConnectOptions connectOptions() {
  Integer port = server.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT);
  String ip = server.getContainerIpAddress();
  return new PgConnectOptions()
    .setPort(port)
    .setHost(ip)
    .setDatabase("postgres")
    .setUser("postgres")
    .setPassword("postgres");
}
 
Example 15
Source Project: nomulus   Source File: JpaTransactionManagerRule.java    License: Apache License 2.0 5 votes vote down vote up
private static JdbcDatabaseContainer create() {
  PostgreSQLContainer container =
      new PostgreSQLContainer(NomulusPostgreSql.getDockerTag())
          .withDatabaseName(POSTGRES_DB_NAME);
  container.start();
  return container;
}
 
Example 16
Source Project: testcontainers-java   Source File: CustomizablePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testSimple() throws SQLException {
    try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:9.6.8")
            .withDatabaseName(DB_NAME)
            .withUsername(USER)
            .withPassword(PWD)) {

        postgres.start();

        ResultSet resultSet = performQuery(postgres, "SELECT 1");

        int resultSetInt = resultSet.getInt(1);
        assertEquals("A basic SELECT query succeeds", 1, resultSetInt);
    }
}
 
Example 17
Source Project: testcontainers-java   Source File: SimplePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testSimple() throws SQLException {
    try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>()) {
        postgres.start();

        ResultSet resultSet = performQuery(postgres, "SELECT 1");
        int resultSetInt = resultSet.getInt(1);
        assertEquals("A basic SELECT query succeeds", 1, resultSetInt);
    }
}
 
Example 18
Source Project: testcontainers-java   Source File: SimplePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCommandOverride() throws SQLException {
    try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withCommand("postgres -c max_connections=42")) {
        postgres.start();

        ResultSet resultSet = performQuery(postgres, "SELECT current_setting('max_connections')");
        String result = resultSet.getString(1);
        assertEquals("max_connections should be overriden", "42", result);
    }
}
 
Example 19
Source Project: testcontainers-java   Source File: SimplePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testUnsetCommand() throws SQLException {
    try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withCommand("postgres -c max_connections=42").withCommand()) {
        postgres.start();

        ResultSet resultSet = performQuery(postgres, "SELECT current_setting('max_connections')");
        String result = resultSet.getString(1);
        assertNotEquals("max_connections should not be overriden", "42", result);
    }
}
 
Example 20
Source Project: testcontainers-java   Source File: SimplePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testExplicitInitScript() throws SQLException {
    try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>().withInitScript("somepath/init_postgresql.sql")) {
        postgres.start();

        ResultSet resultSet = performQuery(postgres, "SELECT foo FROM bar");

        String firstColumnValue = resultSet.getString(1);
        assertEquals("Value from init script should equal real value", "hello world", firstColumnValue);
    }
}
 
Example 21
Source Project: testcontainers-java   Source File: SimplePostgreSQLTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testWithAdditionalUrlParamInJdbcUrl() {
    try (PostgreSQLContainer postgres = new PostgreSQLContainer<>()
        .withUrlParam("charSet", "UNICODE")) {

        postgres.start();
        String jdbcUrl = postgres.getJdbcUrl();
        assertThat(jdbcUrl, containsString("?"));
        assertThat(jdbcUrl, containsString("&"));
        assertThat(jdbcUrl, containsString("charSet=UNICODE"));
    }
}
 
Example 22
Source Project: tutorials   Source File: PostgreSqlContainerLiveTest.java    License: MIT License 5 votes vote down vote up
private ResultSet performQuery(PostgreSQLContainer postgres, String query) throws SQLException {
    String jdbcUrl = postgres.getJdbcUrl();
    String username = postgres.getUsername();
    String password = postgres.getPassword();
    Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
    return conn.createStatement()
        .executeQuery(query);
}
 
Example 23
Source Project: apicurio-registry   Source File: KafkaConnectConverterIT.java    License: Apache License 2.0 4 votes vote down vote up
private Connection getConnection(PostgreSQLContainer<?> postgresContainer) throws SQLException {
    return DriverManager.getConnection(postgresContainer.getJdbcUrl(), postgresContainer.getUsername(),
        postgresContainer.getPassword());
}
 
Example 24
Source Project: apicurio-registry   Source File: KafkaConnectConverterIT.java    License: Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void startContainers() {
    String apicurioVersion = System.getProperty("project.version");
    assertNotNull(apicurioVersion);

    Path converterDistro = Paths.get(System.getProperty("user.dir"), "..", "distro", "connect-converter",
            "target", "apicurio-kafka-connect-converter-" + apicurioVersion + "-converter.tar.gz");

    if (Files.notExists(converterDistro)) {
        LOGGER.info("Connecter distribution {}", converterDistro.toString());
        throw new IllegalStateException("Kafka connect converter distribution is not present");
    }

    ImageFromDockerfile apicurioDebeziumImage = new ImageFromDockerfile()
            .withFileFromPath("converter-distro.tar.gz", converterDistro)
            .withDockerfileFromBuilder(builder -> builder
                    .from("debezium/connect:1.1.1.Final")
                    .env("KAFKA_CONNECT_DEBEZIUM_DIR", "$KAFKA_CONNECT_PLUGINS_DIR/debezium-connector-postgres")
                    .copy("converter-distro.tar.gz", "$KAFKA_CONNECT_DEBEZIUM_DIR/apicurio-kafka-connect-converter.tar.gz")
                    .run("cd $KAFKA_CONNECT_DEBEZIUM_DIR && tar -xvf apicurio-kafka-connect-converter.tar.gz")
                    .build());

    if (!TestUtils.isExternalRegistry()) {
        Testcontainers.exposeHostPorts(8081);
    }

    Testcontainers.exposeHostPorts(9092);
    kafka = new KafkaContainer();
    kafka.addEnv("KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", "1");
    kafka.addEnv("KAFKA_TRANSACTION_STATE_LOG_MIN_ISR", "1");
    kafka.addExposedPorts(9092);
    kafka.withCreateContainerCmdModifier(cmd -> {
        cmd
                .withHostName("localhost")
                .withPortBindings(new PortBinding(Ports.Binding.bindPort(9092), new ExposedPort(9092)));
    });
    kafka.start();

    Network network = Network.newNetwork();

    postgres = new PostgreSQLContainer<>("debezium/postgres:11")
          .withNetwork(network)
          .withNetworkAliases("postgres");
    postgres.start();

    debeziumContainer = new DebeziumContainer("dummy-version");
    debeziumContainer.setImage(apicurioDebeziumImage);
    debeziumContainer.withNetwork(network)
          .withEnv("BOOTSTRAP_SERVERS", "host.testcontainers.internal:9092")
          .withLogConsumer(new Slf4jLogConsumer(LOGGER));
    debeziumContainer.setWaitStrategy(
            Wait.forHttp("/connectors")
            .forPort(8083)
            .forStatusCode(200)
            .withReadTimeout(Duration.ofSeconds(3))
            .withStartupTimeout(Duration.ofSeconds(300)));
    debeziumContainer.start();

}
 
Example 25
Source Project: pgadba   Source File: DatabaseHolder.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static PostgreSQLContainer getCached() {
  return postgres;
}
 
Example 26
Source Project: quarkus   Source File: VaultTestExtension.java    License: Apache License 2.0 4 votes vote down vote up
public void start() throws InterruptedException, IOException {

        log.info("start containers on " + System.getProperty("os.name"));

        new File(HOST_POSTGRES_TMP_CMD).mkdirs();

        Network network = Network.newNetwork();

        postgresContainer = new PostgreSQLContainer<>()
                .withDatabaseName(DB_NAME)
                .withUsername(DB_USERNAME)
                .withPassword(DB_PASSWORD)
                .withNetwork(network)
                .withFileSystemBind(HOST_POSTGRES_TMP_CMD, CONTAINER_TMP_CMD)
                .withNetworkAliases(POSTGRESQL_HOST)
                .withExposedPorts(POSTGRESQL_PORT)
                .withClasspathResourceMapping("postgres-init.sql", TMP_POSTGRES_INIT_SQL_FILE, READ_ONLY);

        postgresContainer.setPortBindings(Arrays.asList(MAPPED_POSTGRESQL_PORT + ":" + POSTGRESQL_PORT));

        String configFile = useTls() ? "vault-config-tls.json" : "vault-config.json";

        log.info("starting vault with url=" + VAULT_URL + " and config file=" + configFile);

        new File(HOST_VAULT_TMP_CMD).mkdirs();

        vaultContainer = new GenericContainer<>("vault:" + getVaultVersion())
                .withExposedPorts(VAULT_PORT)
                .withEnv("SKIP_SETCAP", "true")
                .withEnv("VAULT_SKIP_VERIFY", "true") // this is internal to the container
                .withEnv("VAULT_ADDR", VAULT_URL)
                .withNetwork(network)
                .withFileSystemBind(HOST_VAULT_TMP_CMD, CONTAINER_TMP_CMD)
                .withClasspathResourceMapping(configFile, TMP_VAULT_CONFIG_JSON_FILE, READ_ONLY)
                .withClasspathResourceMapping("vault-tls.key", "/tmp/vault-tls.key", READ_ONLY)
                .withClasspathResourceMapping("vault-tls.crt", "/tmp/vault-tls.crt", READ_ONLY)
                .withClasspathResourceMapping("vault.policy", TMP_VAULT_POLICY_FILE, READ_ONLY)
                .withClasspathResourceMapping("vault-postgres-creation.sql", TMP_VAULT_POSTGRES_CREATION_SQL_FILE, READ_ONLY)
                .withCommand("server", "-log-level=debug", "-config=" + TMP_VAULT_CONFIG_JSON_FILE);

        vaultContainer.setPortBindings(Arrays.asList(VAULT_PORT + ":" + VAULT_PORT));

        postgresContainer.start();
        execPostgres(format("psql -U %s -d %s -f %s", DB_USERNAME, DB_NAME, TMP_POSTGRES_INIT_SQL_FILE));

        Consumer<OutputFrame> consumer = outputFrame -> System.out.print("VAULT >> " + outputFrame.getUtf8String());
        vaultContainer.setLogConsumers(Arrays.asList(consumer));
        vaultContainer.start();

        initVault();
        log.info("vault has started with root token: " + rootToken);
    }
 
Example 27
Source Project: pulsar   Source File: JdbcPostgresSinkTester.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected PostgreSQLContainer createSinkService(PulsarCluster cluster) {
    return (PostgreSQLContainer) new PostgreSQLContainer()
        .withNetworkAliases(POSTGRES);
}
 
Example 28
Source Project: nomulus   Source File: GenerateSqlSchemaCommand.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  // Start PostgreSQL if requested.
  if (startPostgresql) {
    // Complain if the user has also specified either --db_host or --db_port.
    if (databaseHost != null || databasePort != null) {
      System.err.println(DB_OPTIONS_CLASH);
      // TODO: it would be nice to exit(1) here, but this breaks testability.
      return;
    }

    // Start the container and store the address information.
    postgresContainer =
        new PostgreSQLContainer(NomulusPostgreSql.getDockerTag())
            .withDatabaseName(DB_NAME)
            .withUsername(DB_USERNAME)
            .withPassword(DB_PASSWORD);
    postgresContainer.start();
    databaseHost = postgresContainer.getContainerIpAddress();
    databasePort = postgresContainer.getMappedPort(POSTGRESQL_PORT);
  } else if (databaseHost == null) {
    System.err.println(
        "You must specify either --start_postgresql to start a PostgreSQL database in a\n"
            + "docker instance, or specify --db_host (and, optionally, --db_port) to identify\n"
            + "the location of a running instance.  To start a long-lived instance (suitable\n"
            + "for running this command multiple times) run this:\n\n"
            + "  docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\\n"
            + "    -d postgres:9.6.12\n\n"
            + "Copy the container id output from the command, then run:\n\n"
            + "  docker inspect <container-id> | grep IPAddress\n\n"
            + "To obtain the value for --db-host.\n");
    // TODO(mmuller): need exit(1), see above.
    return;
  }

  // use the default port if non has been defined.
  if (databasePort == null) {
    databasePort = POSTGRESQL_PORT;
  }

  try {
    File outputFile = new File(outFile);

    // Generate the copyright header (this file gets checked for copyright).  The schema exporter
    // appends to the existing file, so this has the additional desired effect of clearing any
    // existing data in the file.
    String copyright =
        "-- Copyright 2019 The Nomulus Authors. All Rights Reserved.\n"
            + "--\n"
            + "-- Licensed under the Apache License, Version 2.0 (the \"License\");\n"
            + "-- you may not use this file except in compliance with the License.\n"
            + "-- You may obtain a copy of the License at\n"
            + "--\n"
            + "--     http://www.apache.org/licenses/LICENSE-2.0\n"
            + "--\n"
            + "-- Unless required by applicable law or agreed to in writing, software\n"
            + "-- distributed under the License is distributed on an \"AS IS\" BASIS,\n"
            + "-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
            + "-- See the License for the specific language governing permissions and\n"
            + "-- limitations under the License.\n";
    try {
      Files.write(outputFile.toPath(), copyright.getBytes(UTF_8));
    } catch (IOException e) {
      System.err.println("Error writing sql file: " + e);
      e.printStackTrace();
      System.exit(1);
    }

    HibernateSchemaExporter exporter =
        HibernateSchemaExporter.create(
            "jdbc:postgresql://"
                + databaseHost
                + ":"
                + databasePort
                + "/"
                + DB_NAME
                + "?useSSL=false",
            DB_USERNAME,
            DB_PASSWORD);
    exporter.export(PersistenceXmlUtility.getManagedClasses(), outputFile);

  } finally {
    if (postgresContainer != null) {
      postgresContainer.stop();
    }
  }
}
 
Example 29
Source Project: nomulus   Source File: PostgresqlCommand.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Starts the database if appropriate.
 *
 * <p>Returns true if the database was successfully initialized, false if not.
 */
private boolean initializeDatabase() {
  // Start PostgreSQL if requested.
  if (startPostgresql) {
    // Complain if the user has also specified either --db_host or --db_port.
    if (databaseHost != null || databasePort != null) {
      System.err.println(DB_OPTIONS_CLASH);
      // TODO: it would be nice to exit(1) here, but this breaks testability.
      return false;
    }

    // Start the container and store the address information.
    postgresContainer =
        new PostgreSQLContainer(NomulusPostgreSql.getDockerTag())
            .withDatabaseName(DB_NAME)
            .withUsername(DB_USERNAME)
            .withPassword(DB_PASSWORD);
    try {
      onContainerCreate();
    } catch (Exception e) {
      logger.atSevere().withCause(e).log("Error in container callback hook.");
      return false;
    }
    postgresContainer.start();
    databaseHost = postgresContainer.getContainerIpAddress();
    databasePort = postgresContainer.getMappedPort(POSTGRESQL_PORT);
  } else if (databaseHost == null) {
    System.err.println(
        "You must specify either --start_postgresql to start a PostgreSQL database in a\n"
            + "docker instance, or specify --db_host (and, optionally, --db_port) to identify\n"
            + "the location of a running instance.  To start a long-lived instance (suitable\n"
            + "for running this command multiple times) run this:\n\n"
            + "  docker run --rm --name some-postgres -e POSTGRES_PASSWORD=domain-registry \\\n"
            + "    -d "
            + NomulusPostgreSql.getDockerTag()
            + "\n\nCopy the container id output from the command, then run:\n\n"
            + "  docker inspect <container-id> | grep IPAddress\n\n"
            + "To obtain the value for --db-host.\n");
    // TODO(mmuller): need exit(1), see above.
    return false;
  }

  // use the default port if non has been defined.
  if (databasePort == null) {
    databasePort = POSTGRESQL_PORT;
  }

  return true;
}
 
Example 30
Source Project: spring-session   Source File: DatabaseContainers.java    License: Apache License 2.0 4 votes vote down vote up
static PostgreSQLContainer postgreSql9() {
	return new PostgreSql9Container();
}