public final Config embedded(final String supplierClass) { return embedded(supplierClass, Optional.empty()); }
public final Config embedded(final Embedded embedded) { return embedded(Optional.of(embedded)); }
public final Config embedded(final String supplierClass, final Optional<String> version) { return embedded(Embedded.create(supplierClass, version)); }
/** * Creates the data source based on a `Config` instance. * * @param config * the config * @return the data source instance */ @SuppressWarnings("unchecked") public static DataSource<PreparedStatement, Row> fromConfig(final Config config) { return config.embedded().map(embedded -> { try { final Supplier<DataSource<PreparedStatement, Row>> supplier = (Supplier<DataSource<PreparedStatement, Row>>) Class .forName(embedded.supplierClass) .getConstructor(Config.class, Optional.class).newInstance(config, embedded.version); return supplier.get(); } catch (final Exception e) { throw new NdbcException("Can't load DataSource supplier for: " + embedded, e); } }).orElseGet(() -> { try { final Supplier<DataSource<PreparedStatement, Row>> supplier = (Supplier<DataSource<PreparedStatement, Row>>) Class .forName(config.dataSourceSupplierClass()) .getConstructor(Config.class).newInstance(config); return supplier.get(); } catch (final Exception e) { throw new NdbcException("Can't load DataSource supplier: " + config.dataSourceSupplierClass(), e); } }); }
final DataSource<PreparedStatement, Row> underlying = DataSource.fromConfig(config.embedded(Optional.empty())); return new ProxyDataSource<PreparedStatement, Row>(underlying) { @Override
@Override public DataSource<PreparedStatement, Row> get() { log.info("Starting embedded mysql " + version + " on port " + config.port()); final String password = config.password().orElseGet(() -> { throw new UnsupportedOperationException("Embedded mysql requires a password"); }); final DownloadConfig downloadConfig = DownloadConfig.aDownloadConfig() .withCacheDir(Paths.get(System.getProperty("user.home"), ".ndbc", "embedded_mysql").toString()) .build(); final MysqldConfig mysqldConfig = MysqldConfig.aMysqldConfig(version) .withPort(config.port()) .withUser(config.user(), password) .build(); final Builder builder = EmbeddedMysql.anEmbeddedMysql(mysqldConfig, downloadConfig); config.database().ifPresent(db -> builder.addSchema(SchemaConfig.aSchemaConfig(db).build())); final EmbeddedMysql mysql = builder.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> mysql.stop())); log.info("mysql " + version + " started"); DataSource<PreparedStatement, Row> underlying = DataSource.fromConfig(config.embedded(Optional.empty())); return new ProxyDataSource<PreparedStatement, Row>(underlying) { @Override public Config config() { return EmbeddedSupplier.this.config; } }; }
})); config = config.embedded(getProperty(prefix, properties, "embedded.supplierClass") .map(cls -> Embedded.create(cls, getProperty(prefix, properties, "embedded.version"))));