How to use nextPageToken in Google Apps Reseller API?

758 views Asked by At

I am writing a simple Java application that fetches all customer subscriptions from Google Apps Reseller using the Reseller API. However I am stuck at paging through the results as the max size is 100 per page and I cannot figure out the next page token. Here is the code so far. How do I use the setNextPageToken() and print all of the results?

public static void main(String[] args) throws IOException {
        GoogleCredential credentials = GoogleApiUtil.getCredentials();

        Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
                .setApplicationName("ResellerDemo").build();


        boolean allResultsRead = false;
        String nextPageToken = null;
        while (!allResultsRead) {
            Subscriptions result = service.subscriptions().list()   
                    .execute();
            List<Subscription> subscriptions = result.getSubscriptions();
            nextPageToken = result.getNextPageToken();
            if (subscriptions == null || subscriptions.size() == 0) {
                System.out.println("No subscriptions found.");
            } else {
                System.out.println("Subscriptions:");
                for (Subscription sub : subscriptions) {
                    System.out.printf("%s (%s, %s)\n",
                            sub.getCustomerId(),
                            sub.getSkuId(),                               
                            sub.getPlan().getCommitmentInterval());
                }
            }
            if (result.getNextPageToken() == null) {
                allResultsRead = true;

            } else {
                result.setNextPageToken(result.getNextPageToken());

            }

        }
1

There are 1 answers

0
Gal Morad On BEST ANSWER

This should work. When you implement the real thing, make sure you have retry with exponential back off.

public void retrieveAll() throws IOException, InterruptedException {

    GoogleCredential credentials = GoogleApiUtil.getCredentials();

    Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
            .setApplicationName("ResellerDemo").build();

    String nextPageToken = null;


    do {
        Subscriptions subsList = service.subscriptions().list().setMaxResults(Long.valueOf(100)).setPageToken(nextPageToken)
                .execute();
        printSubscirptions(subsList);

        nextPageToken = subsList.getNextPageToken();

    } while(nextPageToken != null && !"".equals(nextPageToken));


}

private void printSubscirptions(Subscriptions subscriptions){
    System.out.println("Subscriptions:");
    for (Subscription sub : subscriptions.getSubscriptions()) {
        System.out.printf("%s (%s, %s)\n",
                sub.getCustomerId(),
                sub.getSkuId(),
                sub.getPlan().getCommitmentInterval());
    }

}