Giter Site home page Giter Site logo

gcm4j's Introduction

GCM4J Build Status

Overview

GCM4J is a simple, extensible, documented Google Cloud Messaging (GCM) client written in Java. Written and extensively used in production by Phonedeck.

Installation

The recommended way is to use the library as a Maven dependency.

<dependency>
  <groupId>com.phonedeck</groupId>
  <artifactId>gcm4j</artifactId>
  <version>1.0</version>
</dependency>

Getting Started

Creating Gcm and Sending the First Push Message

// create a GCM4J client
Gcm gcm = new DefaultGcm(new GcmConfig()
  .withKey("your-gcm-key-from-google-apis"));
  
// assemble a request
GcmRequest request = new GcmRequest()
  .withRegistrationId("registration-id-reported-by-your-device")
  .withCollapseKey("sync")
  .withDelayWhileIdle(true)
  .withDataItem("command", "sync");

// send the request asynchronously
ListenableFuture<GcmResponse> responseFuture = gcm.send(request);

// wait for and process the response
GcmResponse response = responseFuture.get();
System.out.println("Response: " + response);

Processing the Response Asynchronously

Futures.addCallback(responseFuture, new FutureCallback<GcmResponse>() {  
  public void onSuccess(GcmResponse response) {
    System.out.println("Response: " + response);           
  }
  public void onFailure(Throwable t) {
    System.err.println("Error occured: " + t);
  }
});

Error Handling

The user can face two types of errors:

  1. network error: when the request GCM server could not be reached, or the GCM server responded with an error
  2. GCM error result: when the GCM server processed the request, but could not complete it for some reason

In the first case the request itself throws an exception:

// Synchronous
try {
  GcmResponse response = responseFuture.get();
} catch (ExecutionException ex) {
  if (ex.getCause() instanceof GcmNetworkException) {
    // GCM server gave a non-200 HTTP response
    GcmNetworkException gne = (GcmNetworkException) ex.getCause();
    System.err.println("GCM Server responded with and error: " + gne.getCode() + " " + gne.getResponse());
  } else if (ex.getCause() instanceof IOException) {
    // host not found or net is down
    System.err.println("Network error occured: " + ex);
  } else {
    // should not happen during normal operation
    System.err.println("Unknown error occured: " + ex);
  }  
} catch (InterruptedException ex) {
  // the thread waiting for the response got interrupted
  System.err.println("Thread interrupted");
  Thread.currentThread().interrupt();
}
// Asynchronous
Futures.addCallback(responseFuture, new FutureCallback<GcmResponse>() {
  public void onSuccess(GcmResponse response) { 
    // everything's shiny
  }

  public void onFailure(Throwable t) {
    if (t instanceof GcmNetworkException) {
      // GCM server gave a non-200 HTTP response
      GcmNetworkException gne = (GcmNetworkException) t;
      System.err.println("GCM Server responded with and error: " + gne.getCode() + " " + gne.getResponse());
    } else if (t instanceof IOException) {
      // host not found or net is down
      System.err.println("Network error occured: " + t);
    } else {
      // should not happen during normal operation
      System.err.println("Unknown error occured: " + t);
    }  
  }
});

In the latter case the request gets a proper response, and each registration ID has its own status:

for (Result result : response.getResults()) {
  if (result.getError() == null) {
    System.out.println("Aaaaalright");
  } else {
    System.err.println("Error " + result.getError() + " occured for registration id " + result.getRequestedRegistrationId());
  }
}

Filters

Every request is run through a chain of filters. Each filter may modify the request, pass down the request to the next filter, get back and possibly modify the response, and pass the response up to the previous one.

The order the filters were added matters. The first added filter gets the request first and the response last. Therefore the request of the last filter is passed directly to the GCM Servers and the user gets the response of the last filter.

Simple logging filter example:

public final class LoggingFilter implements GcmFilter {
  public ListenableFuture<GcmResponse> filter(GcmRequest request, FilterChain chain) {
    System.out.println("Got request: " + request);

    ListenableFuture<GcmResponse> response = chain.next(request);
    Futures.addCallback(response, new FutureCallback<GcmResponse>() {
      public void onSuccess(GcmResponse result) {
        System.out.println("Got response: " + result);
      }                        
      public void onFailure(Throwable t) {
        System.err.println("Exception occured: " + t);
      }
    });
    
    return response;
  }
}

GcmConfig config = new GcmConfig()
  .withFilter(new LoggingFilter());

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.