final ResourceMethodDescriptor methodDescriptor,
final List<?> resultElements,
final PageIncrement pageIncrement,
final Integer totalResults)
{
CollectionMetadata metadata = new CollectionMetadata();
List<Parameter<?>> pagingContextParams =
methodDescriptor.getParametersWithType(Parameter.ParamType.PAGING_CONTEXT_PARAM);
PagingContext defaultPagingContext =
pagingContextParams.isEmpty() ? null
: (PagingContext) pagingContextParams.get(0).getDefaultValue();
PagingContext pagingContext = getPagingContext(resourceContext, defaultPagingContext);
metadata.setCount(pagingContext.getCount());
metadata.setStart(pagingContext.getStart());
if (totalResults != null)
{
metadata.setTotal(totalResults);
}
else
{
metadata.removeTotal();
}
LinkArray links = new LinkArray();
String bestEncoding = RestConstants.HEADER_VALUE_APPLICATION_JSON;
if (resourceContext.getRawRequest() != null)
{
bestEncoding = pickBestEncoding(resourceContext.getRequestHeaders().get(RestConstants.HEADER_ACCEPT));
}
//links use count as the step interval, so links don't make sense with count==0
if (pagingContext.getCount() > 0)
{
// prev link
if (pagingContext.getStart() > 0)
{
int prevStart = Math.max(0, pagingContext.getStart() - pagingContext.getCount());
String prevUri =
buildPaginatedUri(requestUri, prevStart, pagingContext.getCount());
Link prevLink = new Link();
prevLink.setRel("prev");
prevLink.setHref(prevUri);
prevLink.setType(bestEncoding);
links.add(prevLink);
}
// next link if there are more results, or we returned a full page
Integer nextStart = getNextPageStart(resultElements.size(), totalResults, pagingContext, pageIncrement);
if (nextStart != null)
{
// R2 doesn't expose host/port => can't build absolute URI (this is ok, as
// relative URIs internally
String nextUri =
buildPaginatedUri(requestUri, nextStart, pagingContext.getCount());
Link nextLink = new Link();
nextLink.setRel("next");
nextLink.setHref(nextUri);
nextLink.setType(bestEncoding);
links.add(nextLink);
}
metadata.setLinks(links);
}
return metadata;
}