GCM4J

A Java library to use the Google Cloud Messaging service.

License

License

GroupId

GroupId

com.phonedeck
ArtifactId

ArtifactId

gcm4j
Last Version

Last Version

1.3
Release Date

Release Date

Type

Type

jar
Description

Description

GCM4J
A Java library to use the Google Cloud Messaging service.
Project URL

Project URL

https://github.com/phonedeck/gcm4j
Project Organization

Project Organization

Phonedeck (desk.io GmbH)
Source Code Management

Source Code Management

https://github.com/phonedeck/gcm4j

Download gcm4j

How to add to project

<!-- https://jarcasting.com/artifacts/com.phonedeck/gcm4j/ -->
<dependency>
    <groupId>com.phonedeck</groupId>
    <artifactId>gcm4j</artifactId>
    <version>1.3</version>
</dependency>
// https://jarcasting.com/artifacts/com.phonedeck/gcm4j/
implementation 'com.phonedeck:gcm4j:1.3'
// https://jarcasting.com/artifacts/com.phonedeck/gcm4j/
implementation ("com.phonedeck:gcm4j:1.3")
'com.phonedeck:gcm4j:jar:1.3'
<dependency org="com.phonedeck" name="gcm4j" rev="1.3">
  <artifact name="gcm4j" type="jar" />
</dependency>
@Grapes(
@Grab(group='com.phonedeck', module='gcm4j', version='1.3')
)
libraryDependencies += "com.phonedeck" % "gcm4j" % "1.3"
[com.phonedeck/gcm4j "1.3"]

Dependencies

compile (4)

Group / Artifact Type Version
org.slf4j : slf4j-api jar 1.7.5
commons-io : commons-io jar 1.3.2
com.fasterxml.jackson.core : jackson-databind jar 2.2.2
com.google.guava : guava jar 14.0.1

test (4)

Group / Artifact Type Version
junit : junit jar 4.8.1
ch.qos.logback : logback-classic jar 1.0.13
org.mockito : mockito-all jar 1.8.4
by.stub : stubby4j jar 2.0.11

Project Modules

There are no modules declared in this project.

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.3</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());

Version History

1.3 - Dec 16, 2015

  • Supporting priority and notification fields

1.2 - Feb 12, 2014

  • Simplified response and error handling

1.1 - Feb 11, 2014

  • Possibility to handle Retry-After values in filters
  • Richer Request and Response interfaces

1.0 - Jul 29, 2013

  • Initial release

Contributors

The maintainers would like to express their gratitude towards the contributors, that spared no time to make this library more powerful.

  • @turf00 for providing a standard way to respect the server's Retry-After response on errors and a lot of test cases
  • @jalogar for implementing missing auxiliary functions
  • @ivannkf for adding priority and notification fields
com.phonedeck

Phonedeck

Versions

Version
1.3
1.2
1.0