Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.5.0+

Box: Poll User Events and Save a Checkpoint

See more Box Examples

Poll the authenticated user event stream in bounded batches. The local JSON checkpoint keeps processed event IDs and the next stream position. This single-process demonstration logs events; a production worker should commit its business action, deduplication record, and cursor transactionally and prune old IDs.

See the Box API guide for setup and the complete workflow.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
    //  See Global Unlock Sample.
    //  Guide: Box API Guide.

    success = false;

    //  Supply an unexpired token obtained with one of the Box authentication examples.
    //  A token represents a particular user or service account. IDs must be accessible to it.
    CkHttpCurl curl = new CkHttpCurl();
    curl.SetVar("access_token","BOX_ACCESS_TOKEN");

    CkJsonObject state = new CkJsonObject();
    CkFileAccess files = new CkFileAccess();
    String statePath = "qa_data/box_events_state.json";
    if (files.FileExists(statePath) == true) {
        success = state.LoadFile(statePath);
        if (success != true) {
            Log.i(TAG, state.lastErrorText());
            return;
            }

        if (state.HasMember("position") != true) {
            Log.i(TAG, "Invalid checkpoint: position missing.");
            return;
            }

        }
    else {
        //  "now" starts a new subscription. It deliberately skips historical events.
        state.UpdateString("position","now");
        }

    curl.SetVar("position",state.stringOf("position"));
    CkJsonObject page = new CkJsonObject();
    CkStringBuilder seenPath = new CkStringBuilder();
    String eventId;
    String nextPosition;
    int batch = 0;
    int i;
    int count;
    boolean more = true;
    while ((more == true) and (batch < 20)) {
        curl.ClearTargetOutput("*");
        CkStringBuilder authorizedCommand1 = new CkStringBuilder();
        authorizedCommand1.SetString("curl -X GET \"https://api.box.com/2.0/events?stream_type=all&stream_position={{position}}&limit=100\" -H \"Authorization: Bearer {{access_token}}\"");
        int headerReplacement1 = authorizedCommand1.Replace("{{access_token}}",curl.getVar("access_token"));
        success = curl.DoYourThing(authorizedCommand1.getAsString());
        if ((success != true) or (curl.get_StatusCode() != 200)) {
            Log.i(TAG, "Box request failed. HTTP status: " + String.valueOf(curl.get_StatusCode()));
            Log.i(TAG, "Failure reason: " + String.valueOf(curl.get_FailReason()));
            Log.i(TAG, curl.responseBodyStr());
            return;
            }

        success = curl.GetResponseJson(page);
        if (success != true) {
            Log.i(TAG, curl.lastErrorText());
            return;
            }

        count = page.SizeOfArray("entries");
        i = 0;
        while (i < count) {
            page.put_I(i);
            eventId = page.stringOf("entries[i].event_id");
            if (eventId == "") {
                Log.i(TAG, "Event without an event_id; checkpoint not advanced.");
                return;
                }

            seenPath.Clear();
            seenPath.Append("seen.");
            seenPath.Append(eventId);
            if (state.HasMember(seenPath.getAsString()) == false) {
                //  Replace this logging with your idempotent business operation.
                //  Record success only after that operation succeeds.
                Log.i(TAG, eventId + " " + page.stringOf("entries[i].event_type") + " " + page.stringOf("entries[i].source.id"));
                state.UpdateBool(seenPath.getAsString(),true);
                }

            i = i + 1;
            }

        nextPosition = page.stringOf("next_stream_position");
        if (nextPosition == "") {
            Log.i(TAG, "Missing next_stream_position; checkpoint not advanced.");
            return;
            }

        more = (count > 0) and (nextPosition != curl.getVar("position"));
        state.UpdateString("position",nextPosition);
        success = state.WriteFile(statePath);
        if (success != true) {
            Log.i(TAG, state.lastErrorText());
            return;
            }

        curl.SetVar("position",nextPosition);
        batch = batch + 1;
        }

    Log.i(TAG, "Checkpoint saved. Run again later to continue polling.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}