How to get paged collection with java sdk

Hello!

I am using cumulocity java sdk 1011.0.22 for microservice development.

I need to get list of managed object with pagination information. The list is filtered using
InventoryFilter object.

How I can get it?

When I do

inventoryApi.getManagedObjectsByFilter(new InventoryFilter().byFragmentType(fragmentType))

it returns ManagedObjectCollection. Is it possible to get here the amount of pages?

Thanks in advance!

Hi Boris,

a ManagedObjectCollection is actually a PageCollectionResource which has the following methods:
http://resources.cumulocity.com/documentation/javasdk/current/com/cumulocity/sdk/client/PagedCollectionResource.html

To get the first page for a pageSize of 100 you can do

moc.get(100);

This returns a PagedManagedObjectCollectionRepresentation:
http://resources.cumulocity.com/documentation/javasdk/current/com/cumulocity/sdk/client/inventory/PagedManagedObjectCollectionRepresentation.html

which has a methods getPageStatistics that returns a PageStatisticsRepresentation that contains information about the number of pages:
http://resources.cumulocity.com/documentation/javasdk/current/com/cumulocity/rest/representation/PageStatisticsRepresentation.html

3 Likes

Hello, Harald!

Many thanks for your answer.
Could you please tell me then, how I can get second page in such case?

I found the method

PageStatisticsRepresentation#getPage(BaseCollectionRepresentation collectionRepresentation, int pageNumber, int pageSize)

but I can’t understand what should I pass with the first parameter.

Hi Boris,

the first parameter, is the “current” page on which you are operating. A normal workflow would be to call one of get() methods which returns a BaseCollectionRepresentation of the first page and then navigate back and forwards using getNextPage() or getPreviousPage() while using the last fetched page for the first parameter. Or use getPage() to fetch a specific page. In any case you need to invoke get() once to get the first page.

2 Likes

Hi,
don’t forget the allPages() method (of PagedManagedObjectCollectionRepresentation) which returns a handy iterable, which will do the paging under the hood.
Hence you could do the following and don’t need to care about getting the next page. Once it reaches object 101 (in this case with page size 100) it will get the next page for you.

Iterable<ManagedObjectRepresentation> it = inventoryApi.getManagedObjectsByFilter(new InventoryFilter().byFragmentType(fragmentType)).get(100).allPages();
for(ManagedObjectRepresentation mo : it){
   //do something
}

Regards Kai

2 Likes