use of org.candlepin.model.ResultIterator in project candlepin by candlepin.
the class CandlepinQueryInterceptor method postProcess.
@Override
public void postProcess(ServerResponse response) {
Object entity = response.getEntity();
if (entity instanceof CandlepinQuery) {
final PageRequest pageRequest = ResteasyProviderFactory.getContextData(PageRequest.class);
final Session session = this.openSession();
final CandlepinQuery query = (CandlepinQuery) entity;
final ObjectMapper mapper = this.jsonProvider.locateMapper(Object.class, MediaType.APPLICATION_JSON_TYPE);
// Use a separate session so we aren't at risk of lazy loading or interceptors closing
// our cursor mid-stream.
query.useSession(session);
// Apply any paging config we may have
if (pageRequest != null) {
// Impl note:
// Sorting will always be required (for consistency) if a page request object is
// present -- either isPaging() will be true, or we'll have ordering config.
String sortField = pageRequest.getSortBy() != null ? pageRequest.getSortBy() : AbstractHibernateObject.DEFAULT_SORT_FIELD;
PageRequest.Order order = pageRequest.getOrder() != null ? pageRequest.getOrder() : PageRequest.DEFAULT_ORDER;
query.addOrder(order == PageRequest.Order.DESCENDING ? Order.desc(sortField) : Order.asc(sortField));
if (pageRequest.isPaging()) {
query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
query.setMaxResults(pageRequest.getPerPage());
// Create a page object for the link header response
Page page = new Page();
// This is expensive :(
page.setMaxRecords(query.getRowCount());
page.setPageRequest(pageRequest);
// Note: we don't need to store the page data in the page
ResteasyProviderFactory.pushContext(Page.class, page);
}
}
// Set the output streamer that will stream our query result
response.setEntity(new StreamingOutput() {
@Override
public void write(OutputStream stream) throws IOException, WebApplicationException {
JsonGenerator generator = null;
ResultIterator<Object> iterator = null;
try {
generator = mapper.getJsonFactory().createGenerator(stream);
iterator = query.iterate();
generator.writeStartArray();
while (iterator.hasNext()) {
mapper.writeValue(generator, iterator.next());
}
generator.writeEndArray();
} finally {
if (generator != null) {
generator.flush();
generator.close();
}
if (iterator != null) {
iterator.close();
}
if (session != null) {
session.close();
}
}
}
});
}
}
Aggregations