本文整理汇总了Java中org.skife.jdbi.v2.tweak.HandleCallback类的典型用法代码示例。如果您正苦于以下问题:Java HandleCallback类的具体用法?Java HandleCallback怎么用?Java HandleCallback使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HandleCallback类属于org.skife.jdbi.v2.tweak包,在下文中一共展示了HandleCallback类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
}
}
);
}
开发者ID:rodolfodpk,项目名称:myeslib2,代码行数:19,代码来源:Stack1JdbiDao.java
示例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;
}
开发者ID:rodolfodpk,项目名称:myeslib,代码行数:20,代码来源:HzStringMapStore.java
示例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);
}
开发者ID:rodolfodpk,项目名称:myeslib,代码行数:19,代码来源:JdbiConsumeEventsRoute.java
示例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");
}
开发者ID:groupon,项目名称:mysql-junit4,代码行数:18,代码来源:MySQLRuleExample.java
示例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");
}
开发者ID:groupon,项目名称:mysql-junit4,代码行数:18,代码来源:FlywayFixtureExample.java
示例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));
}
开发者ID:allengeorge,项目名称:libraft,代码行数:27,代码来源:OnDiskSnapshotsStoreTest.java
示例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));
}
开发者ID:allengeorge,项目名称:libraft,代码行数:25,代码来源:OnDiskSnapshotsStoreTest.java
示例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);
}
开发者ID:rodolfodpk,项目名称:myeslib2,代码行数:41,代码来源:Stack1JdbiDao.java
示例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();
}
开发者ID:camunda,项目名称:camunda-bpm-dropwizard,代码行数:13,代码来源:GetHistoryLevelDaoTest.java
示例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);
}
开发者ID:rodolfodpk,项目名称:myeslib,代码行数:13,代码来源:HzStringQueueStore.java
示例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;
}
});
}
开发者ID:killbill,项目名称:killbill-analytics-plugin,代码行数:28,代码来源:ReportsUserApi.java
示例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);
}
});
}
开发者ID:killbill,项目名称:killbill-analytics-plugin,代码行数:11,代码来源:ReportsConfiguration.java
示例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());
}
开发者ID:killbill,项目名称:killbill-analytics-plugin,代码行数:34,代码来源:TestSqlReportDataExtractorQueries.java
示例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));
}
开发者ID:allengeorge,项目名称:libraft,代码行数:37,代码来源:OnDiskSnapshotsStoreTest.java
示例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));
}
开发者ID:allengeorge,项目名称:libraft,代码行数:38,代码来源:OnDiskSnapshotsStoreTest.java
示例16: get
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public AggregateRootHistory get(final UUID id) {
final AggregateRootHistory arh = new AggregateRootHistory();
try {
log.debug("will load {} from {}", id.toString(), tables.getAggregateRootTable());
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 order by version", tables.getUnitOfWorkTable());
public List<UowRecord> withHandle(Handle h) {
return h.createQuery(sql)
.bind("id", id.toString())
.map(new UowRecordMapper()).list();
}
}
);
if (unitsOfWork != null) {
log.debug("found {} units of work for id {} on {}", unitsOfWork.size(), id.toString(), tables.getUnitOfWorkTable());
for (UowRecord r : unitsOfWork){
log.debug("converting to uow from {}", r.uowData);
UnitOfWork uow = fromStringFunction.apply(r.uowData);
log.debug(uow.toString());
arh.add(uow);
arh.markAsPersisted(uow);
}
} else {
log.debug("found none unit of work for id {} on {}", id.toString(), tables.getUnitOfWorkTable());
}
} catch (Exception e) {
log.error("error when loading {} from table {}", id.toString(), tables.getUnitOfWorkTable());
e.printStackTrace();
} finally {
}
return arh;
}
开发者ID:rodolfodpk,项目名称:myeslib,代码行数:42,代码来源:JdbiAggregateRootHistoryReaderDao.java
示例17: getTimeSeriesData
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private Map<String, List<XY>> getTimeSeriesData(final String tableName,
final ReportSpecification reportSpecification,
final ReportsConfigurationModelDao reportsConfiguration,
@Nullable final DateTime startDate,
@Nullable final DateTime endDate,
final Long tenantRecordId) {
final SqlReportDataExtractor sqlReportDataExtractor = new SqlReportDataExtractor(tableName,
reportSpecification,
startDate,
endDate,
dbEngine,
tenantRecordId);
return dbi.withHandle(new HandleCallback<Map<String, List<XY>>>() {
@Override
public Map<String, List<XY>> withHandle(final Handle handle) throws Exception {
final List<Map<String, Object>> results = handle.select(sqlReportDataExtractor.toString());
if (results.size() == 0) {
Collections.emptyMap();
}
final Map<String, List<XY>> timeSeries = new LinkedHashMap<String, List<XY>>();
for (final Map<String, Object> row : results) {
// Day
Object dateObject = row.get(DAY_COLUMN_NAME);
if (dateObject == null) {
// Timestamp
dateObject = row.get(TS_COLUMN_NAME);
if (dateObject == null) {
continue;
}
dateObject = DATE_TIME_FORMATTER.parseDateTime(dateObject.toString()).toString();
}
final String date = dateObject.toString();
final String legendWithDimensions = createLegendWithDimensionsForSeries(row, reportSpecification);
for (final String column : row.keySet()) {
if (isMetric(column, reportSpecification)) {
// Create a unique name for that result set
final String seriesName = Objects.firstNonNull(reportSpecification.getLegend(), column) + (legendWithDimensions == null ? "" : (": " + legendWithDimensions));
if (timeSeries.get(seriesName) == null) {
timeSeries.put(seriesName, new LinkedList<XY>());
}
final Object value = row.get(column);
final Float valueAsFloat = value == null ? 0f : Float.valueOf(value.toString());
timeSeries.get(seriesName).add(new XY(date, valueAsFloat));
}
}
}
return timeSeries;
}
});
}
开发者ID:killbill,项目名称:killbill-analytics-plugin,代码行数:55,代码来源:ReportsUserApi.java
示例18: getSamplesBySourceIdsAndMetricIds
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Override
public void getSamplesBySourceIdsAndMetricIds(final List<Integer> sourceIdList,
@Nullable final List<Integer> metricIdList,
final DateTime startTime,
final DateTime endTime,
final TimelineChunkConsumer chunkConsumer,
final TenantContext context) {
if (sourceIdList.size() == 0) {
return;
}
dbi.withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(final Handle handle) throws Exception {
handle.setStatementLocator(new StringTemplate3StatementLocator(TimelineSqlDao.class));
ResultIterator<TimelineChunk> iterator = null;
try {
final Query<Map<String, Object>> query = handle
.createQuery("getSamplesBySourceRecordIdsAndMetricRecordIds")
.bind("startTime", DateTimeUtils.unixSeconds(startTime))
.bind("endTime", DateTimeUtils.unixSeconds(endTime))
.bind("tenantRecordId", createInternalTenantContext(context).getTenantRecordId())
.define("sourceIds", JOINER.join(sourceIdList));
if (metricIdList != null && !metricIdList.isEmpty()) {
query.define("metricIds", JOINER.join(metricIdList));
}
iterator = query
.map(timelineChunkMapper)
.iterator();
while (iterator.hasNext()) {
chunkConsumer.processTimelineChunk(iterator.next());
}
return null;
} finally {
if (iterator != null) {
try {
iterator.close();
} catch (Exception e) {
log.error("Exception closing TimelineChunkAndTimes iterator for sourceIds {} and metricIds {}", sourceIdList, metricIdList);
}
}
}
}
});
}
开发者ID:killbill,项目名称:killbill-meter-plugin,代码行数:50,代码来源:DefaultTimelineDao.java
示例19: streamingAggregateLevel
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
private void streamingAggregateLevel(final int aggregationLevel, final int chunksToAggregate) {
final List<TimelineChunk> sourceTimelineCandidates = new ArrayList<TimelineChunk>();
final TimelineChunkConsumer aggregationConsumer = new TimelineChunkConsumer() {
int lastSourceId = 0;
int lastMetricId = 0;
@Override
public void processTimelineChunk(final TimelineChunk candidate) {
timelineChunksConsidered.incrementAndGet();
final int sourceId = candidate.getSourceId();
final int metricId = candidate.getMetricId();
if (lastSourceId == 0) {
lastSourceId = sourceId;
lastMetricId = metricId;
}
if (lastSourceId != sourceId || lastMetricId != metricId) {
aggregatesCreated.addAndGet(aggregateTimelineCandidates(sourceTimelineCandidates, aggregationLevel, chunksToAggregate));
sourceTimelineCandidates.clear();
lastSourceId = sourceId;
lastMetricId = metricId;
}
sourceTimelineCandidates.add(candidate);
}
};
final long startTime = System.currentTimeMillis();
try {
dbi.withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(final Handle handle) throws Exception {
// MySQL needs special setup to make it stream the results. See:
// http://javaquirks.blogspot.com/2007/12/mysql-streaming-result-set.html
// http://stackoverflow.com/questions/2447324/streaming-large-result-sets-with-mysql
final Query<Map<String, Object>> query = handle.createQuery("getStreamingAggregationCandidates")
.setFetchSize(Integer.MIN_VALUE)
.bind("aggregationLevel", aggregationLevel)
.bind("tenantRecordId", MeterInternalTenantContext.INTERNAL_TENANT_RECORD_ID);
query.setStatementLocator(new StringTemplate3StatementLocator(TimelineAggregatorSqlDao.class));
ResultIterator<TimelineChunk> iterator = null;
try {
iterator = query
.map(timelineChunkMapper)
.iterator();
while (iterator.hasNext()) {
aggregationConsumer.processTimelineChunk(iterator.next());
}
} catch (Exception e) {
log.error(String.format("Exception during aggregation of level %d", aggregationLevel), e);
} finally {
if (iterator != null) {
iterator.close();
}
}
return null;
}
});
if (sourceTimelineCandidates.size() >= chunksToAggregate) {
aggregatesCreated.addAndGet(aggregateTimelineCandidates(sourceTimelineCandidates, aggregationLevel, chunksToAggregate));
}
if (chunkIdsToInvalidateOrDelete.size() > 0) {
performWrites();
}
} finally {
msSpentAggregating.addAndGet(System.currentTimeMillis() - startTime);
}
}
开发者ID:killbill,项目名称:killbill-meter-plugin,代码行数:69,代码来源:TimelineAggregator.java
示例20: shouldThrowStorageExceptionIfSnapshotCannotBeStoredInSnapshotDirectory
import org.skife.jdbi.v2.tweak.HandleCallback; //导入依赖的package包/类
@Test
public void shouldThrowStorageExceptionIfSnapshotCannotBeStoredInSnapshotDirectory() throws IOException, StorageException {
long snapshotTerm = 6;
long snapshotIndex = 7;
// start by getting a snapshot
ExtendedSnapshotWriter snapshotWriter = snapshotsStore.newSnapshotWriter();
snapshotWriter.setTerm(snapshotTerm);
snapshotWriter.setIndex(snapshotIndex);
// write the snapshot
OutputStream os = snapshotWriter.getSnapshotOutputStream();
try {
os.write("TEST".getBytes(Charset.forName(Charsets.US_ASCII.toString())));
} finally {
Closeables.close(os, true);
}
// now, before you save the snapshot, delete the snapshot directory!
boolean deleted = snapshotsDirectory.delete();
assertThat(deleted, is(true));
boolean exceptionThrown = false;
try {
// then, attempt to store the snapshot :)
snapshotsStore.storeSnapshot(snapshotWriter);
} catch (StorageException e) {
exceptionThrown = true;
assertThat(e.getCause(), instanceOf(IOException.class)); // should be an IOException because we couldn't save the file
}
// check that we actually threw the exception
assertThat(exceptionThrown, is(true));
// check that no metadata was stored in the database
int entries = dbi.withHandle(new HandleCallback<Integer>() {
@Override
public Integer withHandle(Handle handle) throws Exception {
SnapshotsDAO dao = handle.attach(SnapshotsDAO.class);
return dao.getNumSnapshots();
}
});
assertThat(entries, is(0));
}
开发者ID:allengeorge,项目名称:libraft,代码行数:46,代码来源:OnDiskSnapshotsStoreTest.java
注:本文中的org.skife.jdbi.v2.tweak.HandleCallback类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论