本文整理汇总了Java中org.skife.jdbi.v2.tweak.HandleCallback类的典型用法代码示例。如果您正苦于以下问题:Java HandleCallback类的具体用法?Java HandleCallback怎么用?Java HandleCallback使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HandleCallback类属于org.skife.jdbi.v2.tweak包,在下文中一共展示了HandleCallback类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getCommand
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public Command getCommand(final CommandId commandId) {
return dbi
.withHandle(new HandleCallback<Command>() {
final String sql = String.format("select id, cmd_data " +
"from %s where id = :id ", dbMetadata.commandTable);
public Command withHandle(final Handle h) {
return h.createQuery(sql)
.bind("id", commandId.toString())
.map((i, r, ctx) -> {
final String cmdData = new ClobToStringMapper("cmd_data").map(i, r, ctx);
final Command cmd = cmdSer.fromStringFunction.apply(cmdData);
return cmd;
}).first();
}
}
);
}
示例2: loadAllKeys
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public Set<UUID> loadAllKeys() {
// TODO define how many keys will be pre-loaded
log.debug("loading all keys from table {}", tableName);
Set<UUID> result = dbi.withHandle(new HandleCallback<Set<UUID>>() {
@Override
public Set<UUID> withHandle(Handle h) throws Exception {
List<String> strResult = h.createQuery(String.format("select id from %s", tableName))
.map(new StringMapper()).list();
Set<UUID> uResult = new HashSet<>();
for (String uuid : strResult){
uResult.add(UUID.fromString(uuid));
}
return uResult;
}
});
log.debug("{} keys within table {} were loaded", result.size(), tableName);
return result;
}
示例3: process
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public void process(Exchange e) throws Exception {
final BigDecimal previousSeqNumber = e.getIn().getHeader(PREVIOUS_SEQ_NUMBER, BigDecimal.class);
final BigDecimal latestSeqNumber = dbi.withHandle(new HandleCallback<BigDecimal>() {
@Override
public BigDecimal withHandle(Handle handle) throws Exception {
String sqlGetIdsSinceLastSeqNumber =
String.format("select max(seq_number) from %s where seq_number > :previous_seq_number", tablesMetadata.getUnitOfWorkTable());
log.debug(sqlGetIdsSinceLastSeqNumber);
return handle.createQuery(sqlGetIdsSinceLastSeqNumber)
.bind("previous_seq_number", previousSeqNumber)
.map(BigDecimalMapper.FIRST)
.first();
}
});
e.getOut().setHeader(PREVIOUS_SEQ_NUMBER, previousSeqNumber);
e.getOut().setHeader(LATEST_SEQ_NUMBER, latestSeqNumber == null ? previousSeqNumber : latestSeqNumber);
}
示例4: testFixturesArePresent
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void testFixturesArePresent() throws Exception
{
DataSource ds = mysql.getDataSource();
List<String> rs = new DBI(ds).withHandle(new HandleCallback<List<String>>()
{
@Override
public List<String> withHandle(final Handle handle) throws Exception
{
return handle.createQuery("select name from something order by id")
.map(StringMapper.FIRST)
.list();
}
});
assertThat(rs).containsExactly("Gene", "Brian");
}
示例5: testFixturesEstablished
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void testFixturesEstablished() throws Exception
{
DataSource ds = mysql.getDataSource();
List<String> rs = new DBI(ds).withHandle(new HandleCallback<List<String>>()
{
@Override
public List<String> withHandle(final Handle handle) throws Exception
{
return handle.createQuery("select name from something order by id")
.map(StringMapper.FIRST)
.list();
}
});
assertThat(rs).containsExactly("Gene", "Brian");
}
示例6: shouldThrowStorageExceptionIfDatabaseCallFailsInCallToInitialize
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void shouldThrowStorageExceptionIfDatabaseCallFailsInCallToInitialize() {
// create a broken snapshotsStore that we will use to test the DB failure out on
DBI brokenDBI = mock(DBI.class);
Handle brokenHandle = mock(Handle.class);
OnDiskSnapshotsStore brokenSnapshotStore = new OnDiskSnapshotsStore(brokenDBI, snapshotsDirectory.getAbsolutePath());
// return the callback object but fail to do the attach!
IllegalArgumentException failure = new IllegalArgumentException("failed!");
when(brokenDBI.open()).thenReturn(brokenHandle);
when(brokenDBI.withHandle(any(HandleCallback.class))).thenCallRealMethod(); // calling the real method will trigger the call to open() above and cause execute the 'catch' etc. logic
when(brokenHandle.attach(any(Class.class))).thenThrow(failure);
// attempt to initialize
// we should throw an exception the moment we attempt to create the table
boolean exceptionThrown = false;
try {
brokenSnapshotStore.initialize();
} catch (StorageException e) {
exceptionThrown = true;
assertThat(e.getCause(), Matchers.<Throwable>sameInstance(failure)); // we shouldn't return the CallbackFailedException - instead the underlying exception
}
// the initialization should have failed
assertThat(exceptionThrown, is(true));
}
示例7: shouldThrowStorageExceptionIfExceptionThrownInCallToInitialize
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void shouldThrowStorageExceptionIfExceptionThrownInCallToInitialize() {
// create a broken snapshotsStore that we will use to test the DB failure out on
DBI brokenDBI = mock(DBI.class);
OnDiskSnapshotsStore brokenSnapshotStore = new OnDiskSnapshotsStore(brokenDBI, snapshotsDirectory.getAbsolutePath());
// fail the moment a handle is requested
IllegalArgumentException failure = new IllegalArgumentException("failed!");
when(brokenDBI.open()).thenThrow(failure);
when(brokenDBI.withHandle(any(HandleCallback.class))).thenCallRealMethod(); // calling the real method will trigger the call to open() above and cause execute the 'catch' etc. logic
// attempt to initialize
// we should throw an exception the moment we attempt to create the table
boolean exceptionThrown = false;
try {
brokenSnapshotStore.initialize();
} catch (StorageException e) {
exceptionThrown = true;
assertThat(e.getCause(), Matchers.<Throwable>sameInstance(failure));
}
// the initialization should have failed
assertThat(exceptionThrown, is(true));
}
示例8: getPartial
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public List<UnitOfWork> getPartial(K id, Long biggerThanThisVersion) {
final List<UnitOfWork> arh = new ArrayList<>();
logger.debug("will load {} from {}", id.toString(), dbMetadata.aggregateRootTable);
List<UowRecord> unitsOfWork = dbi
.withHandle(new HandleCallback<List<UowRecord>>() {
String sql = String.format("select id, version, uow_data, seq_number " +
"from %s where id = :id " +
" and version > :version " +
"order by version", dbMetadata.unitOfWorkTable);
public List<UowRecord> withHandle(Handle h) {
return h.createQuery(sql)
.bind("id", id.toString())
.bind("version", biggerThanThisVersion)
.map(new UowRecordMapper()).list();
}
}
);
if (unitsOfWork == null) {
logger.debug("found none unit of work for id {} and version > {} on {}", id.toString(), biggerThanThisVersion, dbMetadata.unitOfWorkTable);
return new ArrayList<>();
}
logger.debug("found {} units of work for id {} and version > {} on {}", unitsOfWork.size(), id.toString(), biggerThanThisVersion, dbMetadata.unitOfWorkTable);
for (UowRecord r : unitsOfWork) {
logger.debug("converting to uow from {}", r.uowData);
Function<String, UnitOfWork> f = uowSer.fromStringFunction;
UnitOfWork uow = f.apply(r.uowData);
logger.debug(uow.toString());
arh.add(uow);
}
return Collections.unmodifiableList(arh);
}
示例9: returns_absent_when_no_value_is_found
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void returns_absent_when_no_value_is_found() {
h2.getDbi().withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(Handle handle) throws Exception {
handle.execute("drop table act_ge_property");
return null;
}
});
assertThat(h2.get().getFailsafe().isPresent()).isFalse();
}
示例10: loadAllKeys
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public Set<Long> loadAllKeys() {
log.info(String.format("loading all keys within table %s", tableName));
List<Long> result = dbi.withHandle(new HandleCallback<List<Long>>() {
@Override
public List<Long> withHandle(Handle h) throws Exception {
return h.createQuery(String.format("select id from %s", tableName))
.map(Long.class).list();
}
});
return new HashSet<Long>(result);
}
示例11: getCountersData
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private List<DataMarker> getCountersData(final String tableName, final Long tenantRecordId) {
return dbi.withHandle(new HandleCallback<List<DataMarker>>() {
@Override
public List<DataMarker> withHandle(final Handle handle) throws Exception {
final List<Map<String, Object>> results = handle.select("select * from " + tableName + " where tenant_record_id = " + tenantRecordId);
if (results.size() == 0) {
return Collections.emptyList();
}
final List<DataMarker> counters = new LinkedList<DataMarker>();
for (final Map<String, Object> row : results) {
final Object labelObject = row.get(LABEL);
final Object countObject = row.get(COUNT_COLUMN_NAME);
if (labelObject == null || countObject == null) {
continue;
}
final String label = labelObject.toString();
final Float value = Float.valueOf(countObject.toString());
final DataMarker counter = new CounterChart(label, value);
counters.add(counter);
}
return counters;
}
});
}
示例12: executeWithConnectionAndTransaction
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private <Result> Result executeWithConnectionAndTransaction(final ReportsConfigurationQueryCallback<Result> callback) {
return dbi.withHandle(new HandleCallback<Result>() {
@Override
public Result withHandle(Handle handle) throws Exception {
final Connection connection = handle.getConnection();
final ReportsConfigurationSqlDao transactional = handle.attach(ReportsConfigurationSqlDao.class);
return callback.executeCallback(connection, transactional);
}
});
}
示例13: testQueryGeneration
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test(groups = "slow")
public void testQueryGeneration() throws Exception {
final String tableName = "payments_per_day";
embeddedDB.executeScript(String.format("drop table if exists %s;" +
"create table %s(day datetime, name varchar(100), currency varchar(10), state varchar(10), amount int, fee int, tenant_record_id int);",
tableName, tableName));
final String query = "payments_per_day;" +
"filter:(currency=USD&state!=ERRORED)|(currency=EUR¤cy=PROCESSED)|(name~'John Doe%'&name!~'John Does');" +
"filter:currency=BTC;" +
"dimension:currency(USD=Group 1|BRL,GBP,EUR,MXN,AUD=Group 2, with Europe);" +
"dimension:state;" +
"metric:avg(amount);" +
"metric:avg(fee);" +
"metric:100*sum(fee)/amount";
final ReportSpecification reportSpecification = new ReportSpecification(query);
final SqlReportDataExtractor sqlReportDataExtractor = new SqlReportDataExtractor(tableName,
reportSpecification,
new LocalDate(2012, 10, 10).toDateTimeAtStartOfDay(),
new LocalDate(2014, 11, 11).toDateTimeAtStartOfDay(),
embeddedDB.getDBEngine(),
1234L);
final List<Map<String, Object>> results = dbi.withHandle(new HandleCallback<List<Map<String, Object>>>() {
@Override
public List<Map<String, Object>> withHandle(final Handle handle) throws Exception {
return handle.select(sqlReportDataExtractor.toString());
}
});
// Don't actually test the query, just make sure it got executed (no MySQL error)
Assert.assertTrue(results.isEmpty());
}
示例14: throwWhenDAOMethodCalled
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private void throwWhenDAOMethodCalled(SnapshotStoreMethodCallable callable) throws Exception {
// create a broken snapshotsStore that we will use to test the DB failure out on
DBI mockDBI = mock(DBI.class);
Handle mockHandle = mock(Handle.class);
SnapshotsDAO mockDAO = mock(SnapshotsDAO.class);
OnDiskSnapshotsStore brokenSnapshotStore = new OnDiskSnapshotsStore(mockDBI, snapshotsDirectory.getAbsolutePath());
// basic setup:
// - return the mock handle for every open() call
// - call the real "withHandle" method for any handle callback
// - return the mock dao for every attach
// - ensure that we do nothing for the initialization
when(mockDBI.open()).thenReturn(mockHandle);
when(mockDBI.withHandle(any(HandleCallback.class))).thenCallRealMethod(); // calling the real method will trigger the call to open() above and cause execute the 'catch' etc. logic
when(mockHandle.attach(SnapshotsDAO.class)).thenReturn(mockDAO);
doNothing().when(mockDAO).createSnapshotsTableWithIndex();
// initialize
brokenSnapshotStore.initialize();
// run any tasks the caller wants before the method to test
Throwable toThrow = new IllegalArgumentException("bad argument - very boring");
callable.setup(brokenSnapshotStore, mockDAO, toThrow);
// run the method we want to test
boolean exceptionThrown = false;
try {
callable.runThrowingMethod(brokenSnapshotStore);
} catch (StorageException e) {
exceptionThrown = true;
assertThat(e.getCause(), sameInstance(toThrow)); // we shouldn't return the CallbackFailedException - instead the underlying exception
}
// we should have thrown the exception
assertThat(exceptionThrown, is(true));
}
示例15: throwOnDBIOpen
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private void throwOnDBIOpen(SnapshotStoreMethodSimpleCallable callable) throws Exception {
// create a broken snapshotsStore that we will use to test the DB failure out on
DBI brokenDBI = mock(DBI.class);
Handle mockHandle = mock(Handle.class);
SnapshotsDAO mockDAO = mock(SnapshotsDAO.class);
OnDiskSnapshotsStore brokenSnapshotStore = new OnDiskSnapshotsStore(brokenDBI, snapshotsDirectory.getAbsolutePath());
// basic setup:
// - return the mock handle for the first open() call (i.e. initialize)
// - throw on subsequent calls
// - call the real "withHandle" method for any handle callback
// - return the mock dao for every attach (should only be one attach)
// - ensure that we do nothing for the initialization
IllegalArgumentException failure = new IllegalArgumentException("failed!");
when(brokenDBI.open()).thenReturn(mockHandle).thenThrow(failure); // first return the real handle to be used in initialization, and then throw when the tested method is called
when(brokenDBI.withHandle(any(HandleCallback.class))).thenCallRealMethod(); // calling the real method will trigger the call to open() above and cause execute the 'catch' etc. logic
when(mockHandle.attach(SnapshotsDAO.class)).thenReturn(mockDAO);
doNothing().when(mockDAO).createSnapshotsTableWithIndex();
// initialize
brokenSnapshotStore.initialize();
// run any tasks the caller wants before the method to test
callable.setup(brokenSnapshotStore);
// run the method we want to test
boolean exceptionThrown = false;
try {
callable.runThrowingMethod(brokenSnapshotStore);
} catch (StorageException e) {
exceptionThrown = true;
assertThat(e.getCause(), Matchers.<Throwable>sameInstance(failure)); // we shouldn't return the CallbackFailedException - instead the underlying exception
}
// we should have thrown the exception
assertThat(exceptionThrown, is(true));
}