repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/ReusableStringTemplate3StatementLocator.java | jdbi/src/main/java/org/killbill/commons/jdbi/ReusableStringTemplate3StatementLocator.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.Map;
import java.util.regex.Matcher;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.language.AngleBracketTemplateLexer;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.StatementLocator;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.charset.StandardCharsets.US_ASCII;
// Similar to StringTemplate3StatementLocator, but safe to use in conjunction with dbi#setStatementLocator
public class ReusableStringTemplate3StatementLocator implements StatementLocator {
protected final StringTemplateGroup group;
protected final StringTemplateGroup literals = new StringTemplateGroup("literals", AngleBracketTemplateLexer.class);
protected final boolean treatLiteralsAsTemplates;
public ReusableStringTemplate3StatementLocator(final Class baseClass) {
this(mungify("/" + baseClass.getName()) + ".sql.stg", false, false);
}
public ReusableStringTemplate3StatementLocator(final String templateGroupFilePathOnClasspath) {
this(templateGroupFilePathOnClasspath, false, false);
}
public ReusableStringTemplate3StatementLocator(final Class baseClass,
final boolean allowImplicitTemplateGroup,
final boolean treatLiteralsAsTemplates) {
this(mungify("/" + baseClass.getName()) + ".sql.stg", allowImplicitTemplateGroup, treatLiteralsAsTemplates);
}
public ReusableStringTemplate3StatementLocator(final String templateGroupFilePathOnClasspath,
final boolean allowImplicitTemplateGroup,
final boolean treatLiteralsAsTemplates) {
this.treatLiteralsAsTemplates = treatLiteralsAsTemplates;
final InputStream ins = getClass().getResourceAsStream(templateGroupFilePathOnClasspath);
if (allowImplicitTemplateGroup && ins == null) {
this.group = new StringTemplateGroup("empty template group", AngleBracketTemplateLexer.class);
} else if (ins == null) {
throw new IllegalStateException("unable to find group file "
+ templateGroupFilePathOnClasspath
+ " on classpath");
} else {
final InputStreamReader reader = new InputStreamReader(ins, UTF_8);
try {
this.group = new StringTemplateGroup(reader, AngleBracketTemplateLexer.class);
reader.close();
} catch (final IOException e) {
throw new IllegalStateException("unable to load string template group " + templateGroupFilePathOnClasspath,
e);
}
}
}
// Note! This code needs to be thread safe. We just synchronize the whole method for now, we could probably do better...
public synchronized String locate(final String name, final StatementContext ctx) throws Exception {
if (group.isDefined(name)) {
final StringTemplate t = group.lookupTemplate(name);
for (final Map.Entry<String, Object> entry : ctx.getAttributes().entrySet()) {
t.setAttribute(entry.getKey(), entry.getValue());
}
final String sql = t.toString();
// Reset the template attributes
t.setAttributes(null);
return sql;
} else if (treatLiteralsAsTemplates) {
// no template in the template group, but we want literals to be templates
final String key = Base64.getEncoder().encodeToString(name.getBytes(US_ASCII));
if (!literals.isDefined(key)) {
literals.defineTemplate(key, name);
}
final StringTemplate t = literals.lookupTemplate(key);
for (final Map.Entry<String, Object> entry : ctx.getAttributes().entrySet()) {
t.setAttribute(entry.getKey(), entry.getValue());
}
final String sql = t.toString();
// Reset the template attributes
t.setAttributes(null);
return sql;
} else {
return name;
}
}
private static final String sep = "/"; // *Not* System.getProperty("file.separator"), which breaks in jars
private static String mungify(final String path) {
return path.replaceAll("\\.", Matcher.quoteReplacement(sep));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/guice/DataSourceProvider.java | jdbi/src/main/java/org/killbill/commons/jdbi/guice/DataSourceProvider.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.guice;
import java.io.IOException;
import java.net.URI;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.sql.DataSource;
import org.killbill.commons.embeddeddb.EmbeddedDB;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.jdbi.hikari.KillBillHealthChecker;
import org.killbill.commons.jdbi.hikari.KillBillMetricsTrackerFactory;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.utils.annotation.VisibleForTesting;
import org.skife.config.TimeSpan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool.PoolInitializationException;
public class DataSourceProvider implements Provider<DataSource> {
protected final DaoConfig config;
protected final String poolName;
protected final boolean useMariaDB;
protected final EmbeddedDB embeddedDB;
private DatabaseType databaseType;
private String dataSourceClassName;
private String driverClassName;
private MetricRegistry metricRegistry;
private HealthCheckRegistry healthCheckRegistry;
@VisibleForTesting
static enum DatabaseType {
GENERIC, MYSQL, H2, POSTGRESQL
}
@Inject
public DataSourceProvider(final DaoConfig config) {
this(config, null);
}
public DataSourceProvider(final DaoConfig config, final String poolName) {
this(config, poolName, true);
}
public DataSourceProvider(final DaoConfig config, final EmbeddedDB embeddedDB, final String poolName) {
this(config, embeddedDB, poolName, true);
}
public DataSourceProvider(final DaoConfig config, final String poolName, final boolean useMariaDB) {
this(config, null, poolName, useMariaDB);
}
public DataSourceProvider(final DaoConfig config, final EmbeddedDB embeddedDB, final String poolName, final boolean useMariaDB) {
this.config = config;
this.poolName = poolName;
this.useMariaDB = useMariaDB;
this.embeddedDB = embeddedDB;
parseJDBCUrl();
}
@Inject
public void setMetricsRegistry(@Nullable final MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
@Inject
public void setHealthCheckRegistry(@Nullable final HealthCheckRegistry healthCheckRegistry) {
this.healthCheckRegistry = healthCheckRegistry;
}
@Override
public DataSource get() {
final DataSource dataSource = buildDataSource();
if (embeddedDB != null) {
embeddedDB.setDataSource(dataSource);
}
return dataSource;
}
private DataSource buildDataSource() {
switch(config.getConnectionPoolingType()) {
case HIKARICP:
if (dataSourceClassName != null) {
loadDriver();
}
return new HikariDataSourceBuilder().buildDataSource();
case NONE:
if (embeddedDB != null) {
try {
embeddedDB.initialize();
embeddedDB.start();
return embeddedDB.getDataSource();
} catch (final IOException e) {
throw new RuntimeException(e);
} catch (final SQLException e) {
throw new RuntimeException(e);
}
}
default:
break;
}
throw new IllegalArgumentException("DataSource " + config.getConnectionPoolingType() + " unsupported");
}
private class HikariDataSourceBuilder {
private final Logger logger = LoggerFactory.getLogger(HikariDataSourceBuilder.class);
DataSource buildDataSource() {
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setUsername(config.getUsername());
hikariConfig.setPassword(config.getPassword());
hikariConfig.setMaximumPoolSize(config.getMaxActive());
hikariConfig.setLeakDetectionThreshold(config.getLeakDetectionThreshold().getMillis());
hikariConfig.setMinimumIdle(config.getMinIdle());
hikariConfig.setConnectionTimeout(toMilliSeconds(config.getConnectionTimeout()));
hikariConfig.setIdleTimeout(toMilliSeconds(config.getIdleMaxAge()));
// value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout setting
hikariConfig.setMaxLifetime(toMilliSeconds(config.getMaxConnectionAge()));
// TODO config.getIdleConnectionTestPeriod() ?
// ... no such thing on the HikariCP config.getIdleConnectionTestPeriod()
final String initSQL = config.getConnectionInitSql();
if (initSQL != null && !initSQL.isEmpty()) {
hikariConfig.setConnectionInitSql(initSQL);
}
hikariConfig.setInitializationFailTimeout(config.isInitializationFailFast() ? 1 : -1);
hikariConfig.setTransactionIsolation(config.getTransactionIsolationLevel());
hikariConfig.setReadOnly(config.isReadOnly());
hikariConfig.setRegisterMbeans(true);
if (metricRegistry != null) {
hikariConfig.setMetricsTrackerFactory(new KillBillMetricsTrackerFactory(metricRegistry));
}
if (poolName != null) {
hikariConfig.setPoolName(poolName);
}
hikariConfig.addDataSourceProperty("url", config.getJdbcUrl());
hikariConfig.addDataSourceProperty("user", config.getUsername());
hikariConfig.addDataSourceProperty("password", config.getPassword());
if (DatabaseType.MYSQL.equals(databaseType)) {
hikariConfig.addDataSourceProperty("cachePrepStmts", config.isPreparedStatementsCacheEnabled());
hikariConfig.addDataSourceProperty("prepStmtCacheSize", config.getPreparedStatementsCacheSize());
hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", config.getPreparedStatementsCacheSqlLimit());
if (Float.valueOf(config.getMySQLServerVersion()).compareTo(Float.valueOf("5.1")) >= 0) {
hikariConfig.addDataSourceProperty("useServerPrepStmts", config.isServerSidePreparedStatementsEnabled());
}
}
if (dataSourceClassName != null) {
hikariConfig.setDataSourceClassName(dataSourceClassName);
} else {
// Old-school DriverManager-based JDBC
hikariConfig.setJdbcUrl(config.getJdbcUrl());
if (driverClassName != null) {
hikariConfig.setDriverClassName(driverClassName);
}
}
try {
final DataSource hikariDataSource = new HikariDataSource(hikariConfig);
if (healthCheckRegistry != null) {
KillBillHealthChecker.registerHealthChecks(hikariDataSource, hikariConfig, healthCheckRegistry);
}
return hikariDataSource;
} catch (final PoolInitializationException e) {
// When initializationFailFast=true, log the exception to alert the user (the Guice initialization sequence will continue though)
logger.error("Unable to initialize the database pool", e);
throw e;
}
}
}
static int toSeconds(final TimeSpan timeSpan) {
return toSeconds(timeSpan.getPeriod(), timeSpan.getUnit());
}
static int toSeconds(final long period, final TimeUnit timeUnit) {
return (int) TimeUnit.SECONDS.convert(period, timeUnit);
}
static int toMilliSeconds(final TimeSpan timeSpan) {
return toMilliSeconds(timeSpan.getPeriod(), timeSpan.getUnit());
}
static int toMilliSeconds(final long period, final TimeUnit timeUnit) {
return (int) TimeUnit.MILLISECONDS.convert(period, timeUnit);
}
private void parseJDBCUrl() {
final URI uri = URI.create(config.getJdbcUrl().substring(5));
final String schemeLocation;
if (uri.getPath() != null) {
schemeLocation = null;
} else if (uri.getSchemeSpecificPart() != null) {
final String[] schemeParts = uri.getSchemeSpecificPart().split(":");
schemeLocation = schemeParts[0];
} else {
schemeLocation = null;
}
dataSourceClassName = config.getDataSourceClassName();
driverClassName = config.getDriverClassName();
if ("mysql".equals(uri.getScheme())) {
databaseType = DatabaseType.MYSQL;
if (dataSourceClassName == null) {
if (useMariaDB) {
//dataSourceClassName = "org.mariadb.jdbc.MySQLDataSource";
dataSourceClassName = "org.killbill.commons.embeddeddb.mysql.KillBillMariaDbDataSource";
} else {
dataSourceClassName = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
}
}
if (driverClassName == null) {
if (useMariaDB) {
driverClassName = "org.mariadb.jdbc.Driver";
} else {
driverClassName = "com.mysql.cj.jdbc.Driver";
}
}
} else if ("h2".equals(uri.getScheme()) && ("mem".equals(schemeLocation) || "file".equals(schemeLocation))) {
databaseType = DatabaseType.H2;
if (dataSourceClassName == null) {
dataSourceClassName = "org.h2.jdbcx.JdbcDataSource";
}
if (driverClassName == null) {
driverClassName = "org.h2.Driver";
}
} else if ("postgresql".equals(uri.getScheme())) {
databaseType = DatabaseType.POSTGRESQL;
if (dataSourceClassName == null) {
dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource";
}
if (driverClassName == null) {
driverClassName = "org.postgresql.Driver";
}
} else {
databaseType = DatabaseType.GENERIC;
}
}
private void loadDriver() {
if (driverClassName != null) {
try {
Class.forName(driverClassName).newInstance();
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/guice/DataSourceConnectionPoolingType.java | jdbi/src/main/java/org/killbill/commons/jdbi/guice/DataSourceConnectionPoolingType.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.guice;
public enum DataSourceConnectionPoolingType {
HIKARICP,
NONE
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/guice/DaoConfig.java | jdbi/src/main/java/org/killbill/commons/jdbi/guice/DaoConfig.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.guice;
import org.killbill.commons.jdbi.log.LogLevel;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.DefaultNull;
import org.skife.config.Description;
import org.skife.config.TimeSpan;
public interface DaoConfig {
@Description("The jdbc url for the database")
@Config("org.killbill.dao.url")
@Default("jdbc:h2:file:/var/tmp/killbill;MODE=LEGACY;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
String getJdbcUrl();
@Description("The jdbc user name for the database")
@Config("org.killbill.dao.user")
@Default("killbill")
String getUsername();
@Description("The jdbc password for the database")
@Config("org.killbill.dao.password")
@Default("killbill")
String getPassword();
@Description("The minimum allowed number of idle connections to the database")
@Config("org.killbill.dao.minIdle")
@Default("1")
int getMinIdle();
@Description("The maximum allowed number of active connections to the database")
@Config("org.killbill.dao.maxActive")
@Default("100")
int getMaxActive();
@Description("Amount of time that a connection can be out of the pool before a message is logged indicating a possible connection leak")
@Config("org.killbill.dao.leakDetectionThreshold")
@Default("60s")
TimeSpan getLeakDetectionThreshold();
@Description("How long to wait before a connection attempt to the database is considered timed out")
@Config("org.killbill.dao.connectionTimeout")
@Default("10s")
TimeSpan getConnectionTimeout();
@Description("The time for a connection to remain unused before it is closed off")
@Config("org.killbill.dao.idleMaxAge")
@Default("60m")
TimeSpan getIdleMaxAge();
@Description("Any connections older than this setting will be closed off whether it is idle or not. Connections " +
"currently in use will not be affected until they are returned to the pool")
@Config("org.killbill.dao.maxConnectionAge")
@Default("0m")
TimeSpan getMaxConnectionAge();
@Description("Time for a connection to remain idle before sending a test query to the DB")
@Config("org.killbill.dao.idleConnectionTestPeriod")
@Default("5m")
TimeSpan getIdleConnectionTestPeriod();
@Description("Sets a SQL statement executed after every new connection creation before adding it to the pool")
@Config("org.killbill.dao.connectionInitSql")
@DefaultNull
String getConnectionInitSql();
@Description("Number of prepared statements that the driver will cache per connection")
@Config("org.killbill.dao.prepStmtCacheSize")
@Default("500")
int getPreparedStatementsCacheSize();
@Description("Maximum length of a prepared SQL statement that the driver will cache")
@Config("org.killbill.dao.prepStmtCacheSqlLimit")
@Default("2048")
int getPreparedStatementsCacheSqlLimit();
@Description("Enable prepared statements cache")
@Config("org.killbill.dao.cachePrepStmts")
@Default("true")
boolean isPreparedStatementsCacheEnabled();
@Description("Enable server-side prepared statements")
@Config("org.killbill.dao.useServerPrepStmts")
@Default("true")
boolean isServerSidePreparedStatementsEnabled();
@Description("DataSource class name provided by the JDBC driver, leave null for autodetection")
@Config("org.killbill.dao.dataSourceClassName")
@DefaultNull
String getDataSourceClassName();
@Description("JDBC driver to use (when dataSourceClassName is null)")
@Config("org.killbill.dao.driverClassName")
@DefaultNull
String getDriverClassName();
@Description("MySQL server version")
@Config("org.killbill.dao.mysqlServerVersion")
@Default("5.1")
String getMySQLServerVersion();
@Description("Log level for SQL queries")
@Config("org.killbill.dao.logLevel")
@Default("DEBUG")
LogLevel getLogLevel();
@Description("Connection pooling type")
@Config("org.killbill.dao.poolingType")
@Default("HIKARICP")
DataSourceConnectionPoolingType getConnectionPoolingType();
@Description("How long to wait before a connection attempt to the database is considered timed out (healthcheck only)")
@Config("org.killbill.dao.healthCheckConnectionTimeout")
@Default("10s")
TimeSpan getHealthCheckConnectionTimeout();
@Description("Expected 99th percentile calculation to obtain a connection (healthcheck only)")
@Config("org.killbill.dao.healthCheckExpected99thPercentile")
@Default("50ms")
TimeSpan getHealthCheckExpected99thPercentile();
@Description("Whether or not initialization should fail on error immediately")
@Config("org.killbill.dao.initializationFailFast")
@Default("false")
boolean isInitializationFailFast();
@Description("Set the default transaction isolation level")
@Config("org.killbill.dao.transactionIsolationLevel")
@Default("TRANSACTION_READ_COMMITTED")
String getTransactionIsolationLevel();
@Description("Whether to put connections in read-only mode")
@Config("org.killbill.dao.readOnly")
@Default("false")
boolean isReadOnly();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/guice/DBIProvider.java | jdbi/src/main/java/org/killbill/commons/jdbi/guice/DBIProvider.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.guice;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.sql.DataSource;
import org.killbill.commons.jdbi.argument.DateTimeArgumentFactory;
import org.killbill.commons.jdbi.argument.DateTimeZoneArgumentFactory;
import org.killbill.commons.jdbi.argument.LocalDateArgumentFactory;
import org.killbill.commons.jdbi.argument.UUIDArgumentFactory;
import org.killbill.commons.jdbi.log.Slf4jLogging;
import org.killbill.commons.jdbi.mapper.UUIDMapper;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.ResultSetMapperFactory;
import org.skife.jdbi.v2.TimingCollector;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import org.skife.jdbi.v2.tweak.SQLLog;
import org.skife.jdbi.v2.tweak.StatementBuilderFactory;
import org.skife.jdbi.v2.tweak.StatementRewriter;
import org.skife.jdbi.v2.tweak.TransactionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DBIProvider implements Provider<IDBI> {
private static final Logger logger = LoggerFactory.getLogger(DBIProvider.class);
private final DaoConfig config;
private final DataSource ds;
private final TransactionHandler transactionHandler;
private final Set<ArgumentFactory> argumentFactorySet = new LinkedHashSet<>();
private final Set<ResultSetMapperFactory> resultSetMapperFactorySet = new LinkedHashSet<>();
private final Set<ResultSetMapper> resultSetMapperSet = new LinkedHashSet<>();
private SQLLog sqlLog;
private TimingCollector timingCollector;
private StatementRewriter statementRewriter;
private StatementBuilderFactory statementBuilderFactory;
@Inject
public DBIProvider(final DaoConfig config, final DataSource ds, final TransactionHandler transactionHandler) {
this.config = config;
this.ds = ds;
this.transactionHandler = transactionHandler;
setDefaultArgumentFactorySet();
setDefaultResultSetMapperSet();
}
@Inject
public void setArgumentFactorySet(@Nullable final Set<ArgumentFactory> argumentFactorySet) {
if (argumentFactorySet != null) {
this.argumentFactorySet.addAll(argumentFactorySet);
}
}
@Inject
public void setResultSetMapperFactorySet(@Nullable final Set<ResultSetMapperFactory> resultSetMapperFactorySet) {
if (resultSetMapperFactorySet != null) {
this.resultSetMapperFactorySet.addAll(resultSetMapperFactorySet);
}
}
@Inject
public void setResultSetMapperSet(@Nullable final Set<ResultSetMapper> resultSetMapperSet) {
if (resultSetMapperSet != null) {
this.resultSetMapperSet.addAll(resultSetMapperSet);
}
}
@Inject
public void setSqlLog(@Nullable final SQLLog sqlLog) {
this.sqlLog = sqlLog;
}
@Inject
public void setTimingCollector(@Nullable final TimingCollector timingCollector) {
this.timingCollector = timingCollector;
}
@Inject
public void setStatementRewriter(@Nullable final StatementRewriter statementRewriter) {
this.statementRewriter = statementRewriter;
}
@Inject
public void setStatementBuilderFactory(@Nullable final StatementBuilderFactory statementBuilderFactory) {
this.statementBuilderFactory = statementBuilderFactory;
}
@Override
public IDBI get() {
final DBI dbi = new DBI(ds);
if (statementRewriter != null) {
dbi.setStatementRewriter(statementRewriter);
}
if (statementBuilderFactory != null) {
dbi.setStatementBuilderFactory(statementBuilderFactory);
}
for (final ArgumentFactory argumentFactory : argumentFactorySet) {
dbi.registerArgumentFactory(argumentFactory);
}
for (final ResultSetMapperFactory resultSetMapperFactory : resultSetMapperFactorySet) {
dbi.registerMapper(resultSetMapperFactory);
}
for (final ResultSetMapper resultSetMapper : resultSetMapperSet) {
dbi.registerMapper(resultSetMapper);
}
if (transactionHandler != null) {
dbi.setTransactionHandler(transactionHandler);
}
if (sqlLog != null) {
dbi.setSQLLog(sqlLog);
} else if (config != null) {
final Slf4jLogging sqlLog = new Slf4jLogging(logger, config.getLogLevel());
dbi.setSQLLog(sqlLog);
}
if (timingCollector != null) {
dbi.setTimingCollector(timingCollector);
}
return dbi;
}
protected void setDefaultArgumentFactorySet() {
argumentFactorySet.add(new UUIDArgumentFactory());
argumentFactorySet.add(new DateTimeZoneArgumentFactory());
argumentFactorySet.add(new DateTimeArgumentFactory());
argumentFactorySet.add(new LocalDateArgumentFactory());
}
protected void setDefaultResultSetMapperSet() {
resultSetMapperSet.add(new UUIDMapper());
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/statement/SmartFetchSize.java | jdbi/src/main/java/org/killbill/commons/jdbi/statement/SmartFetchSize.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.statement;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation;
import org.skife.jdbi.v2.tweak.BaseStatementCustomizer;
// Similar to org.skife.jdbi.v2.sqlobject.customizers.FetchSize but a bit smarter:
// @FetchSize(Integer.MIN_VALUE) doesn't work for H2 for example.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
@SqlStatementCustomizingAnnotation(SmartFetchSize.Factory.class)
public @interface SmartFetchSize {
int value() default 0;
// Override value
boolean shouldStream() default false;
static class Factory implements SqlStatementCustomizerFactory {
public SqlStatementCustomizer createForMethod(final Annotation annotation, final Class sqlObjectType, final Method method) {
final SmartFetchSize fs = (SmartFetchSize) annotation;
return new SqlStatementCustomizer() {
public void apply(final SQLStatement q) throws SQLException {
setFetchSize((Query) q, fs.value(), fs.shouldStream());
}
};
}
public SqlStatementCustomizer createForType(final Annotation annotation, final Class sqlObjectType) {
final SmartFetchSize fs = (SmartFetchSize) annotation;
return new SqlStatementCustomizer() {
public void apply(final SQLStatement q) throws SQLException {
setFetchSize((Query) q, fs.value(), fs.shouldStream());
}
};
}
public SqlStatementCustomizer createForParameter(final Annotation annotation, final Class sqlObjectType, final Method method, final Object arg) {
final Integer va = (Integer) arg;
return new SqlStatementCustomizer() {
public void apply(final SQLStatement q) throws SQLException {
setFetchSize((Query) q, va, false);
}
};
}
private Query setFetchSize(final Query query, final Integer value, final boolean shouldStream) {
query.addStatementCustomizer(new SmartFetchSizeCustomizer(value, shouldStream));
return query;
}
}
public static final class SmartFetchSizeCustomizer extends BaseStatementCustomizer {
// Shared name across drivers, see org.mariadb.jdbc.DatabaseMetaData and com.mysql.jdbc.DatabaseMetaData
private static final String MYSQL = "MySQL";
private final int fetchSize;
private final boolean shouldStream;
public SmartFetchSizeCustomizer(final int fetchSize, final boolean shouldStream) {
this.fetchSize = fetchSize;
this.shouldStream = shouldStream;
}
@Override
public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException {
stmt.setFetchSize(fetchSize);
if (shouldStream) {
if (ctx != null &&
ctx.getConnection() != null &&
ctx.getConnection().getMetaData() != null &&
MYSQL.equalsIgnoreCase(ctx.getConnection().getMetaData().getDatabaseProductName())) {
// The Integer.MIN_VALUE hint isn't supported by MariaDB anymore
if (ctx.getConnection().getMetaData().getDriverName().startsWith("MariaDB")) {
// See https://mariadb.com/kb/en/about-mariadb-connector-j/#streaming-result-sets and org.mariadb.jdbc.message.ClientMessage#readPacket
stmt.setFetchSize(1);
} else {
try {
// Magic value to force MySQL to stream from the database
// See https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-implementation-notes.html (ResultSet)
stmt.setFetchSize(Integer.MIN_VALUE);
} catch (final SQLException e) {
// Shouldn't happen? The exception will be logged by log4jdbc
stmt.setFetchSize(0);
}
}
} else {
// Other engines (H2, PostgreSQL, etc.)
stmt.setFetchSize(0);
}
} else {
stmt.setFetchSize(fetchSize);
}
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/transaction/RestartTransactionRunner.java | jdbi/src/main/java/org/killbill/commons/jdbi/transaction/RestartTransactionRunner.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.transaction;
import java.sql.SQLException;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionIsolationLevel;
import org.skife.jdbi.v2.tweak.TransactionHandler;
import org.skife.jdbi.v2.tweak.transactions.DelegatingTransactionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A TransactionHandler that automatically retries transactions that fail due to
* serialization failures or innodb wait lock timeout, which can generally be resolved by automatically
* retrying the transaction. Any TransactionCallback used under this runner
* should be aware that it may be invoked multiple times.
*/
public class RestartTransactionRunner extends DelegatingTransactionHandler implements TransactionHandler {
private static final Logger log = LoggerFactory.getLogger(RestartTransactionRunner.class);
private static final String SQLSTATE_TXN_SERIALIZATION_FAILED = "40001";
private static final String SQLSTATE_INNODB_WAIT_LOCK_TIMEOUT_EXCEEDED = "41000";
private final Configuration configuration;
public RestartTransactionRunner(final TransactionHandler delegate) {
this(new Configuration(), delegate);
}
public RestartTransactionRunner(final Configuration configuration, final TransactionHandler delegate) {
super(delegate);
this.configuration = configuration;
}
@Override
public <ReturnType> ReturnType inTransaction(final Handle handle, final TransactionCallback<ReturnType> callback) {
int retriesRemaining = configuration.maxRetries;
while (true) {
try {
return getDelegate().inTransaction(handle, callback);
} catch (final RuntimeException e) {
if (!isSqlState(configuration.serializationFailureSqlStates, e) || --retriesRemaining <= 0) {
throw e;
}
if (e.getCause() instanceof SQLException) {
final String sqlState = ((SQLException) e.getCause()).getSQLState();
log.warn("Restarting transaction due to SQLState {}, retries remaining {}", sqlState, retriesRemaining);
} else {
log.warn("Restarting transaction due to {}, retries remaining {}", e.toString(), retriesRemaining);
}
}
}
}
@Override
public <ReturnType> ReturnType inTransaction(final Handle handle,
final TransactionIsolationLevel level,
final TransactionCallback<ReturnType> callback) {
final TransactionIsolationLevel initial = handle.getTransactionIsolationLevel();
try {
handle.setTransactionIsolation(level);
return inTransaction(handle, callback);
} finally {
handle.setTransactionIsolation(initial);
}
}
/**
* Returns true iff the Throwable or one of its causes is an SQLException whose SQLState begins
* with the passed state.
*/
protected boolean isSqlState(final String[] expectedSqlStates, Throwable throwable) {
do {
if (throwable instanceof SQLException) {
final String sqlState = ((SQLException) throwable).getSQLState();
if (sqlState != null) {
for (final String expectedSqlState : expectedSqlStates) {
if (sqlState.startsWith(expectedSqlState)) {
return true;
}
}
}
}
} while ((throwable = throwable.getCause()) != null);
return false;
}
public static class Configuration {
private final int maxRetries;
private final String[] serializationFailureSqlStates;
public Configuration() {
this(5, new String[]{SQLSTATE_TXN_SERIALIZATION_FAILED, SQLSTATE_INNODB_WAIT_LOCK_TIMEOUT_EXCEEDED});
}
private Configuration(final int maxRetries, final String[] serializationFailureSqlStates) {
this.maxRetries = maxRetries;
this.serializationFailureSqlStates = serializationFailureSqlStates;
}
public Configuration withMaxRetries(final int maxRetries) {
return new Configuration(maxRetries, serializationFailureSqlStates);
}
public Configuration withSerializationFailureSqlState(final String[] serializationFailureSqlState) {
return new Configuration(maxRetries, serializationFailureSqlState);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/transaction/NotificationTransactionHandler.java | jdbi/src/main/java/org/killbill/commons/jdbi/transaction/NotificationTransactionHandler.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.transaction;
import org.killbill.commons.jdbi.notification.DatabaseTransactionEvent;
import org.killbill.commons.jdbi.notification.DatabaseTransactionEventType;
import org.killbill.commons.jdbi.notification.DatabaseTransactionNotificationApi;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.tweak.TransactionHandler;
import org.skife.jdbi.v2.tweak.transactions.DelegatingTransactionHandler;
import org.skife.jdbi.v2.tweak.transactions.LocalTransactionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A transaction handler that allows to notify observers about database transaction success/failure.
*/
public class NotificationTransactionHandler extends DelegatingTransactionHandler implements TransactionHandler {
private static final Logger logger = LoggerFactory.getLogger(NotificationTransactionHandler.class);
private final DatabaseTransactionNotificationApi transactionNotificationApi;
public NotificationTransactionHandler(final DatabaseTransactionNotificationApi transactionNotificationApi) {
super(new LocalTransactionHandler());
this.transactionNotificationApi = transactionNotificationApi;
}
public void commit(final Handle handle) {
getDelegate().commit(handle);
dispatchEvent(new DatabaseTransactionEvent(DatabaseTransactionEventType.COMMIT));
}
public void rollback(final Handle handle) {
getDelegate().rollback(handle);
dispatchEvent(new DatabaseTransactionEvent(DatabaseTransactionEventType.ROLLBACK));
}
private void dispatchEvent(final DatabaseTransactionEvent event) {
try {
transactionNotificationApi.dispatchNotification(event);
} catch (final Exception e) {
logger.warn("Failed to notify for event {}", event);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionEventType.java | jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionEventType.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.notification;
public enum DatabaseTransactionEventType {
ROLLBACK,
COMMIT
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionNotificationApi.java | jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionNotificationApi.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.notification;
import org.killbill.commons.eventbus.EventBus;
public class DatabaseTransactionNotificationApi {
private final EventBus eventBus;
public DatabaseTransactionNotificationApi() {
this.eventBus = new EventBus(this.getClass().getName());
}
public void registerForNotification(final Object listener) {
eventBus.register(listener);
}
public void unregisterForNotification(final Object listener) {
eventBus.unregister(listener);
}
public void dispatchNotification(final DatabaseTransactionEvent event) {
eventBus.post(event);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionEvent.java | jdbi/src/main/java/org/killbill/commons/jdbi/notification/DatabaseTransactionEvent.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.notification;
public class DatabaseTransactionEvent {
private final DatabaseTransactionEventType type;
public DatabaseTransactionEvent(final DatabaseTransactionEventType type) {
this.type = type;
}
public DatabaseTransactionEventType getType() {
return type;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/metrics/KillBillTimingCollector.java | jdbi/src/main/java/org/killbill/commons/jdbi/metrics/KillBillTimingCollector.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.metrics;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.TimingCollector;
public class KillBillTimingCollector implements TimingCollector {
private final MetricRegistry registry;
public KillBillTimingCollector(final MetricRegistry registry) {
this.registry = registry;
}
public void collect(final long elapsedTime, final StatementContext ctx) {
final Timer timer = this.getTimer(ctx);
timer.update(elapsedTime, TimeUnit.NANOSECONDS);
}
private Timer getTimer(final StatementContext ctx) {
return this.registry.timer(getStatementName(ctx));
}
private String getStatementName(final StatementContext ctx) {
final String rawSql = ctx.getRawSql();
if (rawSql == null || rawSql.isEmpty()) {
return "sql.empty";
}
final Class<?> clazz = ctx.getSqlObjectType();
final Method method = ctx.getSqlObjectMethod();
if (clazz != null) {
final String group = clazz.getPackage().getName();
final String name = clazz.getSimpleName();
final String type = method == null ? rawSql : method.getName();
return String.format("%s.%s.%s", group, name, type);
}
final int colon = rawSql.indexOf(':');
if (colon == -1) {
// No package? Just return the name, JDBI figured out somehow on how to find the raw sql for this statement.
return String.format("%s.%s.%s", "sql", "raw", rawSql);
}
final String group = rawSql.substring(0, colon);
final String name = rawSql.substring(colon + 1);
return String.format("%s.%s", group, name);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/binder/SmartBindBean.java | jdbi/src/main/java/org/killbill/commons/jdbi/binder/SmartBindBean.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.binder;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@BindingAnnotation(SmartBindBeanFactory.class)
public @interface SmartBindBean {
String value() default "___jdbi_bare___";
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/binder/SmartBindBeanFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/binder/SmartBindBeanFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.binder;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
// Similar to org.skife.jdbi.v2.sqlobject.BindBeanFactory with optimizations
public class SmartBindBeanFactory implements BinderFactory {
private static final Binder<SmartBindBean, Object> SMART_BINDER = new Binder<SmartBindBean, Object>() {
@Override
public void bind(final SQLStatement q, final SmartBindBean bind, final Object arg) {
final String prefix;
if (BindBean.BARE_BINDING.equals(bind.value())) {
prefix = null;
} else {
prefix = bind.value() + ".";
}
try {
final BeanInfo infos = Introspector.getBeanInfo(arg.getClass());
final PropertyDescriptor[] props = infos.getPropertyDescriptors();
for (final PropertyDescriptor prop : props) {
final Method readMethod = prop.getReadMethod();
if (readMethod != null) {
// [OPTIMIZATION] Avoid implicit creation of StringBuilder (concatenation) when no custom annotation value is specified
final String name = prefix == null ? prop.getName() : prefix + prop.getName();
q.dynamicBind(readMethod.getReturnType(), name, readMethod.invoke(arg));
}
}
} catch (final Exception e) {
throw new IllegalStateException("unable to bind bean properties", e);
}
}
};
@Override
public Binder build(final Annotation annotation) {
return SMART_BINDER;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillHealthChecker.java | jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillHealthChecker.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.hikari;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.killbill.commons.health.api.HealthCheck;
import org.killbill.commons.health.api.HealthCheckRegistry;
import org.killbill.commons.health.api.Result;
import org.killbill.commons.health.impl.HealthyResultBuilder;
import org.killbill.commons.health.impl.UnhealthyResultBuilder;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import com.zaxxer.hikari.HikariConfig;
/**
* Provides HealthChecks. Two health checks are provided:
* <ul>
* <li>ConnectivityCheck</li>
* <li>Connection99Percent</li>
* </ul>
* The Connection99Percent health check will only be registered if the health check property
* <code>expected99thPercentileMs</code> is defined and greater than 0.
*/
public final class KillBillHealthChecker {
private KillBillHealthChecker() {
// private constructor
}
/**
* Register health checks.
*
* @param dataSource the DataSource to register health checks for
* @param hikariConfig the pool configuration
* @param registry the HealthCheckRegistry into which checks will be registered
*/
public static void registerHealthChecks(final DataSource dataSource, final HikariConfig hikariConfig, final HealthCheckRegistry registry) {
final Properties healthCheckProperties = hikariConfig.getHealthCheckProperties();
final MetricRegistry metricRegistry = (MetricRegistry) hikariConfig.getMetricRegistry();
registry.register(String.format("%s.%s.%s", hikariConfig.getPoolName(), "pool", "ConnectivityCheck"), new ConnectivityHealthCheck(dataSource));
final long expected99thPercentile = Long.parseLong(healthCheckProperties.getProperty("expected99thPercentileMs", "0"));
if (metricRegistry != null && expected99thPercentile > 0) {
for (final Entry<String, Timer> entry : metricRegistry.getTimers().entrySet()) {
if (entry.getKey().equals(String.format("%s.%s.%s", hikariConfig.getPoolName(), "pool", "Wait"))) {
registry.register(String.format("%s.%s.%s", hikariConfig.getPoolName(), "pool", "Connection99Percent"), new Connection99Percent(entry.getValue(), expected99thPercentile));
}
}
}
}
private static class ConnectivityHealthCheck implements HealthCheck {
private final DataSource dataSource;
ConnectivityHealthCheck(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Result check() throws Exception {
try (final Connection ignored = dataSource.getConnection()) {
return new HealthyResultBuilder().createHealthyResult();
} catch (final SQLException e) {
return new UnhealthyResultBuilder().setError(e).createUnhealthyResult();
}
}
}
private static class Connection99Percent implements HealthCheck {
private final Timer waitTimer;
private final long expected99thPercentile;
Connection99Percent(final Timer waitTimer, final long expected99thPercentile) {
this.waitTimer = waitTimer;
this.expected99thPercentile = expected99thPercentile;
}
@Override
public Result check() throws Exception {
final long the99thPercentile = TimeUnit.NANOSECONDS.toMillis(Math.round(waitTimer.getSnapshot().get99thPercentile()));
return the99thPercentile <= expected99thPercentile ? new HealthyResultBuilder().createHealthyResult() : new UnhealthyResultBuilder().setMessage(String.format("99th percentile connection wait time of %dms exceeds the threshold %dms", the99thPercentile, expected99thPercentile)).createUnhealthyResult();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillMetricsTracker.java | jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillMetricsTracker.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.hikari;
import java.util.concurrent.TimeUnit;
import org.killbill.commons.metrics.api.Gauge;
import org.killbill.commons.metrics.api.Histogram;
import org.killbill.commons.metrics.api.Meter;
import org.killbill.commons.metrics.api.MetricRegistry;
import org.killbill.commons.metrics.api.Timer;
import com.zaxxer.hikari.metrics.IMetricsTracker;
import com.zaxxer.hikari.metrics.PoolStats;
public class KillBillMetricsTracker implements IMetricsTracker {
private static final String METRIC_CATEGORY = "pool";
private static final String METRIC_NAME_WAIT = "Wait";
private static final String METRIC_NAME_USAGE = "Usage";
private static final String METRIC_NAME_CONNECT = "ConnectionCreation";
private static final String METRIC_NAME_TIMEOUT_RATE = "ConnectionTimeoutRate";
private static final String METRIC_NAME_TOTAL_CONNECTIONS = "TotalConnections";
private static final String METRIC_NAME_IDLE_CONNECTIONS = "IdleConnections";
private static final String METRIC_NAME_ACTIVE_CONNECTIONS = "ActiveConnections";
private static final String METRIC_NAME_PENDING_CONNECTIONS = "PendingConnections";
private static final String METRIC_NAME_MAX_CONNECTIONS = "MaxConnections";
private static final String METRIC_NAME_MIN_CONNECTIONS = "MinConnections";
private final String poolName;
private final Timer connectionObtainTimer;
private final Histogram connectionUsage;
private final Histogram connectionCreation;
private final Meter connectionTimeoutMeter;
private final MetricRegistry registry;
public KillBillMetricsTracker(final String poolName, final PoolStats poolStats, final MetricRegistry registry) {
this.poolName = poolName;
this.registry = registry;
this.connectionObtainTimer = registry.timer(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_WAIT));
this.connectionUsage = registry.histogram(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_USAGE));
this.connectionCreation = registry.histogram(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_CONNECT));
this.connectionTimeoutMeter = registry.meter(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_TIMEOUT_RATE));
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_TOTAL_CONNECTIONS),
poolStats::getTotalConnections);
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_IDLE_CONNECTIONS),
poolStats::getIdleConnections);
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_ACTIVE_CONNECTIONS),
poolStats::getActiveConnections);
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_PENDING_CONNECTIONS),
poolStats::getPendingThreads);
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_MAX_CONNECTIONS),
poolStats::getMaxConnections);
registry.gauge(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_MIN_CONNECTIONS),
poolStats::getMinConnections);
}
@Override
public void close() {
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_WAIT));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_USAGE));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_CONNECT));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_TIMEOUT_RATE));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_TOTAL_CONNECTIONS));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_IDLE_CONNECTIONS));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_ACTIVE_CONNECTIONS));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_PENDING_CONNECTIONS));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_MAX_CONNECTIONS));
registry.remove(String.format("%s.%s.%s", poolName, METRIC_CATEGORY, METRIC_NAME_MIN_CONNECTIONS));
}
@Override
public void recordConnectionAcquiredNanos(final long elapsedAcquiredNanos) {
connectionObtainTimer.update(elapsedAcquiredNanos, TimeUnit.NANOSECONDS);
}
@Override
public void recordConnectionUsageMillis(final long elapsedBorrowedMillis) {
connectionUsage.update(elapsedBorrowedMillis);
}
@Override
public void recordConnectionTimeout() {
connectionTimeoutMeter.mark(1);
}
@Override
public void recordConnectionCreatedMillis(final long connectionCreatedMillis) {
connectionCreation.update(connectionCreatedMillis);
}
public Timer getConnectionAcquisitionTimer() {
return connectionObtainTimer;
}
public Histogram getConnectionDurationHistogram() {
return connectionUsage;
}
public Histogram getConnectionCreationHistogram() {
return connectionCreation;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillMetricsTrackerFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/hikari/KillBillMetricsTrackerFactory.java | /*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.hikari;
import org.killbill.commons.metrics.api.MetricRegistry;
import com.zaxxer.hikari.metrics.IMetricsTracker;
import com.zaxxer.hikari.metrics.MetricsTrackerFactory;
import com.zaxxer.hikari.metrics.PoolStats;
public class KillBillMetricsTrackerFactory implements MetricsTrackerFactory {
private final MetricRegistry registry;
public KillBillMetricsTrackerFactory(final MetricRegistry registry) {
this.registry = registry;
}
public MetricRegistry getRegistry() {
return registry;
}
@Override
public IMetricsTracker create(final String poolName, final PoolStats poolStats) {
return new KillBillMetricsTracker(poolName, poolStats, registry);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/template/KillBillSqlDaoStringTemplate.java | jdbi/src/main/java/org/killbill/commons/jdbi/template/KillBillSqlDaoStringTemplate.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.template;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator.UseSTGroupCache;
import org.skife.jdbi.v2.sqlobject.stringtemplate.UseST4StatementLocator;
import org.skife.jdbi.v2.tweak.StatementLocator;
@SqlStatementCustomizingAnnotation(KillBillSqlDaoStringTemplate.KillBillSqlDaoStringTemplateFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface KillBillSqlDaoStringTemplate {
String DEFAULT_VALUE = " ~ ";
String value() default DEFAULT_VALUE;
class KillBillSqlDaoStringTemplateFactory extends UseST4StatementLocator.LocatorFactory {
static final boolean enableGroupTemplateCaching = Boolean.parseBoolean(System.getProperty("org.killbill.jdbi.allow.stringTemplateGroupCaching", "true"));
static final ConcurrentMap<String, StatementLocator> locatorCache = new ConcurrentHashMap<String, StatementLocator>();
static final ConcurrentMap<Class, String> locatorPathCache = new ConcurrentHashMap<Class, String>();
//
// This is only needed to compute the key for the cache -- whether we get a class or a pathname (string)
//
// (Similar to what jdbi is doing (StringTemplate3StatementLocator))
//
private static final String sep = "/"; // *Not* System.getProperty("file.separator"), which breaks in jars
private static final String QUOTE_REPLACEMENT_SEP = Matcher.quoteReplacement(sep);
static String mungify(final Class claz) {
String locatorPath = locatorPathCache.get(claz);
if (locatorPath != null) {
return locatorPath;
}
final String path = "/" + claz.getName();
locatorPath = path.replaceAll("\\.", QUOTE_REPLACEMENT_SEP) + ".sql.stg";
if (enableGroupTemplateCaching) {
locatorPathCache.put(claz, locatorPath);
}
return locatorPath;
}
private StatementLocator getLocator(final String locatorPath) {
StatementLocator locator = locatorCache.get(locatorPath);
if (locator != null) {
return locator;
}
locator = ST4StatementLocator.fromClasspath(UseSTGroupCache.YES, locatorPath);
if (enableGroupTemplateCaching) {
locatorCache.put(locatorPath, locator);
}
return locator;
}
@Override
public SqlStatementCustomizer createForType(final Annotation annotation, final Class sqlObjectType) {
final KillBillSqlDaoStringTemplate a = (KillBillSqlDaoStringTemplate) annotation;
final String locatorPath = DEFAULT_VALUE.equals(a.value()) ? mungify(sqlObjectType) : a.value();
final StatementLocator l = getLocator(locatorPath);
return new SqlStatementCustomizer() {
@Override
public void apply(final SQLStatement statement) {
statement.setStatementLocator(l);
}
};
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/log/LogLevel.java | jdbi/src/main/java/org/killbill/commons/jdbi/log/LogLevel.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.log;
public enum LogLevel {
DEBUG,
TRACE,
INFO,
WARN,
ERROR
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/log/Slf4jLogging.java | jdbi/src/main/java/org/killbill/commons/jdbi/log/Slf4jLogging.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.log;
import org.skife.jdbi.v2.logging.FormattedLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Slf4jLogging extends FormattedLog {
private final Logger logger;
private final LogLevel logLevel;
public Slf4jLogging() {
this(LoggerFactory.getLogger(Slf4jLogging.class));
}
public Slf4jLogging(final Logger logger) {
this(logger, LogLevel.DEBUG);
}
public Slf4jLogging(final Logger logger, final LogLevel logLevel) {
this.logger = logger;
this.logLevel = logLevel;
}
/**
* Used to ask implementations if logging is enabled.
*
* @return true if statement logging is enabled
*/
@Override
protected boolean isEnabled() {
if (logLevel == LogLevel.DEBUG) {
return logger.isDebugEnabled();
} else if (logLevel == LogLevel.TRACE) {
return logger.isTraceEnabled();
} else if (logLevel == LogLevel.INFO) {
return logger.isInfoEnabled();
} else if (logLevel == LogLevel.WARN) {
return logger.isWarnEnabled();
} else if (logLevel == LogLevel.ERROR) {
return logger.isErrorEnabled();
} else {
return false;
}
}
/**
* Log the statement passed in
*
* @param msg the message to log
*/
@Override
protected void log(final String msg) {
if (logLevel.equals(LogLevel.DEBUG)) {
logger.debug(msg);
} else if (logLevel.equals(LogLevel.TRACE)) {
logger.trace(msg);
} else if (logLevel.equals(LogLevel.INFO)) {
logger.info(msg);
} else if (logLevel.equals(LogLevel.WARN)) {
logger.warn(msg);
} else if (logLevel.equals(LogLevel.ERROR)) {
logger.error(msg);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/mapper/LowerToCamelBeanMapperFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/mapper/LowerToCamelBeanMapperFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.mapper;
import org.skife.jdbi.v2.ResultSetMapperFactory;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
public class LowerToCamelBeanMapperFactory implements ResultSetMapperFactory {
private final Class<?> modelClazz;
public LowerToCamelBeanMapperFactory(final Class<?> modelClazz) {
this.modelClazz = modelClazz;
}
@Override
public boolean accepts(final Class type, final StatementContext ctx) {
return type.equals(modelClazz);
}
@SuppressWarnings("unchecked")
@Override
public ResultSetMapper mapperFor(final Class type, final StatementContext ctx) {
return new LowerToCamelBeanMapper(type);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/mapper/MapperBase.java | jdbi/src/main/java/org/killbill/commons/jdbi/mapper/MapperBase.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
public abstract class MapperBase {
protected LocalDate getDate(final ResultSet rs, final String fieldName) throws SQLException {
final Date resultStamp = rs.getDate(fieldName);
return rs.wasNull() ? null : new LocalDate(resultStamp, DateTimeZone.UTC);
}
protected DateTime getDateTime(final ResultSet rs, final String fieldName) throws SQLException {
final Timestamp resultStamp = rs.getTimestamp(fieldName);
return rs.wasNull() ? null : new DateTime(resultStamp).toDateTime(DateTimeZone.UTC);
}
protected UUID getUUID(final ResultSet resultSet, final String fieldName) throws SQLException {
final String result = resultSet.getString(fieldName);
return result == null ? null : UUID.fromString(result);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/mapper/LowerToCamelBeanMapper.java | jdbi/src/main/java/org/killbill/commons/jdbi/mapper/LowerToCamelBeanMapper.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.mapper;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.killbill.commons.utils.Strings;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
// Identical to org.skife.jdbi.v2.BeanMapper but maps created_date to createdDate
public class LowerToCamelBeanMapper<T> implements ResultSetMapper<T> {
private final Class<T> type;
private final Map<String, PropertyDescriptor> properties = new HashMap<>();
private final Map<String, PropertyMapper<ResultSet, ?>> propertiesMappers = new HashMap<>();
public LowerToCamelBeanMapper(final Class<T> type) {
this.type = type;
try {
final BeanInfo info = Introspector.getBeanInfo(type);
for (final PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
final String key = Strings.toSnakeCase(descriptor.getName()).toLowerCase();
properties.put(key, descriptor);
final PropertyMapper<ResultSet, ?> propertyMapper = getPropertyMapper(descriptor);
propertiesMappers.put(key, propertyMapper);
}
} catch (final IntrospectionException e) {
throw new IllegalArgumentException(e);
}
}
private static PropertyMapper<ResultSet, ?> getPropertyMapper(final PropertyDescriptor descriptor) {
final PropertyMapper<ResultSet, ?> propertyMapper;
final Class<?> propertyType = descriptor.getPropertyType();
if (propertyType.isAssignableFrom(Boolean.class) || propertyType.isAssignableFrom(boolean.class)) {
propertyMapper = ResultSet::getBoolean;
} else if (propertyType.isAssignableFrom(Byte.class) || propertyType.isAssignableFrom(byte.class)) {
propertyMapper = ResultSet::getByte;
} else if (propertyType.isAssignableFrom(Short.class) || propertyType.isAssignableFrom(short.class)) {
propertyMapper = ResultSet::getShort;
} else if (propertyType.isAssignableFrom(Integer.class) || propertyType.isAssignableFrom(int.class)) {
propertyMapper = ResultSet::getInt;
} else if (propertyType.isAssignableFrom(Long.class) || propertyType.isAssignableFrom(long.class)) {
propertyMapper = ResultSet::getLong;
} else if (propertyType.isAssignableFrom(Float.class) || propertyType.isAssignableFrom(float.class)) {
propertyMapper = ResultSet::getFloat;
} else if (propertyType.isAssignableFrom(Double.class) || propertyType.isAssignableFrom(double.class)) {
propertyMapper = ResultSet::getDouble;
} else if (propertyType.isAssignableFrom(BigDecimal.class)) {
propertyMapper = ResultSet::getBigDecimal;
} else if (propertyType.isAssignableFrom(DateTime.class)) {
propertyMapper = (rs, i) -> {
final Timestamp timestamp = rs.getTimestamp(i);
return timestamp == null ? null : new DateTime(timestamp).toDateTime(DateTimeZone.UTC);
};
} else if (propertyType.isAssignableFrom(Time.class)) {
propertyMapper = ResultSet::getTime;
} else if (propertyType.isAssignableFrom(LocalDate.class)) {
propertyMapper = (rs, i) -> {
// We store the LocalDate into a mysql 'date' as a string
// (See https://github.com/killbill/killbill-commons/blob/master/jdbi/src/main/java/org/killbill/commons/jdbi/argument/LocalDateArgumentFactory.java)
// So we also read it as a String which avoids any kind of transformation
//
// Note that we used previously the getDate(index, Calendar) method, but this is not thread safe as we discovered
// unless maybe -- untested --we pass a new instance of a Calendar each time
//
final String dateString = rs.getString(i);
return dateString == null ? null : new LocalDate(dateString, DateTimeZone.UTC);
};
} else if (propertyType.isAssignableFrom(DateTimeZone.class)) {
propertyMapper = (rs, i) -> {
final String dateTimeZoneString = rs.getString(i);
return dateTimeZoneString == null ? null : DateTimeZone.forID(dateTimeZoneString);
};
} else if (propertyType.isAssignableFrom(String.class)) {
propertyMapper = ResultSet::getString;
} else if (propertyType.isAssignableFrom(UUID.class)) {
propertyMapper = (rs, i) -> {
final String uuidString = rs.getString(i);
return uuidString == null ? null : UUID.fromString(uuidString);
};
} else if (propertyType.isEnum()) {
propertyMapper = (rs, i) -> {
final String enumString = rs.getString(i);
return enumString == null ? null : Enum.valueOf((Class<Enum>) propertyType, enumString);
};
} else if (propertyType == byte[].class) {
propertyMapper = ResultSet::getBytes;
} else {
propertyMapper = (rs, i) -> (Time) rs.getObject(i);
}
return propertyMapper;
}
private static Field getField(final Class<?> clazz, final String fieldName) throws NoSuchFieldException {
try {
return clazz.getDeclaredField(fieldName);
} catch (final NoSuchFieldException e) {
// Go up in the hierarchy
final Class<?> superClass = clazz.getSuperclass();
if (superClass == null) {
throw e;
} else {
return getField(superClass, fieldName);
}
}
}
@SuppressWarnings("rawtypes")
public T map(final int row, final ResultSet rs, final StatementContext ctx) throws SQLException {
final T bean;
try {
bean = type.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
throw new IllegalArgumentException(String.format("A bean, %s, was mapped which was not instantiable", type.getName()), e);
}
final Class beanClass = bean.getClass();
final ResultSetMetaData metadata = rs.getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); ++i) {
final String name = metadata.getColumnLabel(i).toLowerCase();
final PropertyMapper<ResultSet, ?> propertyMapper = propertiesMappers.get(name);
if (propertyMapper != null) {
Object value = propertyMapper.apply(rs, i);
// For h2, transform a JdbcBlob into a byte[]
if (value instanceof Blob) {
final Blob blob = (Blob) value;
value = blob.getBytes(1, (int) blob.length());
}
if (rs.wasNull() && !type.isPrimitive()) {
value = null;
}
try {
final PropertyDescriptor descriptor = properties.get(name);
final Method writeMethod = descriptor.getWriteMethod();
if (writeMethod != null) {
writeMethod.invoke(bean, value);
} else {
final String camelCasedName = Strings.toCamelCase(name, false, '_');
final Field field = getField(beanClass, camelCasedName);
field.setAccessible(true); // Often private...
field.set(bean, value);
}
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Unable to set field for property: name=%s, value=%s", name, value), e);
} catch (final NoSuchFieldException e) {
throw new IllegalArgumentException(String.format("Unable to find field for property, %s", name), e);
} catch (final IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Unable to access setter for property, %s", name), e);
} catch (final InvocationTargetException e) {
throw new IllegalArgumentException(String.format("Invocation target exception trying to invoker setter for the %s property", name), e);
}
}
}
return bean;
}
protected interface PropertyMapper<ResultSet, T> {
T apply(ResultSet rs, int i) throws SQLException;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/mapper/UUIDMapper.java | jdbi/src/main/java/org/killbill/commons/jdbi/mapper/UUIDMapper.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
public class UUIDMapper implements ResultSetMapper<UUID> {
@Override
public UUID map(final int index, final ResultSet resultSet, final StatementContext statementContext) throws SQLException {
return UUID.fromString(resultSet.getString(1));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/argument/DateTimeArgumentFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/argument/DateTimeArgumentFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.argument;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
public class DateTimeArgumentFactory implements ArgumentFactory<DateTime> {
@Override
public boolean accepts(final Class<?> expectedType, final Object value, final StatementContext ctx) {
return value instanceof DateTime;
}
@Override
public Argument build(final Class<?> expectedType, final DateTime value, final StatementContext ctx) {
return new DateTimeArgument(value);
}
public static class DateTimeArgument implements Argument {
private final DateTime value;
public DateTimeArgument(final DateTime value) {
this.value = value;
}
@Override
public void apply(final int position, final PreparedStatement statement, final StatementContext ctx) throws SQLException {
if (value != null) {
statement.setTimestamp(position, new Timestamp(value.toDate().getTime()));
} else {
statement.setNull(position, Types.TIMESTAMP);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("DateTimeArgument");
sb.append("{value=").append(value);
sb.append('}');
return sb.toString();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/argument/UUIDArgumentFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/argument/UUIDArgumentFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.argument;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
public class UUIDArgumentFactory implements ArgumentFactory<UUID> {
@Override
public boolean accepts(final Class<?> expectedType, final Object value, final StatementContext ctx) {
return value instanceof UUID;
}
@Override
public Argument build(final Class<?> expectedType, final UUID value, final StatementContext ctx) {
return new UUIDArgument(value);
}
public static class UUIDArgument implements Argument {
private final UUID value;
public UUIDArgument(final UUID value) {
this.value = value;
}
@Override
public void apply(final int position, final PreparedStatement statement, final StatementContext ctx) throws SQLException {
if (value != null) {
statement.setString(position, value.toString());
} else {
statement.setNull(position, Types.VARCHAR);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("UUIDArgument");
sb.append("{value=").append(value);
sb.append('}');
return sb.toString();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/argument/DateTimeZoneArgumentFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/argument/DateTimeZoneArgumentFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.argument;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.joda.time.DateTimeZone;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
public class DateTimeZoneArgumentFactory implements ArgumentFactory<DateTimeZone> {
@Override
public boolean accepts(final Class<?> expectedType, final Object value, final StatementContext ctx) {
return value instanceof DateTimeZone;
}
@Override
public Argument build(final Class<?> expectedType, final DateTimeZone value, final StatementContext ctx) {
return new DateTimeZoneArgument(value);
}
public static class DateTimeZoneArgument implements Argument {
private final DateTimeZone value;
public DateTimeZoneArgument(final DateTimeZone value) {
this.value = value;
}
@Override
public void apply(final int position, final PreparedStatement statement, final StatementContext ctx) throws SQLException {
if (value != null) {
statement.setString(position, value.toString());
} else {
statement.setNull(position, Types.VARCHAR);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("DateTimeZoneArgument");
sb.append("{value=").append(value);
sb.append('}');
return sb.toString();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/killbill/commons/jdbi/argument/LocalDateArgumentFactory.java | jdbi/src/main/java/org/killbill/commons/jdbi/argument/LocalDateArgumentFactory.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.jdbi.argument;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.joda.time.LocalDate;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
public class LocalDateArgumentFactory implements ArgumentFactory<LocalDate> {
@Override
public boolean accepts(final Class<?> expectedType, final Object value, final StatementContext ctx) {
return value instanceof LocalDate;
}
@Override
public Argument build(final Class<?> expectedType, final LocalDate value, final StatementContext ctx) {
return new LocalDateArgument(value);
}
public static class LocalDateArgument implements Argument {
// See org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData
private static final String POSTGRESQL = "PostgreSQL";
private final LocalDate value;
public LocalDateArgument(final LocalDate value) {
this.value = value;
}
@Override
public void apply(final int position, final PreparedStatement statement, final StatementContext ctx) throws SQLException {
final boolean isPostgreSQL = ctx != null &&
ctx.getConnection() != null &&
ctx.getConnection().getMetaData() != null &&
POSTGRESQL.equalsIgnoreCase(ctx.getConnection().getMetaData().getDatabaseProductName());
if (value != null && isPostgreSQL) {
// This might work on MySQL as well, but let's avoid conversions if we don't have to
// See also https://github.com/killbill/killbill/wiki/Date%2C-Datetime%2C-Timezone-and-time-Granularity-in-Kill-Bill
statement.setDate(position, new java.sql.Date(value.toDate().getTime()));
} else if (value != null) {
// ISO8601 format
statement.setString(position, value.toString());
} else {
statement.setNull(position, isPostgreSQL ? Types.DATE : Types.VARCHAR);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("LocalDateArgument");
sb.append("{value=").append(value);
sb.append('}');
return sb.toString();
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/test/java/org/killbill/automaton/TestStateMachine.java | automaton/src/test/java/org/killbill/automaton/TestStateMachine.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import org.killbill.commons.utils.io.Resources;
import org.killbill.xmlloader.XMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestStateMachine {
private final Logger logger = LoggerFactory.getLogger(TestStateMachine.class);
@Test(groups = "fast")
public void testStateMachine() throws Exception {
final DefaultStateMachineConfig sms = XMLLoader.getObjectFromString(Resources.getResource("org/killbill/automaton/PaymentStates.xml").toExternalForm(), DefaultStateMachineConfig.class);
Assert.assertEquals(sms.getStateMachines().length, 2);
final DefaultStateMachine sm1 = sms.getStateMachines()[0];
Assert.assertEquals(sm1.getStates().length, 3);
Assert.assertEquals(sm1.getStates()[0].getName(), "AUTH_INIT");
Assert.assertEquals(sm1.getStates()[1].getName(), "AUTH_SUCCESS");
Assert.assertEquals(sm1.getStates()[2].getName(), "AUTH_FAILED");
Assert.assertEquals(sm1.getOperations().length, 1);
Assert.assertEquals(sm1.getOperations()[0].getName(), "OP_AUTHORIZE");
Assert.assertEquals(sm1.getTransitions().length, 2);
Assert.assertEquals(sm1.getTransitions()[0].getInitialState().getName(), "AUTH_INIT");
Assert.assertEquals(sm1.getTransitions()[0].getOperation().getName(), "OP_AUTHORIZE");
Assert.assertEquals(sm1.getTransitions()[0].getOperationResult(), OperationResult.SUCCESS);
Assert.assertEquals(sm1.getTransitions()[0].getFinalState().getName(), "AUTH_SUCCESS");
Assert.assertEquals(sm1.getTransitions()[1].getInitialState().getName(), "AUTH_INIT");
Assert.assertEquals(sm1.getTransitions()[1].getOperation().getName(), "OP_AUTHORIZE");
Assert.assertEquals(sm1.getTransitions()[1].getOperationResult(), OperationResult.FAILURE);
Assert.assertEquals(sm1.getTransitions()[1].getFinalState().getName(), "AUTH_FAILED");
final DefaultStateMachine sm2 = sms.getStateMachines()[1];
Assert.assertEquals(sm2.getStates().length, 4);
Assert.assertEquals(sm2.getStates()[0].getName(), "CAPTURE_INIT");
Assert.assertEquals(sm2.getStates()[1].getName(), "CAPTURE_SUCCESS");
Assert.assertEquals(sm2.getStates()[2].getName(), "CAPTURE_FAILED");
Assert.assertEquals(sm2.getStates()[3].getName(), "CAPTURE_ERRORED");
Assert.assertEquals(sm2.getOperations().length, 1);
Assert.assertEquals(sm2.getOperations()[0].getName(), "OP_CAPTURE");
Assert.assertEquals(sm2.getTransitions().length, 3);
Assert.assertEquals(sm2.getTransitions()[0].getInitialState().getName(), "CAPTURE_INIT");
Assert.assertEquals(sm2.getTransitions()[0].getOperation().getName(), "OP_CAPTURE");
Assert.assertEquals(sm2.getTransitions()[0].getOperationResult(), OperationResult.SUCCESS);
Assert.assertEquals(sm2.getTransitions()[0].getFinalState().getName(), "CAPTURE_SUCCESS");
Assert.assertEquals(sm2.getTransitions()[1].getInitialState().getName(), "CAPTURE_INIT");
Assert.assertEquals(sm2.getTransitions()[1].getOperation().getName(), "OP_CAPTURE");
Assert.assertEquals(sm2.getTransitions()[1].getOperationResult(), OperationResult.FAILURE);
Assert.assertEquals(sm2.getTransitions()[1].getFinalState().getName(), "CAPTURE_FAILED");
Assert.assertEquals(sm2.getTransitions()[2].getInitialState().getName(), "CAPTURE_INIT");
Assert.assertEquals(sm2.getTransitions()[2].getOperation().getName(), "OP_CAPTURE");
Assert.assertEquals(sm2.getTransitions()[2].getOperationResult(), OperationResult.EXCEPTION);
Assert.assertEquals(sm2.getTransitions()[2].getFinalState().getName(), "CAPTURE_ERRORED");
Assert.assertEquals(sms.getLinkStateMachines().length, 1);
Assert.assertEquals(sms.getLinkStateMachines()[0].getInitialState().getName(), "AUTH_SUCCESS");
Assert.assertEquals(sms.getLinkStateMachines()[0].getInitialStateMachine().getName(), "AUTHORIZE");
Assert.assertEquals(sms.getLinkStateMachines()[0].getFinalState().getName(), "CAPTURE_INIT");
Assert.assertEquals(sms.getLinkStateMachines()[0].getFinalStateMachine().getName(), "CAPTURE");
}
@Test(groups = "fast")
public void testStateTransition() throws Exception {
final DefaultStateMachineConfig sms = XMLLoader.getObjectFromString(Resources.getResource("org/killbill/automaton/PaymentStates.xml").toExternalForm(), DefaultStateMachineConfig.class);
final DefaultStateMachine sm1 = sms.getStateMachines()[1];
final State state = sm1.getState("CAPTURE_INIT");
final Operation operation = sm1.getOperation("OP_CAPTURE");
state.runOperation(operation,
new Operation.OperationCallback() {
@Override
public OperationResult doOperationCallback() throws OperationException {
return OperationResult.SUCCESS;
}
},
new State.EnteringStateCallback() {
@Override
public void enteringState(final State newState, final Operation.OperationCallback operationCallback, final OperationResult operationResult, final State.LeavingStateCallback leavingStateCallback) {
logger.info("Entering state " + newState.getName());
Assert.assertEquals(newState.getName(), "CAPTURE_SUCCESS");
}
},
new State.LeavingStateCallback() {
@Override
public void leavingState(final State oldState) {
logger.info("Leaving state " + oldState.getName());
Assert.assertEquals(oldState.getName(), "CAPTURE_INIT");
}
}
);
state.runOperation(operation,
new Operation.OperationCallback() {
@Override
public OperationResult doOperationCallback() throws OperationException {
return OperationResult.FAILURE;
}
},
new State.EnteringStateCallback() {
@Override
public void enteringState(final State newState, final Operation.OperationCallback operationCallback, final OperationResult operationResult, final State.LeavingStateCallback leavingStateCallback) {
logger.info("Entering state " + newState.getName());
Assert.assertEquals(newState.getName(), "CAPTURE_FAILED");
}
},
new State.LeavingStateCallback() {
@Override
public void leavingState(final State oldState) {
logger.info("Leaving state " + oldState.getName());
Assert.assertEquals(oldState.getName(), "CAPTURE_INIT");
}
}
);
try {
state.runOperation(operation,
new Operation.OperationCallback() {
@Override
public OperationResult doOperationCallback() throws OperationException {
throw new OperationException();
}
},
new State.EnteringStateCallback() {
@Override
public void enteringState(final State newState, final Operation.OperationCallback operationCallback, final OperationResult operationResult, final State.LeavingStateCallback leavingStateCallback) {
logger.info("Entering state " + newState.getName());
Assert.assertEquals(newState.getName(), "CAPTURE_ERRORED");
}
},
new State.LeavingStateCallback() {
@Override
public void leavingState(final State oldState) {
logger.info("Leaving state " + oldState.getName());
Assert.assertEquals(oldState.getName(), "CAPTURE_INIT");
}
}
);
Assert.fail("Should throw an exception");
} catch (final OperationException e) {
Assert.assertTrue(true);
}
}
@Test(groups = "fast")
public void testLinkedStateMachines() throws Exception {
final DefaultStateMachineConfig sms = XMLLoader.getObjectFromString(Resources.getResource("org/killbill/automaton/PaymentStates.xml").toExternalForm(), DefaultStateMachineConfig.class);
final DefaultStateMachine sm1 = sms.getStateMachines()[0];
final State state = sm1.getState("AUTH_SUCCESS");
final DefaultStateMachine sm2 = sms.getStateMachines()[1];
final Operation operation = sm2.getOperation("OP_CAPTURE");
state.runOperation(operation,
new Operation.OperationCallback() {
@Override
public OperationResult doOperationCallback() throws OperationException {
return OperationResult.SUCCESS;
}
},
new State.EnteringStateCallback() {
@Override
public void enteringState(final State newState, final Operation.OperationCallback operationCallback, final OperationResult operationResult, final State.LeavingStateCallback leavingStateCallback) {
logger.info("Entering state " + newState.getName());
Assert.assertEquals(newState.getName(), "CAPTURE_SUCCESS");
}
},
new State.LeavingStateCallback() {
@Override
public void leavingState(final State oldState) {
logger.info("Leaving state " + oldState.getName());
Assert.assertEquals(oldState.getName(), "CAPTURE_INIT");
}
}
);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/test/java/org/killbill/automaton/dot/TestDOTBuilder.java | automaton/src/test/java/org/killbill/automaton/dot/TestDOTBuilder.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton.dot;
import java.util.Map;
import java.util.TreeMap;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDOTBuilder {
@Test(groups = "fast")
public void testGenerator() {
final DOTBuilder payment = new DOTBuilder("Payment");
payment.open(new TreeMap<>(Map.of("splines", "false")));
payment.openCluster("Retry");
final int retryInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int retrySuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int retryFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(retryInit, retrySuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(retryInit, retryFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.addPath(retryFailed, retryFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.openCluster("Transaction");
payment.openCluster("Authorize");
final int authInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int authSuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int authFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int authPending = payment.addNode("PENDING");
payment.addPath(authInit, authSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(authInit, authFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.addPath(authInit, authPending, new TreeMap<>(Map.of("label", "\"Op|P\"")));
payment.addPath(authPending, authSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(authPending, authFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.openCluster("Capture");
final int captureInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int captureSuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int captureFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(captureInit, captureSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(captureInit, captureFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.openCluster("Purchase");
final int purchaseInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int purchaseSuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int purchaseFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(purchaseInit, purchaseSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(purchaseInit, purchaseFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.openCluster("Void");
final int voidInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int voidSuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int voidFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(voidInit, voidSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(voidInit, voidFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.openCluster("Refund");
final int refundInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int refundSuccess = payment.addNode("SUCCESS", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int refundFailed = payment.addNode("FAILED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(refundInit, refundSuccess, new TreeMap<>(Map.of("label", "\"Op|S\"")));
payment.addPath(refundInit, refundFailed, new TreeMap<>(Map.of("label", "\"Op|F\"")));
payment.closeCluster();
payment.addPath(authSuccess, captureInit, new TreeMap<>(Map.of("style", "dotted", "label", "CAPTURE_AMOUNT_CHECK")));
payment.addPath(authSuccess, voidInit, new TreeMap<>(Map.of("style", "dotted")));
payment.addPath(captureSuccess, voidInit, new TreeMap<>(Map.of("style", "dotted")));
payment.addPath(captureSuccess, refundInit, new TreeMap<>(Map.of("style", "dotted", "label", "REFUND_AMOUNT_CHECK")));
payment.addPath(purchaseSuccess, refundInit, new TreeMap<>(Map.of("style", "dotted", "label", "REFUND_AMOUNT_CHECK")));
payment.closeCluster(); // Transaction
payment.openCluster("DirectPayment");
final int directPaymentInit = payment.addNode("INIT", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int directPaymentOpen = payment.addNode("OPEN", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
final int directPaymentClosed = payment.addNode("CLOSED", new TreeMap<>(Map.of("color", "grey", "style", "filled")));
payment.addPath(directPaymentInit, directPaymentOpen);
payment.addPath(directPaymentOpen, directPaymentClosed);
payment.addPath(directPaymentInit, authInit, new TreeMap<>(Map.of("style", "dotted", "color", "blue")));
payment.addPath(directPaymentInit, purchaseInit, new TreeMap<>(Map.of("style", "dotted", "color", "blue")));
payment.addPath(directPaymentOpen, authSuccess, new TreeMap<>(Map.of("style", "dotted", "color", "green")));
payment.addPath(directPaymentOpen, captureSuccess, new TreeMap<>(Map.of("style", "dotted", "color", "green")));
payment.addPath(directPaymentClosed, refundSuccess, new TreeMap<>(Map.of("style", "dotted", "color", "green")));
payment.addPath(directPaymentClosed, voidSuccess, new TreeMap<>(Map.of("style", "dotted", "color", "green")));
payment.closeCluster(); // DirectPayment
payment.close();
Assert.assertEquals(payment.toString(), "digraph Payment {\n" +
" splines=false;\n" +
" subgraph cluster_0 {\n" +
" label=\"Retry\";\n" +
" node_0 [color=grey style=filled label=INIT];\n" +
" node_1 [color=grey style=filled label=SUCCESS];\n" +
" node_2 [color=grey style=filled label=FAILED];\n" +
" node_0 -> node_1 [label=\"Op|S\"];\n" +
" node_0 -> node_2 [label=\"Op|F\"];\n" +
" node_2 -> node_2 [label=\"Op|F\"];\n" +
" }\n" +
" subgraph cluster_1 {\n" +
" label=\"Transaction\";\n" +
" subgraph cluster_2 {\n" +
" label=\"Authorize\";\n" +
" node_3 [color=grey style=filled label=INIT];\n" +
" node_4 [color=grey style=filled label=SUCCESS];\n" +
" node_5 [color=grey style=filled label=FAILED];\n" +
" node_6 [label=PENDING];\n" +
" node_3 -> node_4 [label=\"Op|S\"];\n" +
" node_3 -> node_5 [label=\"Op|F\"];\n" +
" node_3 -> node_6 [label=\"Op|P\"];\n" +
" node_6 -> node_4 [label=\"Op|S\"];\n" +
" node_6 -> node_5 [label=\"Op|F\"];\n" +
" }\n" +
" subgraph cluster_3 {\n" +
" label=\"Capture\";\n" +
" node_7 [color=grey style=filled label=INIT];\n" +
" node_8 [color=grey style=filled label=SUCCESS];\n" +
" node_9 [color=grey style=filled label=FAILED];\n" +
" node_7 -> node_8 [label=\"Op|S\"];\n" +
" node_7 -> node_9 [label=\"Op|F\"];\n" +
" }\n" +
" subgraph cluster_4 {\n" +
" label=\"Purchase\";\n" +
" node_10 [color=grey style=filled label=INIT];\n" +
" node_11 [color=grey style=filled label=SUCCESS];\n" +
" node_12 [color=grey style=filled label=FAILED];\n" +
" node_10 -> node_11 [label=\"Op|S\"];\n" +
" node_10 -> node_12 [label=\"Op|F\"];\n" +
" }\n" +
" subgraph cluster_5 {\n" +
" label=\"Void\";\n" +
" node_13 [color=grey style=filled label=INIT];\n" +
" node_14 [color=grey style=filled label=SUCCESS];\n" +
" node_15 [color=grey style=filled label=FAILED];\n" +
" node_13 -> node_14 [label=\"Op|S\"];\n" +
" node_13 -> node_15 [label=\"Op|F\"];\n" +
" }\n" +
" subgraph cluster_6 {\n" +
" label=\"Refund\";\n" +
" node_16 [color=grey style=filled label=INIT];\n" +
" node_17 [color=grey style=filled label=SUCCESS];\n" +
" node_18 [color=grey style=filled label=FAILED];\n" +
" node_16 -> node_17 [label=\"Op|S\"];\n" +
" node_16 -> node_18 [label=\"Op|F\"];\n" +
" }\n" +
" node_4 -> node_7 [label=CAPTURE_AMOUNT_CHECK style=dotted];\n" +
" node_4 -> node_13 [style=dotted];\n" +
" node_8 -> node_13 [style=dotted];\n" +
" node_8 -> node_16 [label=REFUND_AMOUNT_CHECK style=dotted];\n" +
" node_11 -> node_16 [label=REFUND_AMOUNT_CHECK style=dotted];\n" +
" }\n" +
" subgraph cluster_7 {\n" +
" label=\"DirectPayment\";\n" +
" node_19 [color=grey style=filled label=INIT];\n" +
" node_20 [color=grey style=filled label=OPEN];\n" +
" node_21 [color=grey style=filled label=CLOSED];\n" +
" node_19 -> node_20;\n" +
" node_20 -> node_21;\n" +
" node_19 -> node_3 [color=blue style=dotted];\n" +
" node_19 -> node_10 [color=blue style=dotted];\n" +
" node_20 -> node_4 [color=green style=dotted];\n" +
" node_20 -> node_8 [color=green style=dotted];\n" +
" node_21 -> node_17 [color=green style=dotted];\n" +
" node_21 -> node_14 [color=green style=dotted];\n" +
" }\n" +
"}\n");
//System.out.println(payment.toString()));
//System.out.flush();
//Files.write((new File("/var/tmp/payment.dot")).toPath(), payment.toString().getBytes()));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/StateMachineEntry.java | automaton/src/main/java/org/killbill/automaton/StateMachineEntry.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface StateMachineEntry {
public String getName();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/OperationException.java | automaton/src/main/java/org/killbill/automaton/OperationException.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public class OperationException extends Exception {
private final OperationResult operationResult;
public OperationException() {
this(null, OperationResult.EXCEPTION);
}
public OperationException(final Throwable cause) {
this(cause, OperationResult.EXCEPTION);
}
public OperationException(final Throwable cause, final OperationResult operationResult) {
super(cause);
this.operationResult = operationResult;
}
public OperationResult getOperationResult() {
return operationResult;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultState.java | automaton/src/main/java/org/killbill/automaton/DefaultState.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import org.killbill.xmlloader.ValidationErrors;
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultState extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements State, Externalizable {
@XmlAttribute(required = true)
@XmlID
private String name;
private DefaultStateMachine stateMachine;
// Required for deserialization
public DefaultState() {
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
return errors;
}
@Override
public String getName() {
return name;
}
@Override
public void runOperation(final Operation operation, final Operation.OperationCallback operationCallback, final EnteringStateCallback enteringStateCallback, final LeavingStateCallback leavingStateCallback)
throws MissingEntryException, OperationException {
OperationException rethrowableException = null;
OperationResult result = OperationResult.EXCEPTION;
Transition transition = null;
State initialState = this;
try {
final StateMachine destStateMachine = operation.getStateMachine();
try {
final LinkStateMachine linkStateMachine = DefaultLinkStateMachine.findLinkStateMachine(this.getStateMachine(), this, destStateMachine);
initialState = linkStateMachine.getFinalState();
} catch (final MissingEntryException e) {
initialState = this;
}
// If there is no transition from that state, we stop right there
if (!((DefaultState) initialState).getStateMachine().hasTransitionsFromStates(initialState.getName())) {
throw new MissingEntryException("No transition exists from state " + initialState.getName());
}
// If there is no enteringState transition regardless of the operation outcome, we stop right there
boolean hasAtLeastOneEnteringStateTransition = false;
for (final OperationResult operationResult : OperationResult.values()) {
try {
DefaultTransition.findTransition(initialState, operation, operationResult);
hasAtLeastOneEnteringStateTransition = true;
break;
} catch (final MissingEntryException ignored) {
}
}
if (!hasAtLeastOneEnteringStateTransition) {
throw new MissingEntryException("No entering state transition exists from state " + initialState.getName() + " for operation " + operation.getName());
}
leavingStateCallback.leavingState(initialState);
result = operation.run(operationCallback);
transition = DefaultTransition.findTransition(initialState, operation, result);
} catch (final OperationException e) {
rethrowableException = e;
// STEPH what happens if we get an exception here...
transition = DefaultTransition.findTransition(initialState, operation, e.getOperationResult());
} catch (final RuntimeException e) {
rethrowableException = new OperationException(e);
// transition = null - we don't want to transition
} finally {
if (transition != null) {
enteringStateCallback.enteringState(transition.getFinalState(), operationCallback, result, leavingStateCallback);
}
if (rethrowableException != null) {
throw rethrowableException;
}
}
}
public void setName(final String name) {
this.name = name;
}
public DefaultStateMachine getStateMachine() {
return stateMachine;
}
public void setStateMachine(final DefaultStateMachine stateMachine) {
this.stateMachine = stateMachine;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultState that = (DefaultState) o;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(name);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/StateMachineValidatingConfig.java | automaton/src/main/java/org/killbill/automaton/StateMachineValidatingConfig.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import org.killbill.xmlloader.ValidatingConfig;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.NONE)
public abstract class StateMachineValidatingConfig<Context> extends ValidatingConfig<Context> {
protected StateMachineEntry getEntry(final StateMachineEntry [] entries, final String entryName) throws MissingEntryException {
for (final StateMachineEntry cur : entries) {
if (cur.getName().equals(entryName)) {
return cur;
}
}
throw new MissingEntryException("Unknown entry " + entryName);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultLinkStateMachine.java | automaton/src/main/java/org/killbill/automaton/DefaultLinkStateMachine.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlIDREF;
import org.killbill.xmlloader.ValidationErrors;
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultLinkStateMachine extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements LinkStateMachine, Externalizable {
@XmlElement(name = "initialStateMachine", required = true)
@XmlIDREF
private DefaultStateMachine initialStateMachine;
@XmlElement(name = "initialState", required = true)
@XmlIDREF
private DefaultState initialState;
@XmlElement(name = "finalStateMachine", required = true)
@XmlIDREF
private DefaultStateMachine finalStateMachine;
@XmlElement(name = "finalState", required = true)
@XmlIDREF
private DefaultState finalState;
// Required for deserialization
public DefaultLinkStateMachine() {
}
@Override
public String getName() {
return initialStateMachine.getName() + "-" + finalStateMachine.getName();
}
@Override
public StateMachine getInitialStateMachine() {
return initialStateMachine;
}
@Override
public State getInitialState() {
return initialState;
}
@Override
public StateMachine getFinalStateMachine() {
return finalStateMachine;
}
@Override
public State getFinalState() {
return finalState;
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
return errors;
}
public void setInitialStateMachine(final DefaultStateMachine initialStateMachine) {
this.initialStateMachine = initialStateMachine;
}
public void setInitialState(final DefaultState initialState) {
this.initialState = initialState;
}
public void setFinalStateMachine(final DefaultStateMachine finalStateMachine) {
this.finalStateMachine = finalStateMachine;
}
public void setFinalState(final DefaultState finalState) {
this.finalState = finalState;
}
public static LinkStateMachine findLinkStateMachine(final StateMachine srcStateMachine, final State srcState, final StateMachine dstStateMachine) throws MissingEntryException {
return ((DefaultStateMachine) srcStateMachine).getStateMachineConfig().findLinkStateMachine(srcStateMachine, srcState, dstStateMachine);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultLinkStateMachine that = (DefaultLinkStateMachine) o;
if (initialStateMachine != null ? !initialStateMachine.equals(that.initialStateMachine) : that.initialStateMachine != null) {
return false;
}
if (initialState != null ? !initialState.equals(that.initialState) : that.initialState != null) {
return false;
}
if (finalStateMachine != null ? !finalStateMachine.equals(that.finalStateMachine) : that.finalStateMachine != null) {
return false;
}
return finalState != null ? finalState.equals(that.finalState) : that.finalState == null;
}
@Override
public int hashCode() {
int result = initialStateMachine != null ? initialStateMachine.hashCode() : 0;
result = 31 * result + (initialState != null ? initialState.hashCode() : 0);
result = 31 * result + (finalStateMachine != null ? finalStateMachine.hashCode() : 0);
result = 31 * result + (finalState != null ? finalState.hashCode() : 0);
return result;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(initialStateMachine);
out.writeObject(initialState);
out.writeObject(finalStateMachine);
out.writeObject(finalState);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.initialStateMachine = (DefaultStateMachine) in.readObject();
this.initialState = (DefaultState) in.readObject();
this.finalStateMachine = (DefaultStateMachine) in.readObject();
this.finalState = (DefaultState) in.readObject();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/StateMachine.java | automaton/src/main/java/org/killbill/automaton/StateMachine.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface StateMachine extends StateMachineEntry {
public State [] getStates();
public Transition [] getTransitions();
public Operation [] getOperations();
public State getState(final String stateName) throws MissingEntryException;
public Transition getTransition(final String transitionName) throws MissingEntryException;
public Operation getOperation(final String operationName) throws MissingEntryException;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/LinkStateMachine.java | automaton/src/main/java/org/killbill/automaton/LinkStateMachine.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface LinkStateMachine extends StateMachineEntry{
public StateMachine getInitialStateMachine();
public State getInitialState();
public StateMachine getFinalStateMachine();
public State getFinalState();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultOperation.java | automaton/src/main/java/org/killbill/automaton/DefaultOperation.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import org.killbill.xmlloader.ValidationErrors;
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultOperation extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements Operation, Externalizable {
@XmlAttribute(required = true)
@XmlID
private String name;
private DefaultStateMachine stateMachine;
// Required for deserialization
public DefaultOperation() {
}
@Override
public String getName() {
return name;
}
@Override
public StateMachine getStateMachine() {
return stateMachine;
}
@Override
public OperationResult run(final OperationCallback cb) throws OperationException {
return cb.doOperationCallback();
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
return errors;
}
public void setName(final String name) {
this.name = name;
}
public void setStateMachine(final DefaultStateMachine stateMachine) {
this.stateMachine = stateMachine;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultOperation that = (DefaultOperation) o;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(name);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/MissingEntryException.java | automaton/src/main/java/org/killbill/automaton/MissingEntryException.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public class MissingEntryException extends Exception {
public MissingEntryException() {
}
public MissingEntryException(final String message) {
super(message);
}
public MissingEntryException(final String message, final Throwable cause) {
super(message, cause);
}
public MissingEntryException(final Throwable cause) {
super(cause);
}
/*
// 1.7 only
public MissingEntryException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
*/
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/State.java | automaton/src/main/java/org/killbill/automaton/State.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface State extends StateMachineEntry {
public interface EnteringStateCallback {
public void enteringState(final State newState, final Operation.OperationCallback operationCallback, final OperationResult operationResult, final LeavingStateCallback leavingStateCallback);
}
public interface LeavingStateCallback {
public void leavingState(final State oldState) throws OperationException;
}
public void runOperation(final Operation operation, final Operation.OperationCallback operationCallback, final EnteringStateCallback enteringStateCallback, final LeavingStateCallback leavingStateCallback)
throws MissingEntryException, OperationException;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/OperationResult.java | automaton/src/main/java/org/killbill/automaton/OperationResult.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public enum OperationResult {
PENDING,
SUCCESS,
FAILURE,
EXCEPTION
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/Transition.java | automaton/src/main/java/org/killbill/automaton/Transition.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface Transition extends StateMachineEntry {
public State getInitialState();
public Operation getOperation();
public OperationResult getOperationResult();
public State getFinalState();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultTransition.java | automaton/src/main/java/org/killbill/automaton/DefaultTransition.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlIDREF;
import org.killbill.xmlloader.ValidationErrors;
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultTransition extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements Transition, Externalizable {
@XmlElement(name = "initialState", required = true)
@XmlIDREF
private DefaultState initialState;
@XmlElement(name = "operation", required = true)
@XmlIDREF
private DefaultOperation operation;
@XmlElement(name = "operationResult", required = true)
private OperationResult operationResult;
@XmlElement(name = "finalState", required = true)
@XmlIDREF
private DefaultState finalState;
private DefaultStateMachine stateMachine;
// Required for deserialization
public DefaultTransition() {
}
@Override
public String getName() {
return initialState.getName() + "-" + operation.getName() + "-" + operationResult;
}
@Override
public State getInitialState() {
return initialState;
}
@Override
public Operation getOperation() {
return operation;
}
@Override
public OperationResult getOperationResult() {
return operationResult;
}
@Override
public State getFinalState() {
return finalState;
}
public DefaultStateMachine getStateMachine() {
return stateMachine;
}
public void setStateMachine(final DefaultStateMachine stateMachine) {
this.stateMachine = stateMachine;
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
return errors;
}
public void setInitialState(final DefaultState initialState) {
this.initialState = initialState;
}
public void setOperation(final DefaultOperation operation) {
this.operation = operation;
}
public void setOperationResult(final OperationResult operationResult) {
this.operationResult = operationResult;
}
public void setFinalState(final DefaultState finalState) {
this.finalState = finalState;
}
public static Transition findTransition(final State initialState, final Operation operation, final OperationResult operationResult)
throws MissingEntryException {
return ((DefaultState) initialState).getStateMachine().findTransition(initialState, operation, operationResult);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultTransition that = (DefaultTransition) o;
if (initialState != null ? !initialState.equals(that.initialState) : that.initialState != null) {
return false;
}
if (operation != null ? !operation.equals(that.operation) : that.operation != null) {
return false;
}
if (operationResult != that.operationResult) {
return false;
}
return finalState != null ? finalState.equals(that.finalState) : that.finalState == null;
}
@Override
public int hashCode() {
int result = initialState != null ? initialState.hashCode() : 0;
result = 31 * result + (operation != null ? operation.hashCode() : 0);
result = 31 * result + (operationResult != null ? operationResult.hashCode() : 0);
result = 31 * result + (finalState != null ? finalState.hashCode() : 0);
return result;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(initialState);
out.writeObject(operation);
out.writeBoolean(operationResult != null);
if (operationResult != null) {
out.writeUTF(operationResult.name());
}
out.writeObject(finalState);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.initialState = (DefaultState) in.readObject();
this.operation = (DefaultOperation) in.readObject();
this.operationResult = in.readBoolean() ? OperationResult.valueOf(in.readUTF()) : null;
this.finalState = (DefaultState) in.readObject();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultStateMachine.java | automaton/src/main/java/org/killbill/automaton/DefaultStateMachine.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlID;
import org.killbill.xmlloader.ValidationErrors;
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultStateMachine extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements StateMachine, Externalizable {
@XmlAttribute(required = true)
@XmlID
private String name;
@XmlElementWrapper(name = "states", required = true)
@XmlElement(name = "state", required = true)
private DefaultState[] states;
@XmlElementWrapper(name = "transitions", required = true)
@XmlElement(name = "transition", required = true)
private DefaultTransition[] transitions;
@XmlElementWrapper(name = "operations", required = true)
@XmlElement(name = "operation", required = true)
private DefaultOperation[] operations;
private DefaultStateMachineConfig stateMachineConfig;
// Required for deserialization
public DefaultStateMachine() {
}
@Override
public void initialize(final DefaultStateMachineConfig root) {
stateMachineConfig = root;
for (final DefaultState cur : states) {
cur.initialize(root);
cur.setStateMachine(this);
}
for (final DefaultTransition cur : transitions) {
cur.initialize(root);
cur.setStateMachine(this);
}
for (final DefaultOperation cur : operations) {
cur.initialize(root);
cur.setStateMachine(this);
}
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
validateCollection(root, errors, states);
validateCollection(root, errors, transitions);
validateCollection(root, errors, operations);
return errors;
}
@Override
public String getName() {
return name;
}
@Override
public State[] getStates() {
return states;
}
@Override
public Transition[] getTransitions() {
return transitions;
}
@Override
public Operation[] getOperations() {
return operations;
}
@Override
public State getState(final String stateName) throws MissingEntryException {
return (State) getEntry(states, stateName);
}
@Override
public Transition getTransition(final String transitionName) throws MissingEntryException {
return (Transition) getEntry(transitions, transitionName);
}
@Override
public Operation getOperation(final String operationName) throws MissingEntryException {
return (Operation) getEntry(operations, operationName);
}
public boolean hasTransitionsFromStates(final String initState) {
return Stream.of(transitions)
.filter(input -> input != null && input.getInitialState().getName().equals(initState))
.iterator()
.hasNext();
}
public void setStates(final DefaultState[] states) {
this.states = states;
}
public void setTransitions(final DefaultTransition[] transitions) {
this.transitions = transitions;
}
public void setOperations(final DefaultOperation[] operations) {
this.operations = operations;
}
public DefaultStateMachineConfig getStateMachineConfig() {
return stateMachineConfig;
}
public void setStateMachineConfig(final DefaultStateMachineConfig stateMachineConfig) {
this.stateMachineConfig = stateMachineConfig;
}
public DefaultTransition findTransition(final State initialState, final Operation operation, final OperationResult operationResult)
throws MissingEntryException {
try {
return Stream.of(transitions)
.filter(input -> input != null &&
input.getInitialState().getName().equals(initialState.getName()) &&
input.getOperation().getName().equals(operation.getName()) &&
input.getOperationResult().equals(operationResult))
.findFirst()
.get();
} catch (final NoSuchElementException e) {
throw new MissingEntryException("Missing transition for initialState " + initialState.getName() +
", operation = " + operation.getName() + ", result = " + operationResult, e);
}
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultStateMachine that = (DefaultStateMachine) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (!Arrays.equals(states, that.states)) {
return false;
}
if (!Arrays.equals(transitions, that.transitions)) {
return false;
}
return Arrays.equals(operations, that.operations);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + Arrays.hashCode(states);
result = 31 * result + Arrays.hashCode(transitions);
result = 31 * result + Arrays.hashCode(operations);
return result;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeObject(states);
out.writeObject(transitions);
out.writeObject(operations);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
this.states = (DefaultState[]) in.readObject();
this.transitions = (DefaultTransition[]) in.readObject();
this.operations = (DefaultOperation[]) in.readObject();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/Operation.java | automaton/src/main/java/org/killbill/automaton/Operation.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface Operation extends StateMachineEntry {
public StateMachine getStateMachine();
public OperationResult run(OperationCallback cb) throws OperationException;
public interface OperationCallback {
public OperationResult doOperationCallback() throws OperationException;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/StateMachineConfig.java | automaton/src/main/java/org/killbill/automaton/StateMachineConfig.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
public interface StateMachineConfig {
public StateMachine[] getStateMachines();
public LinkStateMachine[] getLinkStateMachines();
public StateMachine getStateMachineForState(final String stateName) throws MissingEntryException;
public StateMachine getStateMachine(final String stateMachineName) throws MissingEntryException;
public LinkStateMachine getLinkStateMachine(final String linkStateMachineName) throws MissingEntryException;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/DefaultStateMachineConfig.java | automaton/src/main/java/org/killbill/automaton/DefaultStateMachineConfig.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.killbill.xmlloader.ValidationErrors;
@XmlRootElement(name = "stateMachineConfig")
@XmlAccessorType(XmlAccessType.NONE)
public class DefaultStateMachineConfig extends StateMachineValidatingConfig<DefaultStateMachineConfig> implements StateMachineConfig, Externalizable {
@XmlElementWrapper(name = "stateMachines", required = true)
@XmlElement(name = "stateMachine", required = true)
private DefaultStateMachine[] stateMachines;
@XmlElementWrapper(name = "linkStateMachines", required = false)
@XmlElement(name = "linkStateMachine", required = false)
private DefaultLinkStateMachine[] linkStateMachines = new DefaultLinkStateMachine[0];
// Required for deserialization
public DefaultStateMachineConfig() {
}
@Override
public void initialize(final DefaultStateMachineConfig root) {
for (final DefaultStateMachine cur : stateMachines) {
cur.initialize(root);
}
for (final DefaultLinkStateMachine cur : linkStateMachines) {
cur.initialize(root);
}
}
@Override
public ValidationErrors validate(final DefaultStateMachineConfig root, final ValidationErrors errors) {
validateCollection(root, errors, stateMachines);
validateCollection(root, errors, linkStateMachines);
return errors;
}
@Override
public StateMachine getStateMachine(final String stateMachineName) throws MissingEntryException {
return (StateMachine) getEntry(stateMachines, stateMachineName);
}
@Override
public LinkStateMachine getLinkStateMachine(final String linkStateMachineName) throws MissingEntryException {
return (LinkStateMachine) getEntry(linkStateMachines, linkStateMachineName);
}
@Override
public LinkStateMachine[] getLinkStateMachines() {
return linkStateMachines;
}
@Override
public StateMachine getStateMachineForState(final String stateName) throws MissingEntryException {
for (final DefaultStateMachine cur : stateMachines) {
for (final State st : cur.getStates()) {
if (st.getName().equals(stateName)) {
return cur;
}
}
}
throw new MissingEntryException("Cannot find stateMachine associated with state" + stateName);
}
public DefaultStateMachine[] getStateMachines() {
return stateMachines;
}
public void setStateMachines(final DefaultStateMachine[] stateMachines) {
this.stateMachines = stateMachines;
}
public void setLinkStateMachines(final DefaultLinkStateMachine[] linkStateMachines) {
this.linkStateMachines = linkStateMachines;
}
public LinkStateMachine findLinkStateMachine(final StateMachine srcStateMachine, final State srcState, final StateMachine dstStateMachine) throws MissingEntryException {
try {
return Stream.of(linkStateMachines)
.filter(input -> input != null &&
input.getInitialStateMachine().getName().equals(srcStateMachine.getName()) &&
input.getInitialState().getName().equals(srcState.getName()) &&
input.getFinalStateMachine().getName().equals(dstStateMachine.getName()))
.findFirst().get();
} catch (final NoSuchElementException e) {
throw new MissingEntryException("Missing transition for srcStateMachine " + srcStateMachine.getName() +
", srcState = " + srcState.getName() + ", dstStateMachine = " + dstStateMachine.getName(), e);
}
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DefaultStateMachineConfig that = (DefaultStateMachineConfig) o;
if (!Arrays.equals(stateMachines, that.stateMachines)) {
return false;
}
return Arrays.equals(linkStateMachines, that.linkStateMachines);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(stateMachines);
result = 31 * result + Arrays.hashCode(linkStateMachines);
return result;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(stateMachines);
out.writeObject(linkStateMachines);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
this.stateMachines = (DefaultStateMachine[]) in.readObject();
this.linkStateMachines = (DefaultLinkStateMachine[]) in.readObject();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/dot/DOTBuilder.java | automaton/src/main/java/org/killbill/automaton/dot/DOTBuilder.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton.dot;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.killbill.commons.utils.MapJoiner;
public class DOTBuilder {
private static final String INDENT = " ";
private static final String NEW_LINE = "\n";
private static final String SPACE = " ";
private static final String EQUAL = "=";
private static final MapJoiner MAP_JOINER = new MapJoiner(EQUAL, SPACE);
private static final String SEMI_COLON = ";";
private final String name;
private final StringBuilder output;
private int nextNodeId;
private int nextClusterId;
private int currentIndent;
private String currentIndentString;
public DOTBuilder(final String name) {
this.name = name;
this.output = new StringBuilder();
this.nextNodeId = 0;
this.nextClusterId = 0;
this.currentIndent = 1;
rebuildCurrentIndent();
}
public int addNode(final String name) {
return addNode(name, null);
}
public int addNode(final String name, @Nullable final Map<String, String> attributesOrNull) {
// attributes is for example label="Foo" or shape=box
final Map<String, String> attributes = new HashMap<>();
attributes.put("label", name);
if (attributesOrNull != null) {
attributes.putAll(attributesOrNull);
}
final String id = getNodeIdSymbol(nextNodeId);
nextNodeId++;
output.append(currentIndentString)
.append(id);
addAttributesInlineWithSpace(attributes);
return nextNodeId - 1;
}
public void addPath(final int fromNodeId, final int toNodeId) {
addPath(fromNodeId, toNodeId, null);
}
public void addPath(final int fromNodeId, final int toNodeId, @Nullable final Map<String, String> attributes) {
addPath(getNodeIdSymbol(fromNodeId), getNodeIdSymbol(toNodeId), true, attributes);
}
public void addPath(final String from, final String to, final boolean directed, @Nullable final Map<String, String> attributes) {
final String edgeSymbol = "-" + (directed ? ">" : "-");
output.append(currentIndentString)
.append(from)
.append(SPACE)
.append(edgeSymbol)
.append(SPACE)
.append(to);
addAttributesInlineWithSpace(attributes);
}
public void openCluster(final String name) {
openCluster(name, null);
}
public void openCluster(final String name, @Nullable final Map<String, String> attributes) {
output.append(currentIndentString)
.append("subgraph")
.append(SPACE)
.append("cluster_").append(nextClusterId)
.append(SPACE)
.append("{")
.append(NEW_LINE);
nextClusterId++;
increaseCurrentIndent();
output.append(currentIndentString)
.append("label")
.append(EQUAL)
.append("\"")
.append(name)
.append("\"")
.append(SEMI_COLON)
.append(NEW_LINE);
addAttributes(attributes);
}
public void closeCluster() {
decreaseCurrentIndent();
output.append(currentIndentString)
.append("}")
.append(NEW_LINE);
}
public void open() {
open(null);
}
public void open(@Nullable final Map<String, String> attributes) {
output.append("digraph")
.append(SPACE)
.append(name)
.append(SPACE)
.append("{")
.append(NEW_LINE);
addAttributesNoBrackets(attributes);
}
private void addAttributes(@Nullable final Map<String, String> attributes) {
if (attributes != null) {
output.append(currentIndentString);
addAttributesInlineNoSpace(attributes);
}
}
private void addAttributesNoBrackets(@Nullable final Map<String, String> attributes) {
if (attributes != null) {
output.append(currentIndentString);
addAttributesInline(attributes, false, false);
}
}
private void addAttributesInlineNoSpace(@Nullable final Map<String, String> attributes) {
addAttributesInline(attributes, false);
}
private void addAttributesInlineWithSpace(@Nullable final Map<String, String> attributes) {
addAttributesInline(attributes, true);
}
private void addAttributesInline(@Nullable final Map<String, String> attributes, final boolean withSpace) {
addAttributesInline(attributes, withSpace, true);
}
private void addAttributesInline(@Nullable final Map<String, String> attributes, final boolean withSpace, final boolean withBrackets) {
if (attributes != null) {
final String attributesSymbol = (withSpace ? SPACE : "") + (withBrackets ? "[" : "") + MAP_JOINER.join(attributes) + (withBrackets ? "]" : "");
output.append(attributesSymbol);
}
output.append(SEMI_COLON)
.append(NEW_LINE);
}
public void close() {
output.append("}")
.append(NEW_LINE);
}
private String getNodeIdSymbol(final int nodeId) {
return "node_" + nodeId;
}
private void increaseCurrentIndent() {
currentIndent++;
rebuildCurrentIndent();
}
private void decreaseCurrentIndent() {
currentIndent--;
rebuildCurrentIndent();
}
private void rebuildCurrentIndent() {
currentIndentString = "";
for (int i = 0; i < currentIndent; i++) {
currentIndentString += INDENT;
}
}
@Override
public String toString() {
return output.toString();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/dot/DefaultStateMachineConfigDOTGenerator.java | automaton/src/main/java/org/killbill/automaton/dot/DefaultStateMachineConfigDOTGenerator.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton.dot;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.killbill.automaton.*;
import org.killbill.automaton.graph.Helpers;
public class DefaultStateMachineConfigDOTGenerator {
private final String name;
private final StateMachineConfig config;
// We assume state names are unique across all state machines
private final Map<String, Integer> statesNodeIds = new HashMap<String, Integer>();
private DOTBuilder dot;
public DefaultStateMachineConfigDOTGenerator(final String name, final StateMachineConfig config) {
this.name = name;
this.config = config;
}
public DOTBuilder getDot() {
return dot;
}
public void build() {
dot = new DOTBuilder(name);
dot.open();
//dot.open(ImmutableMap.<String, String>of("splines", "false"));
for (final StateMachine stateMachine : config.getStateMachines()) {
final Set<String> initialStates = Helpers.findInitialStates(stateMachine);
final Set<String> finalStates = Helpers.findFinalStates(stateMachine);
dot.openCluster(stateMachine.getName());
for (final State state : stateMachine.getStates()) {
drawState(state, initialStates, finalStates);
}
for (final Transition transition : stateMachine.getTransitions()) {
drawTransition(transition);
}
dot.closeCluster();
}
for (final LinkStateMachine linkStateMachine : config.getLinkStateMachines()) {
drawLinkStateMachine(linkStateMachine);
}
dot.close();
}
@Override
public String toString() {
if (dot == null) {
build();
}
return dot.toString();
}
private void drawState(final State state, final Collection<String> initialStates, final Collection<String> finalStates) {
final Map<String, String> attributes = new HashMap<String, String>();
if (initialStates.contains(state.getName()) || finalStates.contains(state.getName())) {
attributes.put("color", "grey");
attributes.put("style", "filled");
}
final int nodeId = dot.addNode(state.getName(), attributes);
statesNodeIds.put(state.getName(), nodeId);
}
private void drawTransition(final Transition transition) {
final Integer fromNodeId = statesNodeIds.get(transition.getInitialState().getName());
final Integer toNodeId = statesNodeIds.get(transition.getFinalState().getName());
final String color;
switch (transition.getOperationResult()) {
case FAILURE:
case EXCEPTION:
color = "red";
break;
case SUCCESS:
color = "green";
break;
default:
color = "black";
break;
}
final String label = String.format("<%s<SUB>|%s</SUB>>", transition.getOperation().getName(), transition.getOperationResult().name().charAt(0));
dot.addPath(fromNodeId, toNodeId, Map.<String, String>of("label", label, "color", color));
}
private void drawLinkStateMachine(final LinkStateMachine linkStateMachine) {
final Integer fromNodeId = statesNodeIds.get(linkStateMachine.getInitialState().getName());
final Integer toNodeId = statesNodeIds.get(linkStateMachine.getFinalState().getName());
dot.addPath(fromNodeId, toNodeId, Map.<String, String>of("style", "dotted"));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/automaton/src/main/java/org/killbill/automaton/graph/Helpers.java | automaton/src/main/java/org/killbill/automaton/graph/Helpers.java | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.automaton.graph;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.killbill.automaton.State;
import org.killbill.automaton.StateMachine;
import org.killbill.automaton.Transition;
public class Helpers {
// Might be nicer to return Set<State>, but a bit more difficult to work with
// We assume state names are unique anyways
public static Set<String> findInitialStates(final StateMachine stateMachine) {
return findEdgeStates(stateMachine, true);
}
public static Set<String> findFinalStates(final StateMachine stateMachine) {
return findEdgeStates(stateMachine, false);
}
private static Set<String> findEdgeStates(final StateMachine stateMachine, final boolean initial) {
final Set<String> edgeStates = new HashSet<String>();
final Collection<String> complementStates = new HashSet<String>();
for (final Transition transition : stateMachine.getTransitions()) {
final String stateName = initial ? transition.getFinalState().getName() : transition.getInitialState().getName();
complementStates.add(stateName);
}
for (final State state : stateMachine.getStates()) {
if (!complementStates.contains(state.getName())) {
edgeStates.add(state.getName());
}
}
return edgeStates;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestExposeMappedReplacements.java | config-magic/src/test/java/org/skife/config/TestExposeMappedReplacements.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Category(ConfigMagicTests.class)
public class TestExposeMappedReplacements {
@Test
public void testExposeReplacements() {
final Properties properties = new Properties();
properties.put("wat.1", "xyzzy");
final ConfigurationObjectFactory factory = new AugmentedConfigurationObjectFactory(properties);
final Map<String, String> map = new HashMap<String, String>();
map.put("a", "1");
map.put("b", "2");
final ReplacementConfig config = factory.buildWithReplacements(ReplacementConfig.class, map);
assertEquals("xyzzy", config.getWat());
assertEquals(map, config.getMap());
}
@Test
public void testNoReplacements() {
final ConfigurationObjectFactory factory = new AugmentedConfigurationObjectFactory(new Properties());
final ReplacementConfig config = factory.build(ReplacementConfig.class);
assertTrue(config.getMap().isEmpty());
}
@Test
public void testKeyReplacement() {
final ConfigurationObjectFactory factory = new AugmentedConfigurationObjectFactory(new Properties());
final Map<String, String> map = new HashMap<String, String>();
map.put("a", "1");
map.put("b", "2");
final ReplacementConfig config = factory.buildWithReplacements(ReplacementConfig.class, map);
assertEquals("1", config.getAString());
assertEquals(2, config.getBInt());
}
@Test
public void testDefaultValues() {
final ConfigurationObjectFactory factory = new AugmentedConfigurationObjectFactory(new Properties());
final ReplacementConfig config = factory.build(ReplacementConfig.class);
assertEquals(null, config.getDefaultNull());
assertEquals(3, config.getDefault3());
}
public interface ReplacementConfig {
@Config("wat.${a}")
@DefaultNull
String getWat();
@ConfigReplacements
Map<String, String> getMap();
@ConfigReplacements("a")
@Default("invalid")
String getAString();
@ConfigReplacements("b")
@Default("999")
int getBInt();
@ConfigReplacements("x")
@DefaultNull
String getDefaultNull();
@ConfigReplacements("y")
@Default("3")
int getDefault3();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/MultiConfig.java | config-magic/src/test/java/org/skife/config/MultiConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface MultiConfig {
@Config("singleOption")
@Default("failed!")
String getSingleOption();
@Config({"singleOption"})
@Default("failed!")
String getSingleOption2();
@Config({"multiOption1", "multiOption2"})
@Default("failed!")
String getMultiOption1();
@Config({"doesNotExistOption", "multiOption2"})
@Default("failed!")
String getMultiOption2();
@Config({"doesNotExistOption", "alsoDoesNotExistOption"})
@Default("theDefault")
String getMultiDefault();
@Config({"${key}ExtOption", "defaultOption"})
@Default("failed!")
String getReplaceOption();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/WibbleConfig.java | config-magic/src/test/java/org/skife/config/WibbleConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface WibbleConfig {
@Config("the-url")
Wibble getWibble();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/ConfigMagicTests.java | config-magic/src/test/java/org/skife/config/ConfigMagicTests.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public interface ConfigMagicTests {
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Config4.java | config-magic/src/test/java/org/skife/config/Config4.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface Config4 {
String getOption();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestClasses.java | config-magic/src/test/java/org/skife/config/TestClasses.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestClasses {
@Test
public void testRawType() {
final WithRawType config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", Object.class.getName())).build(WithRawType.class);
Assert.assertEquals(config.getTheClazz(), Object.class);
}
@Test(expected = IllegalArgumentException.class)
public void testRawTypeNotFound() {
new AugmentedConfigurationObjectFactory(Props.of("theClazz", "does.not.Exist")).build(WithRawType.class);
}
@Test(expected = IllegalArgumentException.class)
public void testRawTypeIllegal() {
new AugmentedConfigurationObjectFactory(Props.of("theClazz", "not a class")).build(WithRawType.class);
}
@Test
public void testRawTypeWithDefault() {
final WithRawTypeAndDefault config = new AugmentedConfigurationObjectFactory(new Properties()).build(WithRawTypeAndDefault.class);
Assert.assertEquals(config.getTheClazz(), Object.class);
}
@Test
public void testRawTypeWithNullDefault() {
final WithRawType config = new AugmentedConfigurationObjectFactory(new Properties()).build(WithRawType.class);
Assert.assertNull(config.getTheClazz());
}
@Test(expected = IllegalArgumentException.class)
public void testRawTypeWithNotFoundDefault() {
new AugmentedConfigurationObjectFactory(new Properties()).build(WithRawTypeAndUndefinedDefault.class);
}
@Test(expected = IllegalArgumentException.class)
public void testRawTypeWithIllegalDefault() {
new AugmentedConfigurationObjectFactory(new Properties()).build(WithRawTypeAndIllegalDefault.class);
}
@Test
public void testUnspecifiedType() {
final WithUnspecifiedType config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", Foo.class.getName())).build(WithUnspecifiedType.class);
Assert.assertEquals(config.getTheClazz(), Foo.class);
}
@Test
public void testExtends() {
final WithExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", Foo.class.getName())).build(WithExtends.class);
Assert.assertEquals(config.getTheClazz(), Foo.class);
}
@Test
public void testExtendsWithSubClass() {
final WithExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", FooSub.class.getName())).build(WithExtends.class);
Assert.assertEquals(config.getTheClazz(), FooSub.class);
}
@Test(expected = IllegalArgumentException.class)
public void testExtendsWithSuperClass() {
new AugmentedConfigurationObjectFactory(Props.of("theClazz", FooSuper.class.getName())).build(WithExtends.class);
}
@Test(expected = IllegalArgumentException.class)
public void testExtendsWithUnrelatedClass() {
new AugmentedConfigurationObjectFactory(Props.of("theClazz", Properties.class.getName())).build(WithExtends.class);
}
@Test
public void testNestedExtends() {
final WithNestedExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", FooList.class.getName())).build(WithNestedExtends.class);
Assert.assertEquals(config.getTheClazz(), FooList.class);
}
@Test
public void testNestedExtendsWithSubClass() {
final WithNestedExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", FooSubList.class.getName())).build(WithNestedExtends.class);
Assert.assertEquals(config.getTheClazz(), FooSubList.class);
}
@Test
public void testNestedExtendsWithSuperClass() {
final WithNestedExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", FooSuperList.class.getName())).build(WithNestedExtends.class);
Assert.assertEquals(config.getTheClazz(), FooSuperList.class);
}
@Test
public void testNestedExtendsWithUnrelatedClass() {
final WithNestedExtends config = new AugmentedConfigurationObjectFactory(Props.of("theClazz", StringList.class.getName())).build(WithNestedExtends.class);
Assert.assertEquals(config.getTheClazz(), StringList.class);
}
public interface WithRawType {
@SuppressWarnings("rawtypes")
@Config("theClazz")
@DefaultNull
Class getTheClazz();
}
public interface WithRawTypeAndDefault {
@SuppressWarnings("rawtypes")
@Config("theClazz")
@Default("java.lang.Object")
Class getTheClazz();
}
public interface WithRawTypeAndUndefinedDefault {
@SuppressWarnings("rawtypes")
@Config("theClazz")
@Default("does.not.Exist")
Class getTheClazz();
}
public interface WithRawTypeAndIllegalDefault {
@SuppressWarnings("rawtypes")
@Config("theClazz")
@Default("not a class")
Class getTheClazz();
}
public interface WithUnspecifiedType {
@Config("theClazz")
Class<?> getTheClazz();
}
public interface WithExtends {
@Config("theClazz")
Class<? extends Foo> getTheClazz();
}
public interface WithNestedExtends {
@Config("theClazz")
Class<? extends List<? extends Foo>> getTheClazz();
}
public static class FooSuper {}
public static class Foo extends FooSuper {}
public static class FooSub extends Foo {}
@SuppressWarnings("serial")
public static class FooSuperList extends ArrayList<FooSuper> {}
@SuppressWarnings("serial")
public static class FooList extends ArrayList<Foo> {}
@SuppressWarnings("serial")
public static class FooSubList extends ArrayList<FooSub> {}
@SuppressWarnings("serial")
public static class StringList extends ArrayList<String> {}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Config1.java | config-magic/src/test/java/org/skife/config/Config1.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface Config1 {
@Config("stringOption")
String getStringOption();
@Config("booleanOption")
boolean getBooleanOption();
@Config("boxedBooleanOption")
Boolean getBoxedBooleanOption();
@Config("byteOption")
byte getByteOption();
@Config("boxedByteOption")
Byte getBoxedByteOption();
@Config("shortOption")
short getShortOption();
@Config("boxedShortOption")
Short getBoxedShortOption();
@Config("integerOption")
int getIntegerOption();
@Config("boxedIntegerOption")
Integer getBoxedIntegerOption();
@Config("longOption")
long getLongOption();
@Config("boxedLongOption")
Long getBoxedLongOption();
@Config("floatOption")
float getFloatOption();
@Config("boxedFloatOption")
Float getBoxedFloatOption();
@Config("doubleOption")
double getDoubleOption();
@Config("boxedDoubleOption")
Double getBoxedDoubleOption();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/ConfigEnum.java | config-magic/src/test/java/org/skife/config/ConfigEnum.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public enum ConfigEnum {
ONE,
TWO,
THREE;
public String toString() {
return name().toLowerCase();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/CoercionConfig.java | config-magic/src/test/java/org/skife/config/CoercionConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.net.URI;
interface CoercionConfig {
@Config("the-url")
URI getURI();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Wibble.java | config-magic/src/test/java/org/skife/config/Wibble.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public class Wibble {
private String url = null;
public String getURL() {
return url;
}
public void setURL(final String url) {
this.url = url;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestFile.java | config-magic/src/test/java/org/skife/config/TestFile.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.io.File;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestFile {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("file2", "..");
}});
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClassDefault() {
final EmptyClass ec = cof.build(EmptyClass.class);
Assert.assertEquals(new File("."), ec.getFile());
}
@Test
public void testAbstractClassDefault() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertEquals(new File(".."), ec.getFile());
}
@Test
public void testAbstractClassDefaultNull() {
final EmptyAbstractClassDefaultNull ec = cof.build(EmptyAbstractClassDefaultNull.class);
Assert.assertNull(ec.getFile());
}
public static class EmptyClass {
@Config("file1")
@Default(".")
public File getFile() {
return null;
}
}
public abstract static class EmptyAbstractClass {
@Config("file2")
public abstract File getFile();
}
public abstract static class EmptyAbstractClassDefaultNull {
@Config("file3")
@DefaultNull
public abstract File getFile();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestDefaultsPresent.java | config-magic/src/test/java/org/skife/config/TestDefaultsPresent.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestDefaultsPresent {
private AugmentedConfigurationObjectFactory cof = null;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClassDefault() {
final EmptyClass ec = cof.build(EmptyClass.class);
Assert.assertEquals("default-value", ec.getValue());
}
@Test
public void testAbstractClassDefault() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertEquals("default-value", ec.getValue());
}
@Test
public void testClassDefaultNull() {
final EmptyClassDefaultNull ec = cof.build(EmptyClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testAbstractClassDefaultNull() {
final EmptyAbstractClassDefaultNull ec = cof.build(EmptyAbstractClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
public static class EmptyClass {
@Config("value")
@Default("default-value")
public String getValue() {
return "value-default";
}
}
public abstract static class EmptyAbstractClass {
@Config("value")
@Default("default-value")
public String getValue() {
return "value-default";
}
}
public static class EmptyClassDefaultNull {
@Config("value")
@DefaultNull
public String getValue() {
return "value-default";
}
}
public abstract static class EmptyAbstractClassDefaultNull {
@Config("value")
@DefaultNull
public String getValue() {
return "value-default";
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestDefaultNull.java | config-magic/src/test/java/org/skife/config/TestDefaultNull.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestDefaultNull {
private AugmentedConfigurationObjectFactory cof = null;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClass() {
final EmptyClass ec = cof.build(EmptyClass.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterface() {
final EmptyInterface ec = cof.build(EmptyInterface.class);
Assert.assertNull(ec.getValue());
}
@Test(expected = IllegalArgumentException.class)
public void testDoubleFeature() {
cof.build(DoubleFeature.class);
}
public interface EmptyInterface {
@Config("value")
@DefaultNull
String getValue();
}
public abstract static class EmptyClass {
@Config("value")
@DefaultNull
public abstract String getValue();
}
public static class DoubleFeature {
@Config("value")
@DefaultNull
@Default("value-default")
public String getValue() {
return "default-value";
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestTimeSpan.java | config-magic/src/test/java/org/skife/config/TestTimeSpan.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestTimeSpan {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testMilliSeconds() {
final ClassWithMilliseconds ec = cof.build(ClassWithMilliseconds.class);
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.MILLISECONDS, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.MILLISECONDS), ec.getValue());
Assert.assertEquals(5, ec.getValue().getMillis());
}
@Test
public void testSeconds() {
final ClassWithSeconds ec = cof.build(ClassWithSeconds.class);
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.SECONDS, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.SECONDS), ec.getValue());
Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS), ec.getValue().getMillis());
}
@Test
public void testMinutes() {
final ClassWithMinutes ec = cof.build(ClassWithMinutes.class);
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.MINUTES, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.MINUTES), ec.getValue());
Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES), ec.getValue().getMillis());
}
@Test
public void testHours() {
final ClassWithHours ec = cof.build(ClassWithHours.class);
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.HOURS, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.HOURS), ec.getValue());
Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS), ec.getValue().getMillis());
}
@Test
public void testDays() {
final ClassWithDays ec = cof.build(ClassWithDays.class);
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.DAYS, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.DAYS), ec.getValue());
Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.DAYS), ec.getValue().getMillis());
}
// for [Issue-5]
@Test
public void testAliases() {
Assert.assertEquals(new TimeSpan("5ms"), new TimeSpan("5milliseconds"));
Assert.assertEquals(new TimeSpan("1ms"), new TimeSpan("1 millisecond"));
Assert.assertEquals(new TimeSpan("7s"), new TimeSpan("7seconds"));
Assert.assertEquals(new TimeSpan("1s"), new TimeSpan("1second"));
Assert.assertEquals(new TimeSpan("15m"), new TimeSpan("15minutes"));
Assert.assertEquals(new TimeSpan("1m"), new TimeSpan("1minute"));
Assert.assertEquals(new TimeSpan("7m"), new TimeSpan("7min"));
Assert.assertEquals(new TimeSpan("25h"), new TimeSpan("25hours"));
Assert.assertEquals(new TimeSpan("1h"), new TimeSpan("1hour"));
Assert.assertEquals(new TimeSpan("31d"), new TimeSpan("31days"));
Assert.assertEquals(new TimeSpan("1d"), new TimeSpan("1day"));
}
// for [Issue-6]
@Test
public void testWhitespace() {
final ClassWithTimespanWithWhitespace ec = cof.build(ClassWithTimespanWithWhitespace.class);
// "5 h"
Assert.assertEquals(5, ec.getValue().getPeriod());
Assert.assertEquals(TimeUnit.HOURS, ec.getValue().getUnit());
Assert.assertEquals(new TimeSpan(5, TimeUnit.HOURS), ec.getValue());
Assert.assertEquals(TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS), ec.getValue().getMillis());
Assert.assertEquals(new TimeSpan("5ms"), new TimeSpan("5 milliseconds"));
Assert.assertEquals(new TimeSpan("5s"), new TimeSpan("5 seconds"));
Assert.assertEquals(new TimeSpan("5m"), new TimeSpan("5 minutes"));
Assert.assertEquals(new TimeSpan("5d"), new TimeSpan("5 days"));
}
@Test(expected = IllegalArgumentException.class)
public void testNoUnit() {
cof.build(ClassWithTimespanWithoutUnit.class);
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalUnit() {
cof.build(ClassWithTimespanWithIllegalUnit.class);
}
public abstract static class ClassWithMilliseconds {
@Config("value")
@Default("5ms")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithSeconds {
@Config("value")
@Default("5s")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithSeconds2 {
@Config("value")
@Default("5seconds")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithMinutes {
@Config("value")
@Default("5m")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithHours {
@Config("value")
@Default("5h")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithDays {
@Config("value")
@Default("5d")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithTimespanWithoutUnit {
@Config("value")
@Default("5")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithTimespanWithIllegalUnit {
@Config("value")
@Default("5x")
public abstract TimeSpan getValue();
}
public abstract static class ClassWithTimespanWithWhitespace {
@Config("value")
@Default("5 h")
public abstract TimeSpan getValue();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/EnumeratedConfig1.java | config-magic/src/test/java/org/skife/config/EnumeratedConfig1.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public interface EnumeratedConfig1 {
@Config("option.${type}")
@Default("default")
String getStringOption(@Param("type") ConfigEnum type);
@Config("another-option.${type}.${s}")
@Default("default")
String getStringOption2Types(@Param("type") ConfigEnum type, @Param("s") String selector);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Config5.java | config-magic/src/test/java/org/skife/config/Config5.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public interface Config5 {
@Config("foo")
String getFoo();
@Config("bar")
int getBar();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestCoercion.java | config-magic/src/test/java/org/skife/config/TestCoercion.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.net.URI;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.hamcrest.CoreMatchers.is;
@Category(ConfigMagicTests.class)
public class TestCoercion {
private AugmentedConfigurationObjectFactory c = null;
@Before
public void setUp() {
this.c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("the-url", "http://github.org/brianm/config-magic");
}});
}
@After
public void tearDown() {
this.c = null;
}
@Test(expected = IllegalStateException.class)
public void testBadConfig() {
c.build(WibbleConfig.class);
}
@Test
public void testGoodConfig() {
final CoercionConfig cc = c.build(CoercionConfig.class);
Assert.assertThat(cc.getURI(), is(URI.create("http://github.org/brianm/config-magic")));
}
@Test
public void testEmptyURI() {
final EmptyUriConfig euc1 = new EmptyUriConfig() {};
Assert.assertNull(euc1.getTheUri());
final EmptyUriConfig euc2 = c.build(EmptyUriConfig.class);
Assert.assertNull(euc2.getTheUri());
}
@Test
public void testNullDouble() {
final NullDoubleConfig ndc1 = new NullDoubleConfig() {};
Assert.assertNull(ndc1.getTheNumber());
final NullDoubleConfig ndc2 = c.build(NullDoubleConfig.class);
Assert.assertNull(ndc2.getTheNumber());
}
public abstract static class EmptyUriConfig {
@Config("the-uri")
@DefaultNull
public URI getTheUri() {
return null;
}
}
public abstract static class NullDoubleConfig {
@Config("the-number")
@DefaultNull
public Double getTheNumber() {
return null;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestVariousPropertyTypes.java | config-magic/src/test/java/org/skife/config/TestVariousPropertyTypes.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Collections;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestVariousPropertyTypes {
private AugmentedConfigurationObjectFactory c = null;
private StrangeConfig sc = null;
@Before
public void setUp() {
final Properties p = new Properties();
p.setProperty("single-property", "single-property-value");
p.setProperty("multi.first.property", "multi-first-value");
p.setProperty("double.second.property", "double-second-value");
p.setProperty("test.value.property", "test-value-value");
p.setProperty("test.default.property", "test-default-value");
c = new AugmentedConfigurationObjectFactory(p);
sc = c.buildWithReplacements(StrangeConfig.class, Collections.singletonMap("key", "value"));
}
@Test
public void testWithDefault() {
Assert.assertEquals("default-is-set", sc.getHasDefault());
}
@Test
public void testWithDefaultNull() {
Assert.assertNull(sc.getHasDefaultNull());
}
@Test
public void testCallMethod() {
Assert.assertEquals("called getCalledMethod()", sc.getCalledMethod());
}
@Test
public void testMultiProperty() {
Assert.assertEquals("multi-first-value", sc.getMultiProperty());
}
@Test
public void testDoubleProperty() {
Assert.assertEquals("double-second-value", sc.getDoubleProperty());
}
@Test
public void testKeyedProperty() {
Assert.assertEquals("test-value-value", sc.getKeyedProperty());
}
public abstract static class StrangeConfig {
@Config("has-default")
@Default("default-is-set")
public String getHasDefault() {
return "called getHasDefault()";
}
@Config("has-default-null")
@DefaultNull
public String getHasDefaultNull() {
return "called getHasDefault()";
}
@Config("get-called-method")
public String getCalledMethod() {
return "called getCalledMethod()";
}
@Config("single.property")
public String getSingleProperty() {
return "called getSingleProperty()";
}
@Config({"multi.first.property", "multi.second.property"})
public String getMultiProperty() {
return "called getMultiProperty()";
}
@Config({"double.first.property", "double.second.property"})
public String getDoubleProperty() {
return "called getDoubleProperty()";
}
@Config({"test.${key}.property", "test.default.property"})
public String getKeyedProperty() {
return "called getKeyedProperty()";
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestArrays.java | config-magic/src/test/java/org/skife/config/TestArrays.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestArrays {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClassDefault() {
final EmptyClass ec = cof.build(EmptyClass.class);
Assert.assertArrayEquals(new String[]{"one", "three", "two"}, ec.getValue());
}
@Test
public void testAbstractClassDefault() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertArrayEquals(new TestEnum[]{TestEnum.TWO, TestEnum.ONE}, ec.getValue());
}
@Test
public void testInterface() {
final EmptyInterface ec = cof.build(EmptyInterface.class);
Assert.assertArrayEquals(new float[]{1.0f, 2.0f}, ec.getValue(), 0.0f);
}
@Test
public void testClassDefaultNull() {
final EmptyClassDefaultNull ec = cof.build(EmptyClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testAbstractClassDefaultNull() {
final EmptyAbstractClassDefaultNull ec = cof.build(EmptyAbstractClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterfaceDefaultNull() {
final EmptyInterfaceDefaultNull ec = cof.build(EmptyInterfaceDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterfaceDefaultEmptyString() {
final EmptyInterfaceEmptyString ec = cof.build(EmptyInterfaceEmptyString.class);
Assert.assertArrayEquals(new int[0], ec.getValue());
}
@Test
public void testDifferentSeparator() {
final DifferentSeparator ec = cof.build(DifferentSeparator.class);
Assert.assertArrayEquals(new float[]{1.0f, 2.0f}, ec.getValue(), 0.0f);
}
public enum TestEnum {
ONE,
TWO,
THREE
}
public interface EmptyInterface {
@Config("value")
@Default("1.0, 2.0")
float[] getValue();
}
public interface EmptyInterfaceDefaultNull {
@Config("value")
@DefaultNull
TestEnum[] getValue();
}
public interface EmptyInterfaceEmptyString {
@Config("value")
@Default("")
int[] getValue();
}
public interface DifferentSeparator {
@Config("value")
@Separator("\\s*;\\s*")
@Default("1.0 ; 2.0")
float[] getValue();
}
public static class EmptyClass {
@Config("value")
@Default("one, three, two")
public String[] getValue() {
return null;
}
}
public abstract static class EmptyAbstractClass {
@Config("value")
@Default("TWO, ONE")
public abstract TestEnum[] getValue();
}
public static class EmptyClassDefaultNull {
@Config("value")
@DefaultNull
public int[] getValue() {
return null;
}
}
public abstract static class EmptyAbstractClassDefaultNull {
@Config("value")
@DefaultNull
public String[] getValue() {
return null;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestEnums.java | config-magic/src/test/java/org/skife/config/TestEnums.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestEnums {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClassDefault() {
final EmptyClass ec = cof.build(EmptyClass.class);
Assert.assertEquals(TestEnum.ONE, ec.getValue());
}
@Test
public void testAbstractClassDefault() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertEquals(TestEnum.TWO, ec.getValue());
}
@Test
public void testInterface() {
final EmptyInterface ec = cof.build(EmptyInterface.class);
Assert.assertEquals(TestEnum.THREE, ec.getValue());
}
@Test
public void testClassDefaultNull() {
final EmptyClassDefaultNull ec = cof.build(EmptyClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testAbstractClassDefaultNull() {
final EmptyAbstractClassDefaultNull ec = cof.build(EmptyAbstractClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterfaceDefaultNull() {
final EmptyInterfaceDefaultNull ec = cof.build(EmptyInterfaceDefaultNull.class);
Assert.assertNull(ec.getValue());
}
public enum TestEnum {
ONE,
TWO,
THREE
}
public interface EmptyInterface {
@Config("value")
@Default("THREE")
TestEnum getValue();
}
public interface EmptyInterfaceDefaultNull {
@Config("value")
@DefaultNull
TestEnum getValue();
}
public static class EmptyClass {
@Config("value")
@Default("ONE")
public TestEnum getValue() {
return TestEnum.ONE;
}
}
public abstract static class EmptyAbstractClass {
@Config("value")
@Default("TWO")
public abstract TestEnum getValue();
}
public static class EmptyClassDefaultNull {
@Config("value")
@DefaultNull
public TestEnum getValue() {
return TestEnum.THREE;
}
}
public abstract static class EmptyAbstractClassDefaultNull {
@Config("value")
@DefaultNull
public TestEnum getValue() {
return null;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestEmptyValue.java | config-magic/src/test/java/org/skife/config/TestEmptyValue.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestEmptyValue {
private AugmentedConfigurationObjectFactory cof = null;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test(expected = IllegalArgumentException.class)
public void testClass() {
cof.build(EmptyClass.class);
}
@Test(expected = IllegalArgumentException.class)
public void testInterface() {
cof.build(EmptyInterface.class);
}
@Test
public void testDefaultClass() {
final EmptyDefaultClass ec = cof.build(EmptyDefaultClass.class);
Assert.assertEquals("default-value", ec.getValue());
}
@Test
public void testAbstractDefaultClass() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertEquals("default-value", ec.getValue());
}
public interface EmptyInterface {
@Config("value")
String getValue();
}
public abstract static class EmptyClass {
@Config("value")
public abstract String getValue();
}
public abstract static class EmptyAbstractClass {
@Config("value")
public String getValue() {
return "default-value";
}
}
public static class EmptyDefaultClass {
@Config("value")
public String getValue() {
return "default-value";
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestCollections.java | config-magic/src/test/java/org/skife/config/TestCollections.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestCollections {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testClassWithListDefault() {
final EmptyClassList ec = cof.build(EmptyClassList.class);
Assert.assertEquals(Arrays.asList("one", "three", "two"), ec.getValue());
}
@Test
public void testClassWithCollectionDefault() {
final EmptyClassCollection ec = cof.build(EmptyClassCollection.class);
Assert.assertEquals(Arrays.asList("one", "three", "two"), ec.getValue());
}
@Test
public void testAbstractClassDefault() {
final EmptyAbstractClass ec = cof.build(EmptyAbstractClass.class);
Assert.assertEquals(new HashSet<TestEnum>(Arrays.asList(TestEnum.TWO, TestEnum.ONE)), ec.getValue());
}
@Test
public void testInterface() {
final EmptyInterface ec = cof.build(EmptyInterface.class);
Assert.assertEquals(new LinkedHashSet<String>(Arrays.asList("one", "two")), ec.getValue());
}
@Test
public void testClassDefaultNull() {
final EmptyClassDefaultNull ec = cof.build(EmptyClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testAbstractClassDefaultNull() {
final EmptyAbstractClassDefaultNull ec = cof.build(EmptyAbstractClassDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterfaceDefaultNull() {
final EmptyInterfaceDefaultNull ec = cof.build(EmptyInterfaceDefaultNull.class);
Assert.assertNull(ec.getValue());
}
@Test
public void testInterfaceDefaultEmptyString() {
final EmptyInterfaceEmptyString ec = cof.build(EmptyInterfaceEmptyString.class);
Assert.assertEquals(Collections.emptyList(), ec.getValue());
}
@Test
public void testDifferentSeparator() {
final DifferentSeparator ec = cof.build(DifferentSeparator.class);
Assert.assertEquals(new HashSet<TestEnum>(Arrays.asList(TestEnum.TWO, TestEnum.ONE)), ec.getValue());
}
public enum TestEnum {
ONE,
TWO,
THREE
}
public interface EmptyInterface {
@Config("value")
@Default("one, two")
LinkedHashSet<String> getValue();
}
public interface EmptyInterfaceDefaultNull {
@Config("value")
@DefaultNull
List<TestEnum> getValue();
}
public interface EmptyInterfaceEmptyString {
@Config("value")
@Default("")
List<TestEnum> getValue();
}
public interface DifferentSeparator {
@Config("value")
@Separator("\\s*!\\s*")
@Default("TWO ! ONE")
Set<TestEnum> getValue();
}
public static class EmptyClassList {
@Config("value")
@Default("one, three, two")
public List<String> getValue() {
return Collections.emptyList();
}
}
public static class EmptyClassCollection {
@Config("value")
@Default("one, three, two")
public Collection<String> getValue() {
return Collections.emptyList();
}
}
public abstract static class EmptyAbstractClass {
@Config("value")
@Default("TWO, ONE")
public abstract Set<TestEnum> getValue();
}
public static class EmptyClassDefaultNull {
@Config("value")
@DefaultNull
public List<Float> getValue() {
return null;
}
}
public abstract static class EmptyAbstractClassDefaultNull {
@Config("value")
@DefaultNull
public Set<String> getValue() {
return null;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestDefaultCoercibles.java | config-magic/src/test/java/org/skife/config/TestDefaultCoercibles.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@Category(ConfigMagicTests.class)
public class TestDefaultCoercibles {
@Test
public void testValueOfCoercible1() {
final Coercer<?> c = DefaultCoercibles.VALUE_OF_COERCIBLE.accept(Date.class);
Assert.assertThat(c, is(notNullValue()));
final Object result = c.coerce("2010-11-21");
Assert.assertEquals(Date.class, result.getClass());
Assert.assertThat(result, equalTo(Date.valueOf("2010-11-21")));
}
@Test
public void testValueOfCoercible2() {
final Coercer<?> c = DefaultCoercibles.VALUE_OF_COERCIBLE.accept(Long.class);
Assert.assertThat(c, is(notNullValue()));
final Object result = c.coerce("4815162342");
Assert.assertEquals(Long.class, result.getClass());
Assert.assertThat(result, is(4815162342L));
}
@Test
public void testStringCtor1() throws MalformedURLException {
final Coercer<?> c = DefaultCoercibles.STRING_CTOR_COERCIBLE.accept(URL.class);
Assert.assertThat(c, is(notNullValue()));
final Object result = c.coerce("http://www.cnn.com/");
Assert.assertEquals(URL.class, result.getClass());
Assert.assertThat(result, equalTo(new URL("http://www.cnn.com/")));
}
@Test
public void testStringCtor2() {
final Coercer<?> c = DefaultCoercibles.STRING_CTOR_COERCIBLE.accept(StringBuilder.class);
Assert.assertThat(c, is(notNullValue()));
final Object result = c.coerce("Ich bin zwei Oeltanks.");
Assert.assertEquals(StringBuilder.class, result.getClass());
Assert.assertThat(result.toString(), is("Ich bin zwei Oeltanks."));
}
@Test
public void testObjectCtor1() {
final Coercer<?> c = DefaultCoercibles.OBJECT_CTOR_COERCIBLE.accept(DateTime.class);
Assert.assertThat(c, is(notNullValue()));
final Object result = c.coerce("2010-11-22T01:58Z");
Assert.assertEquals(DateTime.class, result.getClass());
Assert.assertThat(result, equalTo(new DateTime("2010-11-22T01:58Z")));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestCaseInsensitiveEnumCoercible.java | config-magic/src/test/java/org/skife/config/TestCaseInsensitiveEnumCoercible.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@Category(ConfigMagicTests.class)
public class TestCaseInsensitiveEnumCoercible {
@Test
public void testHappyPath() throws Exception {
final AugmentedConfigurationObjectFactory cof = new AugmentedConfigurationObjectFactory(Props.of("creamer", "half_and_half"));
final Coffee coffee = cof.build(Coffee.class);
assertThat(coffee.getCreamer(), equalTo(Creamer.HALF_AND_HALF));
}
@Test(expected = IllegalStateException.class)
public void testNoMatch() throws Exception {
final AugmentedConfigurationObjectFactory cof = new AugmentedConfigurationObjectFactory(Props.of("creamer", "goat_milk"));
final Coffee coffee = cof.build(Coffee.class);
fail("should have raised an illegal state exception");
}
@Test(expected = IllegalArgumentException.class)
public void testExactMatch() throws Exception {
final ConfigurationObjectFactory cof = new AugmentedConfigurationObjectFactory(Props.of("creamer", "whole_milk"));
cof.addCoercible(new ExactMatchEnumCoercible());
final Coffee coffee = cof.build(Coffee.class);
fail("should have raised an exception");
}
public enum Creamer {
HEAVY_CREAM, HALF_AND_HALF, WHOLE_MILK, SKIM_MILK, GROSS_WHITE_POWDER
}
public abstract static class Coffee {
@Config("creamer")
public abstract Creamer getCreamer();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Config2.java | config-magic/src/test/java/org/skife/config/Config2.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
class Config2 {
public int invocationCount = 0;
public int getInvocationCount() {
return invocationCount;
}
// optional w/ default value
@Config("option")
public String getOption() {
++invocationCount;
return "default";
}
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/ReplacementConfig1.java | config-magic/src/test/java/org/skife/config/ReplacementConfig1.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
public interface ReplacementConfig1 {
@Config("option.${type}")
@Default("default")
String getStringOption();
@Config("another-option.${type}.${s}")
@Default("default")
String getStringOption2Types();
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestDataAmount.java | config-magic/src/test/java/org/skife/config/TestDataAmount.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestDataAmount {
private AugmentedConfigurationObjectFactory cof;
@Before
public void setUp() {
cof = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
cof = null;
}
@Test
public void testKiloBytes() {
DataAmount amount = new DataAmount("20kB");
Assert.assertEquals(DataAmountUnit.KILOBYTE, amount.getUnit());
Assert.assertEquals(20L * 1000, amount.getNumberOfBytes());
// and space allowed now as well
amount = new DataAmount("20 kB");
Assert.assertEquals(DataAmountUnit.KILOBYTE, amount.getUnit());
Assert.assertEquals(20L * 1000, amount.getNumberOfBytes());
final ClassWithKilobytes ec = cof.build(ClassWithKilobytes.class);
Assert.assertEquals(DataAmountUnit.KILOBYTE, ec.getValue().getUnit());
Assert.assertEquals(10L * 1000, ec.getValue().getNumberOfBytes());
}
@Test
public void testRawBytes() {
DataAmount amt = new DataAmount("1024");
Assert.assertEquals(DataAmountUnit.BYTE, amt.getUnit());
Assert.assertEquals(1024L, amt.getNumberOfBytes());
amt = new DataAmount(2000);
Assert.assertEquals(DataAmountUnit.BYTE, amt.getUnit());
Assert.assertEquals(2000L, amt.getNumberOfBytes());
}
public abstract static class ClassWithKilobytes {
@Config("value")
@Default("10kB")
public abstract DataAmount getValue();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Props.java | config-magic/src/test/java/org/skife/config/Props.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
public class Props {
public static Properties of(final String key, final String value) {
final Properties props = new Properties();
props.put(key, value);
return props;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestCustomCoercion.java | config-magic/src/test/java/org/skife/config/TestCustomCoercion.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
@Category(ConfigMagicTests.class)
public class TestCustomCoercion {
@Test(expected = IllegalStateException.class)
public void testNoConverterConfig() {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("the-url", "http://github.org/brianm/config-magic");
}});
c.build(WibbleConfig.class);
}
@Test
public void testWithConverterConfig() {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("the-url", "http://github.org/brianm/config-magic");
}});
c.addCoercible(new WibbleCoercible());
final WibbleConfig wc = c.build(WibbleConfig.class);
Assert.assertThat(wc, is(notNullValue()));
final Wibble w = wc.getWibble();
Assert.assertThat(w, is(notNullValue()));
Assert.assertThat(w.getURL(), equalTo("http://github.org/brianm/config-magic"));
}
private static class WibbleCoercible implements Coercible<Wibble> {
public Coercer<Wibble> accept(final Class<?> clazz) {
if (Wibble.class.equals(clazz)) {
return new Coercer<Wibble>() {
public Wibble coerce(final String value) {
final Wibble w = new Wibble();
w.setURL(value);
return w;
}
};
}
return null;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestBadConfig.java | config-magic/src/test/java/org/skife/config/TestBadConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestBadConfig {
AugmentedConfigurationObjectFactory c = null;
@Before
public void setUp() {
this.c = new AugmentedConfigurationObjectFactory(new Properties());
}
@After
public void tearDown() {
this.c = null;
}
@Test(expected = IllegalArgumentException.class)
public void testBadConfig() {
final BadConfig bc = c.build(BadConfig.class);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/BadConfig.java | config-magic/src/test/java/org/skife/config/BadConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface BadConfig {
@Config({})
String getBadOption();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestConfigurationObjectFactory.java | config-magic/src/test/java/org/skife/config/TestConfigurationObjectFactory.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
*
*/
@Category(ConfigMagicTests.class)
public class TestConfigurationObjectFactory {
@Test
public void testMultipleReplacements() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("another-option.a.1", "A1");
setProperty("another-option.a.2", "A2");
setProperty("another-option.b.1", "B1");
setProperty("another-option.b.2", "B2");
}});
ReplacementConfig1 r;
final Map<String, String> replacementsMap = new HashMap<String, String>();
replacementsMap.put("type", "a");
replacementsMap.put("s", "1");
r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption2Types(), "A1");
replacementsMap.put("type", "a");
replacementsMap.put("s", "2");
r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption2Types(), "A2");
replacementsMap.put("type", "b");
replacementsMap.put("s", "1");
r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption2Types(), "B1");
replacementsMap.put("type", "b");
replacementsMap.put("s", "2");
r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption2Types(), "B2");
}
@Test
public void testReplacement() throws Exception {
final Map<String, String> replacementsMap = new HashMap<String, String>();
replacementsMap.put("type", "first");
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("option.first", "1st");
setProperty("option.second", "2nd");
}});
ReplacementConfig1 r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption(), "1st");
replacementsMap.put("type", "second");
r = c.buildWithReplacements(ReplacementConfig1.class, replacementsMap);
assertEquals(r.getStringOption(), "2nd");
}
@Test
public void testFoo() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("hello", "world");
setProperty("theValue", "value");
}});
final Thing t = c.build(Thing.class);
assertEquals(t.getName(), "world");
}
@Test
public void testEnum() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("option.one", "1");
setProperty("option.two", "2");
}});
final EnumeratedConfig1 t = c.build(EnumeratedConfig1.class);
assertEquals(t.getStringOption(ConfigEnum.ONE), "1");
assertEquals(t.getStringOption(ConfigEnum.TWO), "2");
assertEquals(t.getStringOption(ConfigEnum.THREE), "default");
}
@Test
public void testMultiParameters() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("another-option.one.a", "1-x");
setProperty("another-option.two.b", "2-y");
}});
final EnumeratedConfig1 t = c.build(EnumeratedConfig1.class);
assertEquals(t.getStringOption2Types(ConfigEnum.ONE, "a"), "1-x");
assertEquals(t.getStringOption2Types(ConfigEnum.TWO, "b"), "2-y");
assertEquals(t.getStringOption2Types(ConfigEnum.ONE, "dummy"), "default");
}
@Test
public void testDefaultValue() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties());
final Thing t = c.build(Thing.class);
assertEquals(t.getName(), "woof");
}
@Test
public void testDefaultViaImpl() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties());
final Config2 config = c.build(Config2.class);
assertEquals(config.getOption(), "default");
}
@Test
public void testProvidedOverridesDefault() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("option", "provided");
}});
final Config2 config = c.build(Config2.class);
assertEquals(config.getOption(), "provided");
}
@Test
public void testMissingDefault() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties());
try {
c.build(Config3.class);
fail("Expected exception due to missing value");
} catch (final Throwable e) {
}
}
@Test
public void testDetectsAbstractMethod() throws Exception {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties());
try {
c.build(Config4.class);
fail("Expected exception due to abstract method without @Config annotation");
} catch (final AbstractMethodError e) {
}
}
@Test
public void testTypes() {
final ConfigurationObjectFactory c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("stringOption", "a string");
setProperty("booleanOption", "true");
setProperty("boxedBooleanOption", "true");
setProperty("byteOption", Byte.toString(Byte.MAX_VALUE));
setProperty("boxedByteOption", Byte.toString(Byte.MAX_VALUE));
setProperty("shortOption", Short.toString(Short.MAX_VALUE));
setProperty("boxedShortOption", Short.toString(Short.MAX_VALUE));
setProperty("integerOption", Integer.toString(Integer.MAX_VALUE));
setProperty("boxedIntegerOption", Integer.toString(Integer.MAX_VALUE));
setProperty("longOption", Long.toString(Long.MAX_VALUE));
setProperty("boxedLongOption", Long.toString(Long.MAX_VALUE));
setProperty("floatOption", Float.toString(Float.MAX_VALUE));
setProperty("boxedFloatOption", Float.toString(Float.MAX_VALUE));
setProperty("doubleOption", Double.toString(Double.MAX_VALUE));
setProperty("boxedDoubleOption", Double.toString(Double.MAX_VALUE));
}});
final Config1 config = c.build(Config1.class);
assertEquals("a string", config.getStringOption());
assertEquals(true, config.getBooleanOption());
assertEquals(Boolean.TRUE, config.getBoxedBooleanOption());
assertEquals(Byte.MAX_VALUE, config.getByteOption());
assertEquals(Byte.valueOf(Byte.MAX_VALUE), config.getBoxedByteOption());
assertEquals(Short.MAX_VALUE, config.getShortOption());
assertEquals(Short.valueOf(Short.MAX_VALUE), config.getBoxedShortOption());
assertEquals(Integer.MAX_VALUE, config.getIntegerOption());
assertEquals(Integer.valueOf(Integer.MAX_VALUE), config.getBoxedIntegerOption());
assertEquals(Long.MAX_VALUE, config.getLongOption());
assertEquals(Long.valueOf(Long.MAX_VALUE), config.getBoxedLongOption());
assertEquals(Float.MAX_VALUE, config.getFloatOption(), 0);
assertEquals(Float.valueOf(Float.MAX_VALUE), config.getBoxedFloatOption());
assertEquals(Double.MAX_VALUE, config.getDoubleOption(), 0);
assertEquals(Double.valueOf(Double.MAX_VALUE), config.getBoxedDoubleOption());
}
private interface ThingParam {
@Config("${thing}.hello")
String getHello();
@Config("${thing}.value")
String getValue();
}
public abstract static class Thing {
@Config("hello")
@Default("woof")
public abstract String getName();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestMultiConfig.java | config-magic/src/test/java/org/skife/config/TestMultiConfig.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Collections;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.hamcrest.CoreMatchers.is;
@Category(ConfigMagicTests.class)
public class TestMultiConfig {
AugmentedConfigurationObjectFactory c = null;
@Before
public void setUp() {
this.c = new AugmentedConfigurationObjectFactory(new Properties() {{
setProperty("singleOption", "the-single-value");
setProperty("multiOption1", "the-multi-option1-value");
setProperty("multiOption2", "the-multi-option2-value");
setProperty("fooExtOption", "the-fooExt-option-value");
setProperty("barExtOption", "the-barExt-option-value");
setProperty("defaultOption", "the-default-option-value");
}});
}
@After
public void tearDown() {
this.c = null;
}
@Test
public void testSimple() {
final MultiConfig mc = c.build(MultiConfig.class);
Assert.assertThat(mc.getSingleOption(), is("the-single-value"));
}
@Test
public void testSimple2() {
final MultiConfig mc = c.build(MultiConfig.class);
Assert.assertThat(mc.getSingleOption2(), is("the-single-value"));
}
@Test
public void testMultiOption1() {
final MultiConfig mc = c.build(MultiConfig.class);
Assert.assertThat(mc.getMultiOption1(), is("the-multi-option1-value"));
}
@Test
public void testMultiOption2() {
final MultiConfig mc = c.build(MultiConfig.class);
Assert.assertThat(mc.getMultiOption2(), is("the-multi-option2-value"));
}
@Test
public void testMultiDefault() {
final MultiConfig mc = c.build(MultiConfig.class);
Assert.assertThat(mc.getMultiDefault(), is("theDefault"));
}
@Test
public void testMultiReplace1() {
final MultiConfig mc = c.buildWithReplacements(MultiConfig.class, Collections.singletonMap("key", "foo"));
Assert.assertThat(mc.getReplaceOption(), is("the-fooExt-option-value"));
}
@Test
public void testMultiReplace2() {
final MultiConfig mc = c.buildWithReplacements(MultiConfig.class, Collections.singletonMap("key", "bar"));
Assert.assertThat(mc.getReplaceOption(), is("the-barExt-option-value"));
}
@Test
public void testMultiReplaceDefault() {
final MultiConfig mc = c.buildWithReplacements(MultiConfig.class, Collections.singletonMap("key", "baz"));
Assert.assertThat(mc.getReplaceOption(), is("the-default-option-value"));
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/TestNoFinal.java | config-magic/src/test/java/org/skife/config/TestNoFinal.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ConfigMagicTests.class)
public class TestNoFinal {
@Test(expected = IllegalArgumentException.class)
public void testExplodeOnFinal() {
final ConfigurationObjectFactory cof = new AugmentedConfigurationObjectFactory(new Properties());
cof.build(EmptyClass.class);
}
public static final class EmptyClass {
@Config("value")
public String getValue() {
return "default-value";
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/test/java/org/skife/config/Config3.java | config-magic/src/test/java/org/skife/config/Config3.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
interface Config3 {
// required
@Config("option")
String getOption();
String getOption2();
} | java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/ExactMatchEnumCoercible.java | config-magic/src/main/java/org/skife/config/ExactMatchEnumCoercible.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.reflect.Method;
public class ExactMatchEnumCoercible implements Coercible<Object> {
public Coercer<Object> accept(final Class<?> clazz) {
if (!clazz.isEnum()) {
return null;
}
try {
final Method m = clazz.getMethod("valueOf", String.class);
return new Coercer<Object>() {
public Object coerce(final String value) {
if (value == null) {
return null;
}
try {
return m.invoke(null, value);
} catch (final Exception e) {
throw DefaultCoercibles.convertException(e);
}
}
};
} catch (final NoSuchMethodException e) {
throw new IllegalStateException("<EnumType>.valueOf(String) missing! World broken!", e);
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/CaseInsensitiveEnumCoercible.java | config-magic/src/main/java/org/skife/config/CaseInsensitiveEnumCoercible.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Arrays;
/**
* Do case insensitive string comparisons for determination of enum value matches.
*/
public class CaseInsensitiveEnumCoercible implements Coercible<Object> {
public Coercer<Object> accept(final Class<?> clazz) {
if (!clazz.isEnum()) {
return null;
}
final Enum<?>[] values;
try {
values = (Enum[]) clazz.getMethod("values").invoke(null);
} catch (final Exception e) {
throw new IllegalStateException("World seems to be broken, unable to access <EnumType>.values() static method", e);
}
return new Coercer<Object>() {
public Object coerce(final String value) {
if (value == null) {
return null;
}
for (final Object o : values) {
if (value.equalsIgnoreCase(o.toString())) {
return o;
}
}
throw new IllegalStateException("No enum value of " + Arrays.toString(values) + " matches [" + value + "]");
}
};
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/DefaultNull.java | config-magic/src/main/java/org/skife/config/DefaultNull.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Allows assigning "null" as a default value for a property.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DefaultNull {
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Coercer.java | config-magic/src/main/java/org/skife/config/Coercer.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
/**
* Coerces a given string value to a type.
*/
public interface Coercer<T> {
T coerce(String value);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Default.java | config-magic/src/main/java/org/skife/config/Default.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Default {
String value();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/ConfigReplacements.java | config-magic/src/main/java/org/skife/config/ConfigReplacements.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* If a configuration bean is created with mapped replacement values via
* {@link AugmentedConfigurationObjectFactory#buildWithReplacements(Class, java.util.Map)},
* this annotation designates a method which should present the provided Map.
* The map may not be changed and is not necessarily the same instance as the original.
* If a key is provided, the return is instead the value for that key.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ConfigReplacements {
String DEFAULT_VALUE = "__%%%noValue%%%__";
/**
* The key to look up in the replacement map, if any.
*/
String value() default DEFAULT_VALUE;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Config.java | config-magic/src/main/java/org/skife/config/Config.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Config {
String[] value();
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/SimplePropertyConfigSource.java | config-magic/src/main/java/org/skife/config/SimplePropertyConfigSource.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Properties;
public class SimplePropertyConfigSource implements ConfigSource {
private final Properties props;
public SimplePropertyConfigSource(final Properties props) {
this.props = new Properties(props);
}
public String getString(final String propertyName) {
return props.getProperty(propertyName);
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/AugmentedConfigurationObjectFactory.java | config-magic/src/main/java/org/skife/config/AugmentedConfigurationObjectFactory.java | /*
* Copyright 2020-2025 Equinix, Inc
* Copyright 2014-2025 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Augmented version of {@link ConfigurationObjectFactory} that collects resolved config properties
* at runtime and registers them in {@link RuntimeConfigRegistry}.
*/
public class AugmentedConfigurationObjectFactory extends ConfigurationObjectFactory {
private static final Logger log = LoggerFactory.getLogger(AugmentedConfigurationObjectFactory.class);
public AugmentedConfigurationObjectFactory(final Properties props) {
super(new SimplePropertyConfigSource(props));
}
public AugmentedConfigurationObjectFactory(final ConfigSource configSource) {
super(configSource);
}
@Override
public <T> T build(final Class<T> configClass) {
final T instance = super.build(configClass);
collectConfigValues(configClass, instance, null);
return instance;
}
@Override
public <T> T buildWithReplacements(final Class<T> configClass, final Map<String, String> mappedReplacements) {
final T instance = super.buildWithReplacements(configClass, mappedReplacements);
collectConfigValues(configClass, instance, mappedReplacements);
return instance;
}
private <T> void collectConfigValues(final Class<T> configClass,
final T instance,
final Map<String, String> mappedReplacements) {
final String configSource = configClass.getSimpleName();
for (final Method method : configClass.getMethods()) {
final Config configAnnotation = method.getAnnotation(Config.class);
if (configAnnotation != null && method.getParameterCount() == 0) {
try {
final Object value = method.invoke(instance);
final String[] keys = configAnnotation.value();
for (String key : keys) {
if (mappedReplacements != null) {
key = applyReplacements(key, mappedReplacements);
}
RuntimeConfigRegistry.putWithSource(configSource, key,
value instanceof Collection
? ((Collection<?>) value).stream()
.filter(Objects::nonNull)
.map(String::valueOf)
.collect(Collectors.joining(","))
: value);
}
} catch (final IllegalAccessException | InvocationTargetException e) {
log.warn("Failed to resolve config method: {}", method.getName(), e);
}
} else if (configAnnotation != null) {
log.debug("Skipping config method {} due to parameters", method.getName());
}
}
}
private String applyReplacements(String propertyName, final Map<String, String> mappedReplacements) {
for (final Map.Entry<String, String> entry : mappedReplacements.entrySet()) {
final String token = "${" + entry.getKey() + "}";
final String replacement = entry.getValue();
propertyName = propertyName.replace(token, replacement);
}
return propertyName;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Bully.java | config-magic/src/main/java/org/skife/config/Bully.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
class Bully {
/**
* All explicit type conversions that config magic knows about. Every new bully will know about those.
*/
private static final List<Coercible<?>> TYPE_COERCIBLES;
/**
* Catchall converters. These will be run if no specific type coercer was found.
*/
private static final List<Coercible<?>> DEFAULT_COERCIBLES;
static {
final List<Coercible<?>> typeCoercibles = new ArrayList<Coercible<?>>();
final List<Coercible<?>> defaultCoercibles = new ArrayList<Coercible<?>>();
typeCoercibles.add(DefaultCoercibles.BOOLEAN_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.BYTE_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.SHORT_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.INTEGER_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.LONG_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.FLOAT_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.DOUBLE_COERCIBLE);
typeCoercibles.add(DefaultCoercibles.STRING_COERCIBLE);
// Look Brian, now it groks URIs. ;-)
typeCoercibles.add(DefaultCoercibles.URI_COERCIBLE);
defaultCoercibles.add(DefaultCoercibles.CASE_INSENSITIVE_ENUM_COERCIBLE);
defaultCoercibles.add(DefaultCoercibles.VALUE_OF_COERCIBLE);
defaultCoercibles.add(DefaultCoercibles.STRING_CTOR_COERCIBLE);
defaultCoercibles.add(DefaultCoercibles.OBJECT_CTOR_COERCIBLE);
TYPE_COERCIBLES = Collections.unmodifiableList(typeCoercibles);
DEFAULT_COERCIBLES = Collections.unmodifiableList(defaultCoercibles);
}
/**
* The instance specific mappings from a given type to its coercer. This needs to be two-level because the
* catchall converters will generate specific instances of their coercers based on the type.
*/
private final Map<Class<?>, Coercer<?>> mappings = new HashMap<Class<?>, Coercer<?>>();
/**
* All the coercibles that this instance knows about. This list can be extended with user mappings.
*/
private final List<Coercible<?>> coercibles = new ArrayList<Coercible<?>>();
public Bully() {
coercibles.addAll(TYPE_COERCIBLES);
}
/**
* Adds a new Coercible to the list of known coercibles. This also resets the current mappings in this bully.
*/
public void addCoercible(final Coercible<?> coercible) {
coercibles.add(coercible);
mappings.clear();
}
public synchronized Object coerce(final Type type, final String value, final Separator separator) {
if (type instanceof Class) {
final Class<?> clazz = (Class<?>) type;
if (clazz.isArray()) {
return coerceArray(clazz.getComponentType(), value, separator);
} else if (Class.class.equals(clazz)) {
return coerceClass(type, null, value);
} else {
return coerce(clazz, value);
}
} else if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) type;
final Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class<?>) {
final Type[] args = parameterizedType.getActualTypeArguments();
if (args != null && args.length == 1) {
if (args[0] instanceof Class<?>) {
return coerceCollection((Class<?>) rawType, (Class<?>) args[0], value, separator);
} else if (args[0] instanceof WildcardType) {
return coerceClass(type, (WildcardType) args[0], value);
}
}
}
}
throw new IllegalStateException(String.format("Don't know how to handle a '%s' type for value '%s'", type, value));
}
private boolean isAssignableFrom(final Type targetType, final Class<?> assignedClass) {
if (targetType instanceof Class) {
return ((Class<?>) targetType).isAssignableFrom(assignedClass);
} else if (targetType instanceof WildcardType) {
final WildcardType wildcardType = (WildcardType) targetType;
// Class<? extends Foo>
for (final Type upperBoundType : wildcardType.getUpperBounds()) {
if (!Object.class.equals(upperBoundType)) {
if ((upperBoundType instanceof Class<?>) && !((Class<?>) upperBoundType).isAssignableFrom(assignedClass)) {
return false;
}
}
}
}
return true;
}
private Class<?> coerceClass(final Type type, final WildcardType wildcardType, final String value) {
if (value == null) {
return null;
} else {
try {
final Class<?> clazz = Class.forName(value);
if (!isAssignableFrom(wildcardType, clazz)) {
throw new IllegalArgumentException("Specified class " + clazz + " is not compatible with required type " + type);
}
return clazz;
} catch (final Exception ex) {
throw new IllegalArgumentException(ex);
}
}
}
private Object coerceArray(final Class<?> elemType, final String value, final Separator separator) {
if (value == null) {
return null;
} else if (value.length() == 0) {
return Array.newInstance(elemType, 0);
} else {
final String[] tokens = value.split(separator == null ? Separator.DEFAULT : separator.value());
final Object targetArray = Array.newInstance(elemType, tokens.length);
for (int idx = 0; idx < tokens.length; idx++) {
Array.set(targetArray, idx, coerce(elemType, tokens[idx]));
}
return targetArray;
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private Object coerceCollection(final Class<?> containerType, final Class<?> elemType, final String value, final Separator separator) {
if (value == null) {
return null;
} else {
Collection result = null;
if (Set.class.equals(containerType)) {
result = new LinkedHashSet();
} else if (Collection.class.equals(containerType) || List.class.equals(containerType)) {
result = new ArrayList();
} else if (Collection.class.isAssignableFrom(containerType)) {
try {
final Constructor<?> ctor = containerType.getConstructor();
if (ctor != null) {
result = (Collection) ctor.newInstance();
}
} catch (final Exception ex) {
// handled below
}
}
if (result == null) {
throw new IllegalStateException(String.format("Don't know how to handle a '%s' container type for value '%s'", containerType, value));
}
if (value.length() > 0) {
for (final String token : value.split(separator == null ? Separator.DEFAULT : separator.value())) {
result.add(coerce(elemType, token));
}
}
return result;
}
}
private Object coerce(final Class<?> clazz, final String value) {
Coercer<?> coercer = getCoercerFor(coercibles, clazz);
if (coercer == null) {
coercer = getCoercerFor(DEFAULT_COERCIBLES, clazz);
if (coercer == null) {
throw new IllegalStateException(String.format("Don't know how to handle a '%s' type for value '%s'", clazz, value));
}
}
return coercer.coerce(value);
}
private Coercer<?> getCoercerFor(final List<Coercible<?>> coercibles, final Class<?> type) {
Coercer<?> typeCoercer = mappings.get(type);
if (typeCoercer == null) {
for (final Coercible<?> coercible : coercibles) {
final Coercer<?> coercer = coercible.accept(type);
if (coercer != null) {
mappings.put(type, coercer);
typeCoercer = coercer;
break;
}
}
}
return typeCoercer;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/DataAmount.java | config-magic/src/main/java/org/skife/config/DataAmount.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DataAmount {
private static final Pattern SPLIT = Pattern.compile("^(\\d+)\\s*([a-zA-Z]+)$");
private static final Pattern NUM_ONLY = Pattern.compile("^(\\d+)$");
private final long value;
private final DataAmountUnit unit;
private final long numBytes;
public DataAmount(final String spec) {
Matcher m = SPLIT.matcher(spec);
if (!m.matches()) {
// #7: allow undecorated unit to mean basic bytes
m = NUM_ONLY.matcher(spec);
if (!m.matches()) {
throw new IllegalArgumentException(String.format("%s is not a valid data amount", spec));
}
unit = DataAmountUnit.BYTE;
value = numBytes = Long.parseLong(spec);
} else {
final String number = m.group(1);
final String type = m.group(2);
this.value = Long.parseLong(number);
this.unit = DataAmountUnit.fromString(type);
this.numBytes = unit.getFactor() * value;
}
}
public DataAmount(final long value, final DataAmountUnit unit) {
this.value = value;
this.unit = unit;
this.numBytes = unit.getFactor() * value;
}
/**
* @since 0.15
*/
public DataAmount(final long rawBytes) {
value = numBytes = rawBytes;
unit = DataAmountUnit.BYTE;
}
public long getValue() {
return value;
}
public DataAmountUnit getUnit() {
return unit;
}
public long getNumberOfBytes() {
return numBytes;
}
public DataAmount convertTo(final DataAmountUnit newUnit) {
return new DataAmount(numBytes / newUnit.getFactor(), newUnit);
}
@Override
public String toString() {
return value + unit.getSymbol();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (numBytes ^ (numBytes >>> 32));
result = prime * result + unit.hashCode();
result = prime * result + (int) (value ^ (value >>> 32));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DataAmount other = (DataAmount) obj;
return numBytes == other.numBytes;
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Separator.java | config-magic/src/main/java/org/skife/config/Separator.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Separator {
String DEFAULT = "\\s*,\\s*";
String value() default DEFAULT;
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/Coercible.java | config-magic/src/main/java/org/skife/config/Coercible.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
/**
* Returns a Coercer to convert String values into
* the given type. The interface accepts Class<?> because
* the type can be {@link java.lang.Object}.
*/
public interface Coercible<T> {
Coercer<T> accept(Class<?> clazz);
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/ConfigurationObjectFactory.java | config-magic/src/main/java/org/skife/config/ConfigurationObjectFactory.java | /*
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.Nullable;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType.Builder;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.matcher.ElementMatchers;
class ConfigurationObjectFactory {
private static final Logger logger = LoggerFactory.getLogger(ConfigurationObjectFactory.class);
private final ConfigSource config;
private final Bully bully;
public ConfigurationObjectFactory(final Properties props) {
this(new SimplePropertyConfigSource(props));
}
public ConfigurationObjectFactory(final ConfigSource config) {
this.config = config;
this.bully = new Bully();
}
public void addCoercible(final Coercible<?> coercible) {
this.bully.addCoercible(coercible);
}
public <T> T buildWithReplacements(final Class<T> configClass, final Map<String, String> mappedReplacements) {
return internalBuild(configClass, mappedReplacements);
}
public <T> T build(final Class<T> configClass) {
return internalBuild(configClass, null);
}
private <T> T internalBuild(final Class<T> configClass, @Nullable final Map<String, String> mappedReplacements) {
Builder<T> bbBuilder = new ByteBuddy().subclass(configClass);
// Hook up the actual value interceptors.
for (final Method method : configClass.getMethods()) {
if (method.isAnnotationPresent(Config.class)) {
final Config annotation = method.getAnnotation(Config.class);
if (method.getParameterTypes().length > 0) {
if (mappedReplacements != null) {
throw new RuntimeException("Replacements are not supported for parameterized config methods");
}
bbBuilder = buildParameterized(bbBuilder, method, annotation);
} else {
bbBuilder = buildSimple(bbBuilder, method, annotation, mappedReplacements, null);
}
} else if (method.isAnnotationPresent(ConfigReplacements.class)) {
final ConfigReplacements annotation = method.getAnnotation(ConfigReplacements.class);
if (ConfigReplacements.DEFAULT_VALUE.equals(annotation.value())) {
final Map<String, String> fixedMap = mappedReplacements == null ?
Collections.<String, String>emptyMap() : Collections.unmodifiableMap(mappedReplacements);
bbBuilder = bbBuilder.method(ElementMatchers.is(method)).intercept(FixedValue.value(fixedMap));
} else {
bbBuilder = buildSimple(bbBuilder, method, null, mappedReplacements, annotation);
}
} else if (Modifier.isAbstract(method.getModifiers())) {
throw new AbstractMethodError(String.format("Method [%s] is abstract and lacks an @Config annotation",
method.toGenericString()));
}
}
final Class<?> loaded = bbBuilder.make()
.load(configClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
try {
return configClass.cast(loaded.getConstructor().newInstance());
} catch (final ReflectiveOperationException e) {
throw new AssertionError("Failed to instantiate proxy class for " + configClass.getName(), e);
}
}
private <T> Builder<T> buildSimple(final Builder<T> bbBuilder,
final Method method,
final Config annotation,
final Map<String, String> mappedReplacements,
final ConfigReplacements mapAnnotation) {
String[] propertyNames = new String[0];
String value = null;
// Annotation will be null for an @ConfigReplacements, in which case "value" will
// be preset and ready to be defaulted + bullied
if (annotation != null) {
propertyNames = annotation.value();
if (propertyNames.length == 0) {
throw new IllegalArgumentException("Method " +
method.toGenericString() +
" declares config annotation but no field name!");
}
for (String propertyName : propertyNames) {
if (mappedReplacements != null) {
propertyName = applyReplacements(propertyName, mappedReplacements);
}
value = config.getString(propertyName);
// First value found wins
if (value != null) {
logger.info("Assigning value [{}] for [{}] on [{}#{}()]",
value, propertyName, method.getDeclaringClass().getName(), method.getName());
break;
}
}
} else {
if (mapAnnotation == null) {
throw new IllegalStateException("Neither @Config nor @ConfigReplacements provided, this should not be possible!");
}
final String key = mapAnnotation.value();
value = mappedReplacements == null ? null : mappedReplacements.get(key);
if (value != null) {
logger.info("Assigning mappedReplacement value [{}] for [{}] on [{}#{}()]",
value, key, method.getDeclaringClass().getName(), method.getName());
}
}
final boolean hasDefault = method.isAnnotationPresent(Default.class);
final boolean hasDefaultNull = method.isAnnotationPresent(DefaultNull.class);
if (hasDefault && hasDefaultNull) {
throw new IllegalArgumentException(String.format("@Default and @DefaultNull present in [%s]", method.toGenericString()));
}
boolean useMethod = false;
//
// This is how the value logic works if no value has been set by the config:
//
// - if the @Default annotation is present, use its value.
// - if the @DefaultNull annotation is present, accept null as the value
// - otherwise, check whether the method is not abstract. If it is not, mark the callback that it should call the method and
// ignore the passed in value (which will be null)
// - if all else fails, throw an exception.
//
if (value == null) {
if (hasDefault) {
value = method.getAnnotation(Default.class).value();
logger.info("Assigning default value [{}] for {} on [{}#{}()]",
value, propertyNames, method.getDeclaringClass().getName(), method.getName());
} else if (hasDefaultNull) {
logger.info("Assigning null default value for {} on [{}#{}()]",
propertyNames, method.getDeclaringClass().getName(), method.getName());
} else {
// Final try: Is the method is actually callable?
if (!Modifier.isAbstract(method.getModifiers())) {
useMethod = true;
logger.info("Using method itself for {} on [{}#{}()]",
propertyNames, method.getDeclaringClass().getName(), method.getName());
} else {
throw new IllegalArgumentException(String.format("No value present for '%s' in [%s]",
prettyPrint(propertyNames, mappedReplacements),
method.toGenericString()));
}
}
}
if (useMethod) {
return bbBuilder.method(ElementMatchers.is(method)).intercept(SuperMethodCall.INSTANCE);
} else {
if (value == null) {
return bbBuilder.method(ElementMatchers.is(method)).intercept(FixedValue.nullValue());
} else {
final Object finalValue = bully.coerce(method.getGenericReturnType(), value, method.getAnnotation(Separator.class));
return bbBuilder.method(ElementMatchers.is(method)).intercept(FixedValue.value(finalValue));
}
}
}
private String applyReplacements(String propertyName, final Map<String, String> mappedReplacements) {
for (final Entry<String, String> entry : mappedReplacements.entrySet()) {
final String token = makeToken(entry.getKey());
final String replacement = entry.getValue();
propertyName = propertyName.replace(token, replacement);
}
return propertyName;
}
private <T> Builder<T> buildParameterized(final Builder<T> bbBuilder,
final Method method,
final Config annotation) {
String defaultValue = null;
final boolean hasDefault = method.isAnnotationPresent(Default.class);
final boolean hasDefaultNull = method.isAnnotationPresent(DefaultNull.class);
if (hasDefault && hasDefaultNull) {
throw new IllegalArgumentException(String.format("@Default and @DefaultNull present in [%s]", method.toGenericString()));
}
if (hasDefault) {
defaultValue = method.getAnnotation(Default.class).value();
} else if (!hasDefaultNull) {
throw new IllegalArgumentException(String.format("No value present for '%s' in [%s]",
prettyPrint(annotation.value(), null),
method.toGenericString()));
}
final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
final List<String> paramTokenList = new ArrayList<String>();
for (final Annotation[] parameterTab : parameterAnnotations) {
for (final Annotation parameter : parameterTab) {
if (parameter.annotationType().equals(Param.class)) {
final Param paramAnnotation = (Param) parameter;
paramTokenList.add(makeToken(paramAnnotation.value()));
break;
}
}
}
if (paramTokenList.size() != method.getParameterTypes().length) {
throw new RuntimeException(String.format("Method [%s] is missing one or more @Param annotations",
method.toGenericString()));
}
final Object bulliedDefaultValue = bully.coerce(method.getGenericReturnType(), defaultValue, method.getAnnotation(Separator.class));
final String[] annotationValues = annotation.value();
if (annotationValues.length == 0) {
throw new IllegalArgumentException("Method " +
method.toGenericString() +
" declares config annotation but no field name!");
}
final ConfigMagicMethodInterceptor invocationHandler = new ConfigMagicMethodInterceptor(method,
config,
annotationValues,
paramTokenList,
bully,
bulliedDefaultValue);
return bbBuilder.method(ElementMatchers.is(method)).intercept(InvocationHandlerAdapter.of(invocationHandler));
}
private String makeToken(final String temp) {
return "${" + temp + "}";
}
private String prettyPrint(final String[] values, final Map<String, String> mappedReplacements) {
if (values == null || values.length == 0) {
return "";
}
final StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < (values.length - 1)) {
sb.append(", ");
}
}
sb.append(']');
if (mappedReplacements != null && !mappedReplacements.isEmpty()) {
sb.append(" translated to [");
for (int i = 0; i < values.length; i++) {
sb.append(applyReplacements(values[i], mappedReplacements));
if (i < (values.length - 1)) {
sb.append(", ");
}
}
sb.append("]");
}
return sb.toString();
}
private static final class ConfigMagicMethodInterceptor implements InvocationHandler {
private final Method method;
private final ConfigSource config;
private final String[] properties;
private final Bully bully;
private final Object defaultValue;
private final List<String> paramTokenList;
private transient String toStringValue = null;
private ConfigMagicMethodInterceptor(final Method method,
final ConfigSource config,
final String[] properties,
final List<String> paramTokenList,
final Bully bully,
final Object defaultValue) {
this.method = method;
this.config = config;
this.properties = properties;
this.paramTokenList = paramTokenList;
this.bully = bully;
this.defaultValue = defaultValue;
}
@Override
public Object invoke(final Object o,
final Method method,
final Object[] args) {
for (String property : properties) {
if (args.length == paramTokenList.size()) {
for (int i = 0; i < args.length; ++i) {
property = property.replace(paramTokenList.get(i), String.valueOf(args[i]));
}
final String value = config.getString(property);
if (value != null) {
logger.info("Assigning value [{}] for [{}] on [{}#{}()]",
value, property, method.getDeclaringClass().getName(), method.getName());
return bully.coerce(method.getGenericReturnType(), value, method.getAnnotation(Separator.class));
}
} else {
throw new IllegalStateException("Argument list doesn't match @Param list");
}
}
logger.info("Assigning default value [{}] for {} on [{}#{}()]",
defaultValue, properties, method.getDeclaringClass().getName(), method.getName());
return defaultValue;
}
@Override
public String toString() {
if (toStringValue == null) {
toStringValue = method.getName() + ": " + super.toString();
}
return toStringValue;
}
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
killbill/killbill-commons | https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/config-magic/src/main/java/org/skife/config/RuntimeConfigRegistry.java | config-magic/src/main/java/org/skife/config/RuntimeConfigRegistry.java | /*
* Copyright 2020-2025 Equinix, Inc
* Copyright 2014-2025 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.skife.config;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Registry to capture and expose runtime configuration values.
*/
public class RuntimeConfigRegistry {
private static final Map<String, Map<String, String>> RUNTIME_CONFIGS_BY_SOURCE = new ConcurrentHashMap<>();
public static void putWithSource(final String configSource, final String key, final Object value) {
RUNTIME_CONFIGS_BY_SOURCE
.computeIfAbsent(configSource, k -> new ConcurrentHashMap<>())
.put(key, value == null ? "" : value.toString());
}
public static void putAllWithSource(final String configSource, final Map<String, ?> values) {
if (values == null || values.isEmpty()) {
return;
}
RUNTIME_CONFIGS_BY_SOURCE
.computeIfAbsent(configSource, k -> new ConcurrentHashMap<>())
.putAll(values.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue() == null ? "" : e.getValue().toString())));
}
public static String get(final String key) {
for (final Map<String, String> sourceMap : RUNTIME_CONFIGS_BY_SOURCE.values()) {
final String value = sourceMap.get(key);
if (value != null) {
return value;
}
}
return "";
}
public static Map<String, String> getBySource(final String source) {
return Collections.unmodifiableMap(RUNTIME_CONFIGS_BY_SOURCE.getOrDefault(source, Map.of()));
}
public static Map<String, String> getAll() {
final Map<String, String> allConfigs = new LinkedHashMap<>();
RUNTIME_CONFIGS_BY_SOURCE.values().forEach(allConfigs::putAll);
return Collections.unmodifiableMap(allConfigs);
}
public static Map<String, Map<String, String>> getAllBySource() {
return Collections.unmodifiableMap(RUNTIME_CONFIGS_BY_SOURCE);
}
public static void clear() {
RUNTIME_CONFIGS_BY_SOURCE.clear();
}
}
| java | Apache-2.0 | 9239f88b55d9255c172143bab180b7aa042fcd36 | 2026-01-05T02:38:41.530814Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.