code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.MessageStore; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message and notifies all registered devices. * * <p>This class should not be called directly. Instead, it's used as a helper * for the SendMessage task queue. */ @SuppressWarnings("serial") public class MulticastQueueWorker extends BaseServlet { private MessageSender mSender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); mSender = new MessageSender(config); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { Long multicastId = new Long(req.getParameter("multicastKey")); boolean success = mSender.sendMessage(multicastId); if (success) { taskDone(resp, multicastId); } else { retryTask(resp); } } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp, Long multicastId) { MessageStore.deleteMulticast(multicastId); resp.setStatus(200); } }
Java
/** * Copyright 2012 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.api; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.device.MessageSender; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Send message to all registered devices */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final Logger LOG = Logger.getLogger(SendMessageServlet.class.getName()); /** Authentication key for incoming message requests */ private static final String[][] AUTHORIZED_KEYS = { {"YOUR_API_KEYS_HERE", "developers.google.com"}, {"YOUR_API_KEYS_HERE", "googleapis.com/googledevelopers"}, {"YOUR_API_KEYS_HERE", "Device Key"} }; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Authenticate request String authKey = null; String authHeader = req.getHeader("Authorization"); String squelch = null; if (authHeader != null) { // Use 'Authorization: key=...' header String splitHeader[] = authHeader.split("="); if ("key".equals(splitHeader[0])) { authKey = splitHeader[1]; } } if (authKey == null) { // Valid auth key not found. Check for 'key' query parameter. // Note: This is included for WebHooks support, but will consume message body! authKey = req.getParameter("key"); squelch = req.getParameter("squelch"); } String authorizedUser = null; for (String[] candidateKey : AUTHORIZED_KEYS) { if (candidateKey[0].equals(authKey)) { authorizedUser = candidateKey[1]; break; } } if (authorizedUser == null) { send(resp, 403, "Not authorized"); return; } // Extract URL components String result = req.getPathInfo(); if (result == null) { send(resp, 400, "Bad request (check request format)"); return; } String[] components = result.split("/"); if (components.length != 3) { send(resp, 400, "Bad request (check request format)"); return; } String target = components[1]; String action = components[2]; // Extract extraData String payload = readBody(req); // Override: add jitter for server update requests // if ("sync_schedule".equals(action)) { // payload = "{ \"sync_jitter\": 21600000 }"; // } // Request decoding complete. Log request parameters LOG.info("Authorized User: " + authorizedUser + "\nTarget: " + target + "\nAction: " + action + "\nSquelch: " + (squelch != null ? squelch : "null") + "\nExtra Data: " + payload); // Send broadcast message MessageSender sender = new MessageSender(getServletConfig()); if ("global".equals(target)) { List<Device> allDevices = DeviceStore.getAllDevices(); if (allDevices == null || allDevices.isEmpty()) { send(resp, 404, "No devices registered"); } else { int resultCount = allDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(allDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } else { // Send message to one device List<Device> userDevices = DeviceStore.findDevicesByGPlusId(target); if (userDevices == null || userDevices.isEmpty()) { send(resp, 404, "User not found"); } else { int resultCount = userDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(userDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } } private String readBody(HttpServletRequest req) throws IOException { ServletInputStream inputStream = req.getInputStream(); java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } private static void send(HttpServletResponse resp, int status, String body) throws IOException { if (status >= 400) { LOG.warning(body); } else { LOG.info(body); } // Prevent frame hijacking resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Write response data resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); out.print(body); resp.setStatus(status); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.cron; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class VacuumDbServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Print "OK" message PrintWriter out = resp.getWriter(); out.print("OK"); resp.setStatus(HttpServletResponse.SC_OK); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class MessageStore { private static final Logger LOG = Logger.getLogger(MessageStore.class.getName()); private MessageStore() { throw new UnsupportedOperationException(); } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices * @param type message type * @param extraData additional message payload * @return ID for the persistent record */ public static Long createMulticast(List<String> devices, String type, String extraData) { LOG.info("Storing multicast for " + devices.size() + " devices. (type=" + type + ")"); MulticastMessage msg = new MulticastMessage(); msg.setDestinations(devices); msg.setAction(type); msg.setExtraData(extraData); ofy().save().entity(msg).now(); Long id = msg.getId(); LOG.fine("Multicast ID: " + id); return id; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record */ public static MulticastMessage getMulticast(Long id) { return ofy().load().type(MulticastMessage.class).id(id).get(); } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(Long id, List<String> devices) { MulticastMessage msg = ofy().load().type(MulticastMessage.class).id(id).get(); if (msg == null) { LOG.severe("No entity for multicast ID: " + id); return; } msg.setDestinations(devices); ofy().save().entity(msg); } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. */ public static void deleteMulticast(Long id) { ofy().delete().type(MulticastMessage.class).id(id); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; public class DeviceStore { private static final Logger LOG = Logger.getLogger(DeviceStore.class.getName()); /** * Registers a device. * * @param gcmId device's registration id. */ public static void register(String gcmId, String gPlusId) { LOG.info("Registering device.\nG+ ID: " + gPlusId + "\nGCM ID: " + gcmId); Device oldDevice = findDeviceByGcmId(gcmId); if (oldDevice == null) { // Existing device not found (as expected) Device newDevice = new Device(); newDevice.setGcmId(gcmId); newDevice.setGPlusId(gPlusId); ofy().save().entity(newDevice); } else { // Existing device found LOG.warning(gcmId + " is already registered"); if (!gPlusId.equals(oldDevice.getGPlusId())) { LOG.info("gPlusId has changed from '" + oldDevice.getGPlusId() + "' to '" + gPlusId + "'"); oldDevice.setGPlusId(gPlusId); ofy().save().entity(oldDevice); } } } /** * Unregisters a device. * * @param gcmId device's registration id. */ public static void unregister(String gcmId) { Device device = findDeviceByGcmId(gcmId); if (device == null) { LOG.warning("Device " + gcmId + " already unregistered"); return; } LOG.info("Unregistering " + gcmId); ofy().delete().entity(device); } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldGcmId, String newGcmId) { LOG.info("Updating " + oldGcmId + " to " + newGcmId); Device oldDevice = findDeviceByGcmId(oldGcmId); if (oldDevice == null) { LOG.warning("No device for registration id " + oldGcmId); return; } // Device exists. Since we use the GCM key as the (immutable) primary key, // we must create a new entity. Device newDevice = new Device(); newDevice.setGcmId(newGcmId); newDevice.setGPlusId(oldDevice.getGPlusId()); ofy().save().entity(newDevice); ofy().delete().entity(oldDevice); } /** * Gets registered device count. */ public static int getDeviceCount() { return ofy().load().type(Device.class).count(); } public static List<Device> getAllDevices() { return ofy().load().type(Device.class).list(); } public static Device findDeviceByGcmId(String regId) { return ofy().load().type(Device.class).id(regId).get(); } public static List<Device> findDevicesByGPlusId(String target) { return ofy().load().type(Device.class).filter("gPlusId", target).list(); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db.models; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; @Entity public class Device { @Id private String gcmId; @Index private String gPlusId; public String getGcmId() { return gcmId; } public void setGcmId(String gcmId) { this.gcmId = gcmId; } public String getGPlusId () { return gPlusId; } public void setGPlusId(String gPlusId) { this.gPlusId = gPlusId; } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db.models; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import java.util.List; @Entity public class MulticastMessage { @Id private Long id; private String action; private String extraData; private List<String> destinations; public Key<MulticastMessage> getKey() { return Key.create(MulticastMessage.class, id); } public Long getId() { return id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } public List<String> getDestinations() { return destinations; } public void setDestinations(List<String> destinations) { this.destinations = destinations; } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; /** Static initializer for Objectify ORM service. * * <p>To use this class: com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; * * <p>This is responsible for registering model classes with Objectify before any references * access to the ObjectifyService takes place. All models *must* be registered here, as Objectify * doesn't do classpath scanning (by design). */ public class OfyService { static { factory().register(Device.class); factory().register(MulticastMessage.class); } public static Objectify ofy() { return ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.server.db; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.DatastoreService; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { public static final String API_KEY = "<ENTER_YOUR_KEY>"; public static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger mLogger = Logger.getLogger(getClass().getName()); @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch(EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, API_KEY); datastore.put(entity); mLogger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } /** * Gets the access key. */ protected String getKey() { com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { mLogger.severe("Exception will retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
Java
package com.googlecode.catchexception.apis.hamcrest; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; /** * Creates a {@link Matcher matcher} that matches an exception that has no * {@link Throwable#getCause() cause}. * * @author rwoo * * @param <T> * an exception subclass */ public class ExceptionNoCauseMatcher<T extends Exception> extends BaseMatcher<T> { /* * (non-Javadoc) * * @see org.hamcrest.Matcher#matches(java.lang.Object) */ public boolean matches(Object obj) { if (!(obj instanceof Exception)) return false; Exception exception = (Exception) obj; return exception.getCause() == null; } /* * (non-Javadoc) * * @see org.hamcrest.SelfDescribing#describeTo(org.hamcrest.Description) */ public void describeTo(Description description) { description.appendText("has no cause"); } }
Java
package com.googlecode.catchexception.apis.hamcrest; import org.hamcrest.BaseMatcher; import org.hamcrest.CoreMatchers; import org.hamcrest.Description; import org.hamcrest.Matcher; /** * * Creates a {@link Matcher matcher} that matches an exception with a certain * message. * * @author rwoo * * @param <T> * an exception subclass */ public class ExceptionMessageMatcher<T extends Exception> extends BaseMatcher<T> { /** * The string matcher that shall match exception message. */ private Matcher<String> expectedMessageMatcher; /** * @param expectedMessage * the expected exception message */ public ExceptionMessageMatcher(String expectedMessage) { super(); this.expectedMessageMatcher = CoreMatchers.is(expectedMessage); } /** * @param expectedMessageMatcher * a string matcher that shall match the exception message */ public ExceptionMessageMatcher(Matcher<String> expectedMessageMatcher) { super(); this.expectedMessageMatcher = expectedMessageMatcher; } /* * (non-Javadoc) * * @see org.hamcrest.Matcher#matches(java.lang.Object) */ public boolean matches(Object obj) { if (!(obj instanceof Exception)) return false; Exception exception = (Exception) obj; String foundMessage = exception.getMessage(); return expectedMessageMatcher.matches(foundMessage); } /* * (non-Javadoc) * * @see org.hamcrest.SelfDescribing#describeTo(org.hamcrest.Description) */ public void describeTo(Description description) { description.appendText("has a message that ").appendDescriptionOf( expectedMessageMatcher); } }
Java
package com.googlecode.catchexception.apis; import com.googlecode.catchexception.apis.fest.CatchExceptionFestObjectAssert; /** * This 'proof of concept' shows how use catch-exception with a syntax similar * to <a href="http://docs.codehaus.org/display/FEST/More+Examples">FEST</a>, * see {@link #assertThat2(Object)}. * * @author rwoo * */ public class CatchExceptionFestAssertions { /** * Creates a new instance of * <code>{@link CatchExceptionFestObjectAssert}</code>. * <p> * EXAMPLE: * <code><pre class="prettyprint lang-java">assertThat2(service).throwz(IllegalArgumentException.class).when().prepareBilling(Prize.Zero); assertThat(caughtException()) .hasMessage("Prize must be greater than zero but was 0.0") .hasNoCause(); </pre></code> * * @param <T> * @param actual * the value to be the target of the assertions methods. * @return Returns the created assertion object. */ public static <T> CatchExceptionFestObjectAssert<T> assertThat2(T actual) { return new CatchExceptionFestObjectAssert<T>(actual); } }
Java
package com.googlecode.catchexception.apis.fest; import org.fest.assertions.ObjectAssert; import com.googlecode.catchexception.CatchException; /** * In comparison to {@link ObjectAssert} this class holds a proxy that is able * to catch and verify that a exception is thrown as soon as any method is * called on the proxy. * * @author rwoo * * @param <T> * the type of object that shall be proxied so that the proxy can * catch and verify the thrown exception. */ public class CatchExceptionFestObjectAssert<T> extends ObjectAssert { /** * The proxy that is able to catch and verify that a exception is thrown as * soon as any method is called on the proxy. */ private T proxy; /** * @param actual * the target to verify. */ public CatchExceptionFestObjectAssert(T actual) { super(actual); } /** * Verifies that a method throws an exception of the given type, or to be * more precise, creates a proxy that is able to do this. See * {@link #when()}. * * @param expectedExceptionType * the type of the expected exception * @return Returns this assertion object with an initialized proxy, see * {@link #when()}. */ @SuppressWarnings("unchecked") public CatchExceptionFestObjectAssert<T> throwz( Class<? extends Exception> expectedExceptionType) { proxy = (T) CatchException.verifyException(actual, expectedExceptionType); return this; } /** * @return Returns the proxy that catches and verifies that a exception is * thrown as soon as any method is called on the proxy. */ public T when() { return proxy; } }
Java
package com.googlecode.catchexception.apis; import org.hamcrest.Matcher; import org.junit.matchers.JUnitMatchers; import com.googlecode.catchexception.apis.hamcrest.ExceptionMessageMatcher; import com.googlecode.catchexception.apis.hamcrest.ExceptionNoCauseMatcher; /** * Provides some {@link Matcher matchers} to match some {@link Exception * exception} properties. * <p> * EXAMPLE: * <code><pre class="prettyprint lang-java">assertThat(caughtException(), allOf( is(IndexOutOfBoundsException.class), hasMessage("Index: 9, Size: 9"), hasNoCause() ));</pre></code> * <p> * To combine the standard Hamcrest matchers, your custom matchers, these * matchers, and other matcher collections (as {@link JUnitMatchers}) in a * single class follow the instructions outlined in <a * href="http://code.google.com/p/hamcrest/wiki/Tutorial#Sugar_generation">Sugar * generation</a>. * * @author rwoo */ public class CatchExceptionHamcrestMatchers { /** * EXAMPLE: * <code><pre class="prettyprint lang-java">assertThat(caughtException(), hasMessage("Index: 9, Size: 9"));</pre></code> * * @param <T> * the exception subclass * @param expectedMessage * the expected exception message * @return Returns a matcher that matches an exception if it has the given * message. */ public static <T extends Exception> org.hamcrest.Matcher<T> hasMessage( String expectedMessage) { return new ExceptionMessageMatcher<T>(expectedMessage); } /** * EXAMPLES: * <code><pre class="prettyprint lang-java">assertThat(caughtException(), hasMessageThat(is("Index: 9, Size: 9"))); assertThat(caughtException(), hasMessageThat(containsString("Index: 9"))); // using JUnitMatchers assertThat(caughtException(), hasMessageThat(containsPattern("Index: \\d+"))); // using Mockito's Find</pre></code> * * @param <T> * the exception subclass * @param stringMatcher * a string matcher * @return Returns a matcher that matches an exception if the given string * matcher matches the exception message. */ public static <T extends Exception> org.hamcrest.Matcher<T> hasMessageThat( Matcher<String> stringMatcher) { return new ExceptionMessageMatcher<T>(stringMatcher); } /** * EXAMPLE: * <code><pre class="prettyprint lang-java">assertThat(caughtException(), hasNoCause());</pre></code> * * @param <T> * the exception subclass * @return Returns a matcher that matches the exception if it does not have * a {@link Throwable#getCause() cause}. */ public static <T extends Exception> org.hamcrest.Matcher<T> hasNoCause() { return new ExceptionNoCauseMatcher<T>(); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** This package contains the public API of project catch-exception. You find more information in {@link com.googlecode.catchexception.CatchException}. */ package com.googlecode.catchexception;
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; import java.io.Serializable; /** * Thrown if a method has not thrown an exception of the expected type. * * @author rwoo * @since 16.09.2011 */ public class ExceptionNotThrownAssertionError extends AssertionError { /** * See {@link Serializable}. */ private static final long serialVersionUID = 7044423604241785057L; /** * Use this constructor if neither an exception of the expected type nor * another exception is thrown. * * @param <E> * the type of the exception that is not thrown. * @param clazz * the type of the exception that is not thrown. */ public <E extends Exception> ExceptionNotThrownAssertionError(Class<E> clazz) { super(clazz == Exception.class ? "Exception expected but not thrown" : "Neither an exception of type " + clazz.getName() + " nor another exception was thrown"); } /** * Use this constructor if an exception of another than the expected type is * thrown. * * @param <E> * the type of the exception that is not thrown. * @param clazz * the type of the exception that is not thrown. * @param e * the exception that has been thrown instead of the expected * one. */ public <E extends Exception> ExceptionNotThrownAssertionError( Class<E> clazz, Exception e) { super("Exception of type " + clazz.getName() + " expected but was not thrown. " + "Instead an exception of type " + e.getClass() + " with message '" + e.getMessage() + "' was thrown."); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; import org.mockito.cglib.proxy.MethodInterceptor; import com.googlecode.catchexception.internal.DelegatingInterceptor; import com.googlecode.catchexception.internal.ExceptionHolder; import com.googlecode.catchexception.internal.ExceptionProcessingInterceptor; import com.googlecode.catchexception.internal.InterfaceOnlyProxyFactory; import com.googlecode.catchexception.internal.SubclassProxyFactory; /** * The methods of this class catch and verify exceptions in <em>a single line of * code</em> and make them available for further analysis. * <p> * This Javadoc content is also available on the <a * href="http://code.google.com/p/catch-exception/" >catch-exception</a> web * page. * * <h1>Documentation</h1> * <p> * <b> <a href="#1">1. How to use catch-exception?</a><br/> * <a href="#2">2. What is this stuff actually good for?</a> <br/> * <a href="#3">3. How does it work internally?</a><br/> * <a href="#4">4. When is the caught exception reset?</a><br/> * <a href="#5">5. My code throws a ClassCastException. Why?</a> <br/> * <a href="#6">6. The exception is not caught. Why?</a> <br/> * <a href="#7">7. Do I have to care about memory leaks?</a> <br/> * <a href="#8">8. The caught exception is not available in another thread. * Why?</a><br/> * <a href="#9">9. How do I catch an exception thrown by a static method?</a> <br/> * <a href="#11">11. Can I catch errors instead of exceptions?</a> <br/> * * * * </b> * <p> * <h3 id="1">1. How to use catch-exception?</h3> * <p> * The most basic usage is: * <code><pre class="prettyprint lang-java">import static com.googlecode.catchexception.CatchException.*; // call customerService.prepareBilling(Prize.Zero) // and catch the exception if any is thrown catchException(customerService).prepareBilling(Prize.Zero); // assert that an IllegalArgumentException was thrown assert caughtException() instanceof IllegalArgumentException;</pre></code> * <p> * You can combine the two lines of code in a single one if you like: * <code><pre class="prettyprint lang-java">// call customerService.prepareBilling(Prize.Zero) // and throw an ExceptionNotThrownAssertionError if // the expected exception is not thrown verifyException(customerService, IllegalArgumentException.class).prepareBilling(Prize.Zero);</pre></code> * There is a minor difference between both variants. In the first variant you * must start the JVM with option <code>-ea</code> to enable the assertion. The * second variant does not use JDK assertions and ,therefore, always verifies * the caught exception. * <p> * A third variant allows you to select the type of exceptions you want to catch * (no verification involved): * <code><pre class="prettyprint lang-java">// catch IllegalArgumentExceptions but no other exceptions catchException(customerService, IllegalArgumentException.class).prepareBilling(Prize.Zero);</pre></code> * <p> * The fourth and last variant verifies that some exception is thrown, i.e. the * type of the exception does not matter: * <code><pre class="prettyprint lang-java">verifyException(customerService).prepareBilling(Prize.Zero);</pre></code> * <p> * In all variants you can use <code>caughtException()</code> afterwards to * inspect the caught exception. * <h3 id="2">2. What is this stuff actually good for?</h3> * <p> * This class targets concise and robust code in tests. Dadid Saff, a commiter * to JUnit, has <a * href="http://shareandenjoy.saff.net/2006/12/assertthrownexception_20.html" * >discussed</a> this approach in 2007. Let me summarize the arguments here. * <p> * There are two advantages of the approach proposed here in comparison to the * use of try/catch blocks. * <ul> * <li>The test is more concise and easier to read. * <li>The test cannot be corrupted by a missing assertion. Assume you forgot to * type <code>fail()</code> behind the method call that is expected to throw an * exception. * </ul> * <p> * There are also some advantages of this approach in comparison to test * runner-specific mechanisms that catch and verify exceptions. * <ul> * <li>A single test can verify more than one thrown exception. * <li>The test can verify the properties of the thrown exception after the * exception is caught. * <li>The test can specify by which method call the exception must be thrown. * <li>The test does not depend on a specific test runner (JUnit4, TestNG). * </ul> * <p> * <h3 id="3">3. How does it work internally?</h3> * <p> * The method <code>catchException(obj)</code> wraps the given object with a * proxy that catches the exception, then (optionally) verifies the exception, * and finally attaches the exception to the current <a * name="threadlocal">thread</a> for further analysis. The <a * href="#proxies">known limitations</a> for proxies apply. * <p> * Is both memory consumption and runtime a concern for you? Then use try/catch * blocks instead of this class. Because in this case the creation of proxies is * an unnecessary overhead. If only either memory consumption or runtime is an * issue for you, feel free to configure the cache of the underlying proxy * factories as appropriate. * <h3 id="4">4. When is the caught exception reset?</h3> * <p> * The Method {@link #caughtException()} returns the exception thrown by the * last method call on a proxied object in the current thread, i.e. it is reset * by calling a method on the proxied object. If the called method has not * thrown an exception, <code>caughtException()</code> returns null. * <p> * To reset the caught exception manually, call {@link #resetCaughtException()}. * At the moment there is no way to reset exceptions that have been caught in * other threads. * <h3 id="5"><a name="proxies" />5. My code throws a ClassCastException. Why?</h3> * <p> * Example: * <code><pre class="prettyprint lang-java">StringBuilder sb = new StringBuilder(); catchException(sb).charAt(-2); // throws ClassCastException</pre></code> * <p> * Probably you have tested a final class. Proxy factories usually try to * subclass the type of the proxied object. This is not possible if the original * class is final. But there is a way out. If the tested method belongs to an * interface, then you can cast the argument (here: <code>sb</code>) to that * interface or ,easier, change the declared type of the argument to the * interface type. This works because the created proxy is not longer required * to have the same type as the original class but it must only have the same * interface. * <code><pre class="prettyprint lang-java">// first variant StringBuilder sb = new StringBuilder(); catchException((CharSequence) sb).charAt(-2); // works fine // second variant CharSequence sb = new StringBuilder(); catchException(sb).charAt(-2); // works fine</pre></code> If the tested * method does no belong to an interface fall back to the try/catch-blocks or * use <a * href="http://code.google.com/p/catch-exception/wiki/Dependencies">Powermock * </a>. * <code><pre class="prettyprint lang-java">// example for PowerMock with JUnit4 &#064;RunWith(PowerMockRunner.class) &#064;PrepareForTest({ MyFinalType.class }) public class MyTest { </pre></code> * <h3 id="6">6. The exception is not caught. Why?</h3> * <p> * Example: * <code><pre class="prettyprint lang-java">ServiceImpl impl = new ServiceImpl(); catchException(impl).do(); // do() is a final method that throws an exception</pre></code> * <p> * Probably you have tested a final method. If that tested method belongs to an * interface you could use {@link #interfaces(Object)} to fix that problem. But * then the syntax starts to become ugly. * <code><pre class="prettyprint lang-java">Service api = new ServiceImpl(); catchException(interfaces(api)).do(); // works fine</pre></code> I recommend * to use try/catch blocks in such cases. * * <h3 id="7">7. Do I have to care about memory leaks?</h3> * <p> * This library uses a {@link ThreadLocal}. ThreadLocals are known to cause * memory leaks if they refer to a class the garbage collector would like to * collect. If you use this library only for testing, then memory leaks do not * worry you. If you use this library for other purposes than testing, you * should care. * <p> * <h3 id="8">8. The caught exception is not available in another thread. Why?</h3> * <p> * The caught exception is saved <a href="#threadlocal">at the thread</a> the * exception is thrown in. This is the reason the exception is not visible * within any other thread. * <h3 id="9">9. How do I catch an exception thrown by a static method?</h3> * <p> * Unfortunately, catch-exception does not support this. Fall back on try/catch * blocks. * <h3 id="10">10. Is there a way to get rid of the throws clause in my test * method?</h3> * <p> * Example: * <code><pre class="prettyprint lang-java">public void testSomething() throws Exception { ... catchException(obj).do(); // do() throws a checked exception</pre></code> No, * although the exception is always caught you cannot omit the throws clause in * your test method. * <h3 id="11">11. Can I catch errors instead of exceptions?</h3> * <p> * At the moment you cannot catch {@link Throwable throwables} that are not * {@link Exception exceptions}. But this could be easily changed if someone * wants to get this feature. * * @author rwoo * @since 16.09.2011 */ public class CatchException { /** * Returns the exception caught during the last call on the proxied object * in the current thread. * * @param <E> * This type parameter makes some type casts redundant. * @return Returns the exception caught during the last call on the proxied * object in the current thread - if the call was made through a * proxy that has been created via * {@link #verifyException(Object, Class) verifyException()} or * {@link #catchException(Object, Class) catchException()}. Returns * null the proxy has not caught an exception. Returns null if the * caught exception belongs to a class that is no longer * {@link ClassLoader loaded}. */ public static <E extends Exception> E caughtException() { return ExceptionHolder.<E> get(); } /** * Use it to verify that an exception is thrown and to get access to the * thrown exception (for further verifications). * <p> * The following example verifies that obj.doX() throws a Exception: * <code><pre class="prettyprint lang-java">verifyException(obj).doX(); // catch and verify assert "foobar".equals(caughtException().getMessage()); // further analysis </pre></code> * <p> * If <code>doX()</code> does not throw a <code>Exception</code>, then a * {@link ExceptionNotThrownAssertionError} is thrown. Otherwise the thrown * exception can be retrieved via {@link #caughtException()}. * <p> * * @param <T> * The type of the given <code>obj</code>. * * @param obj * The instance that shall be proxied. Must not be * <code>null</code>. * @return Returns an object that verifies that each invocation on the * underlying object throws an exception. */ public static <T> T verifyException(T obj) { return verifyException(obj, Exception.class); } /** * Use it to verify that an exception of specific type is thrown and to get * access to the thrown exception (for further verifications). * <p> * The following example verifies that obj.doX() throws a MyException: * <code><pre class="prettyprint lang-java">verifyException(obj, MyException.class).doX(); // catch and verify assert "foobar".equals(caughtException().getMessage()); // further analysis </pre></code> * <p> * If <code>doX()</code> does not throw a <code>MyException</code>, then a * {@link ExceptionNotThrownAssertionError} is thrown. Otherwise the thrown * exception can be retrieved via {@link #caughtException()}. * <p> * * @param <T> * The type of the given <code>obj</code>. * * @param <E> * The type of the exception that shall be caught. * @param obj * The instance that shall be proxied. Must not be * <code>null</code>. * @param clazz * The type of the exception that shall be thrown by the * underlying object. Must not be <code>null</code>. * @return Returns an object that verifies that each invocation on the * underlying object throws an exception of the given type. */ public static <T, E extends Exception> T verifyException(T obj, Class<E> clazz) { return processException(obj, clazz, true); } /** * Use it to catch an exception and to get access to the thrown exception * (for further verifications). * <p> * In the following example you catch exceptions that are thrown by * obj.doX(): * <code><pre class="prettyprint lang-java">catchException(obj).doX(); // catch if (caughtException() != null) { assert "foobar".equals(caughtException().getMessage()); // further analysis }</pre></code> * If <code>doX()</code> throws a exception, then {@link #caughtException()} * will return the caught exception. If <code>doX()</code> does not throw a * exception, then {@link #caughtException()} will return <code>null</code>. * <p> * * @param <T> * The type of the given <code>obj</code>. * * @param obj * The instance that shall be proxied. Must not be * <code>null</code>. * @return Returns a proxy for the given object. The proxy catches * exceptions of the given type when a method on the proxy is * called. */ public static <T> T catchException(T obj) { return processException(obj, Exception.class, false); } /** * Use it to catch an exception of a specific type and to get access to the * thrown exception (for further verifications). * <p> * In the following example you catch exceptions of type MyException that * are thrown by obj.doX(): * <code><pre class="prettyprint lang-java">catchException(obj, MyException.class).doX(); // catch if (caughtException() != null) { assert "foobar".equals(caughtException().getMessage()); // further analysis }</pre></code> * If <code>doX()</code> throws a <code>MyException</code>, then * {@link #caughtException()} will return the caught exception. If * <code>doX()</code> does not throw a <code>MyException</code>, then * {@link #caughtException()} will return <code>null</code>. If * <code>doX()</code> throws an exception of another type, i.e. not a * subclass but another class, then this exception is not thrown and * {@link #caughtException()} will return <code>null</code>. * <p> * * @param <T> * The type of the given <code>obj</code>. * * @param <E> * The type of the exception that shall be caught. * @param obj * The instance that shall be proxied. Must not be * <code>null</code>. * @param clazz * The type of the exception that shall be caught. Must not be * <code>null</code>. * @return Returns a proxy for the given object. The proxy catches * exceptions of the given type when a method on the proxy is * called. */ public static <T, E extends Exception> T catchException(T obj, Class<E> clazz) { return processException(obj, clazz, false); } /** * Creates a proxy that processes exceptions thrown by the underlying * object. * <p> * Delegates to * {@link SubclassProxyFactory#createProxy(Class, MethodInterceptor)} which * itself might delegate to * {@link InterfaceOnlyProxyFactory#createProxy(Class, MethodInterceptor)}. */ @SuppressWarnings("javadoc") private static <T, E extends Exception> T processException(T obj, Class<E> exceptionClazz, boolean assertException) { if (obj == null) { throw new IllegalArgumentException("obj must not be null"); } return new SubclassProxyFactory().<T> createProxy(obj.getClass(), new ExceptionProcessingInterceptor<E>(obj, exceptionClazz, assertException)); } /** * Returns a proxy that implements all interfaces of the underlying object. * * @param <T> * must be an interface the object implements * @param obj * the object that created proxy will delegate all calls to * @return Returns a proxy that implements all interfaces of the underlying * object and delegates all calls to that underlying object. */ public static <T> T interfaces(T obj) { if (obj == null) { throw new IllegalArgumentException("obj must not be null"); } return new InterfaceOnlyProxyFactory().<T> createProxy(obj.getClass(), new DelegatingInterceptor(obj)); } /** * Sets the {@link #caughtException() caught exception} to null. This does * not affect exceptions saved at threads other than the current one. * <p> * Actually you probably never need to call this method because each method * call on a proxied object in the current thread resets the caught * exception. But if you want to improve test isolation or if you want to * 'clean up' after testing (to avoid memory leaks), call the method before * or after testing. */ public static void resetCaughtException() { ExceptionHolder.set(null); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import java.lang.reflect.Method; import com.googlecode.catchexception.ExceptionNotThrownAssertionError; /** * This abstract method invocation interceptor * <ul> * <li>delegates all method calls to the 'underlying object', * <li>catches exceptions of a given type, and * <li>(optionally) asserts that an exception of a specific type is thrown. * </ul> * * @author rwoo * @param <E> * The type of the exception that is caught and ,optionally, * verified. * @since 16.09.2011 */ class AbstractExceptionProcessingInvocationHandler<E extends Exception> { /** * See * {@link #AbstractExceptionProcessingInvocationHandler(Object, Class, boolean)} * . */ protected Class<E> clazz; /** * See * {@link #AbstractExceptionProcessingInvocationHandler(Object, Class, boolean)} * . */ protected Object target; /** * See * {@link #AbstractExceptionProcessingInvocationHandler(Object, Class, boolean)} * . */ protected boolean assertException; /** * @param target * The object all method calls are delegated to. Must not be * <code>null</code>. * @param clazz * the type of the exception that is to catch. Must not be * <code>null</code>. * @param assertException * True if the interceptor shall throw an * {@link ExceptionNotThrownAssertionError} if the method has not * thrown an exception of the expected type. */ public AbstractExceptionProcessingInvocationHandler(Object target, Class<E> clazz, boolean assertException) { if (clazz == null) { throw new IllegalArgumentException( "exceptionClazz must not be null"); } if (target == null) { throw new IllegalArgumentException("target must not be null"); } this.clazz = clazz; this.target = target; this.assertException = assertException; } /** * Must be called by the subclass before the intercepted method invocation. */ protected void beforeInvocation() { // clear exception cache ExceptionHolder.set(null); } /** * Must be called by the subclass after the method invocation that has not * thrown a exception. * * @param retval * The value returned by the intercepted method invocation. * @return The value that shall be returned by the proxy. * @throws Error * (optionally) Thrown if the verification failed. */ protected Object afterInvocation(Object retval) throws Error { if (assertException) { throw new ExceptionNotThrownAssertionError(clazz); } else { // return anything. the value does not matter return retval; } } /** * Must be called by the subclass after the intercepted method invocation * that has thrown a exception. * * @param e * the exception thrown by the intercepted method invocation. * @param method * the method that was proxied * @return Always returns null. * @throws Error * Thrown if the verification failed. * @throws Exception * The given exception. (Re-)thrown if the thrown exception * shall not be caught and verification is not required. */ protected Object afterInvocationThrowsException(Exception e, Method method) throws Error, Exception { // is the thrown exception of the expected type? if (!clazz.isAssignableFrom(e.getClass())) { if (assertException) { throw new ExceptionNotThrownAssertionError(clazz, e); } else { throw e; } } else { // save the caught exception for further analysis ExceptionHolder.set(e); // return anything. the value does not matter but null could cause a // NullPointerException while un-boxing return safeReturnValue(method.getReturnType()); } } /** * @param type * a type * @return Returns a value of the given type */ Object safeReturnValue(Class<?> type) { if (!type.isPrimitive()) { return null; } else if (Void.TYPE.equals(type)) { return null; // any value } else if (Byte.TYPE.equals(type)) { return (byte) 0; } else if (Short.TYPE.equals(type)) { return (short) 0; } else if (Integer.TYPE.equals(type)) { return (int) 0; } else if (Long.TYPE.equals(type)) { return (long) 0; } else if (Float.TYPE.equals(type)) { return (float) 0.0; } else if (Double.TYPE.equals(type)) { return (double) 0.0; } else if (Boolean.TYPE.equals(type)) { return (boolean) false; } else if (Character.TYPE.equals(type)) { return (char) ' '; } else { throw new IllegalArgumentException("Type " + type + " is not supported at the moment. Please file a bug."); } } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import java.lang.reflect.Method; import org.mockito.cglib.proxy.MethodInterceptor; import org.mockito.cglib.proxy.MethodProxy; /** * This {@link AbstractExceptionProcessingInvocationHandler} implements * {@link MethodInterceptor} for Mockito's cglib variant. * * @author rwoo * @param <E> * The type of the exception that shall be caught and (optionally) * verified */ public class ExceptionProcessingInterceptor<E extends Exception> extends AbstractExceptionProcessingInvocationHandler<E> implements MethodInterceptor { @SuppressWarnings("javadoc") public ExceptionProcessingInterceptor(Object target, Class<E> clazz, boolean assertException) { super(target, clazz, assertException); } /* * (non-Javadoc) * * @see * org.mockito.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[], * org.mockito.cglib.proxy.MethodProxy) */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { beforeInvocation(); try { Object retval = proxy.invoke(target, args); return afterInvocation(retval); } catch (Exception e) { return afterInvocationThrowsException(e, method); } } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; /** * Marks a proxy as generated by {@link SubclassProxyFactory}. * This is useful for testing. * <p> * EXAMPLE: * <code><pre class="prettyprint lang-java">assert new SubclassProxyFactory(...).createProxy(obj) instanceof SubclassProxy; * </pre></code> * * @author rwoo */ public interface SubclassProxy { // empty by purpose }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import org.mockito.cglib.proxy.MethodInterceptor; /** * Creates proxies. * * @author rwoo * */ interface ProxyFactory { /** * Create a proxy. * * @param <T> * The type parameter makes some casts redundant. * @param targetClass * the class the factory shall create a proxy for * @param interceptor * the method interceptor that shall be applied to all method * calls. * @return Returns the created proxy. */ public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor); }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import java.lang.reflect.Method; import org.mockito.cglib.proxy.MethodInterceptor; import org.mockito.cglib.proxy.MethodProxy; /** * This interceptor delegates the method call to the target object. * * @author rwoo */ public class DelegatingInterceptor implements MethodInterceptor { /** * See {@link #DelegatingInterceptor(Object)}. */ private Object target; /** * @param target * The object all method calls are delegated to. Must not be * <code>null</code>. */ public DelegatingInterceptor(Object target) { this.target = target; } /* * (non-Javadoc) * * @see * org.mockito.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[], * org.mockito.cglib.proxy.MethodProxy) */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return proxy.invoke(target, args); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** This package contains types that do NOT * belong to the public API of project catch-exception. * The types of this package might change * between micro-releases. */ package com.googlecode.catchexception.internal;
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import java.lang.ref.WeakReference; /** * Holds a caught exception {@link ThreadLocal per Thread}. * * @author rwoo * */ public class ExceptionHolder { /** * The container for the most recently caught exception. * <p> * There is no need to use {@link WeakReference weak references} here as all * the code is for testing so that we don't have to care about memory leaks. */ private static final ThreadLocal<Exception> caughtException = new ThreadLocal<Exception>(); /** * Saves the given exception in {@link #caughtException}. * * @param <E> * the type of the caught exception * @param caughtException * the caught exception */ public static <E extends Exception> void set(E caughtException) { ExceptionHolder.caughtException.set(caughtException); } /** * @param <E> * the type of the caught exception * @return Returns the caught exception. Returns null if there is no * exception caught. */ @SuppressWarnings("unchecked") public static <E extends Exception> E get() { return (E) caughtException.get(); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import java.util.HashSet; import java.util.Set; import org.mockito.cglib.proxy.Enhancer; import org.mockito.cglib.proxy.MethodInterceptor; /** * This {@link ProxyFactory} create proxies that implements all interfaces of * the underlying object including the marker interface * {@link InterfaceOnlyProxy}. But in contrast to the proxies created by * {@link SubclassProxyFactory} such a proxy does not subclass the class of the * underlying object. * * @author rwoo */ public class InterfaceOnlyProxyFactory implements ProxyFactory { /* * (non-Javadoc) * * @see * com.googlecode.catchexception.internal.ProxyFactory#createProxy(java. * lang.Class, org.mockito.cglib.proxy.MethodInterceptor) */ @SuppressWarnings("unchecked") public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor) { // get all the interfaces (is there an easier way?) Set<Class<?>> interfaces = new HashSet<Class<?>>(); Class<?> clazz = targetClass; while (true) { for (Class<?> interfaze : clazz.getInterfaces()) { interfaces.add(interfaze); } if (clazz.getSuperclass() == null) { break; } clazz = clazz.getSuperclass(); } interfaces.add(InterfaceOnlyProxy.class); return (T) Enhancer.create(Object.class, interfaces.toArray(new Class<?>[interfaces.size()]), interceptor); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; /** * Marks a proxy as generated by {@link InterfaceOnlyProxyFactory}. This is useful for * testing. * <p> * EXAMPLE: * <code><pre class="prettyprint lang-java">assert new InterfaceOnlyProxyFactory(...).createProxy(obj) instanceof InterfaceOnlyProxy; * </pre></code> * * @author rwoo */ public interface InterfaceOnlyProxy { // empty by purpose }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception.internal; import org.mockito.cglib.proxy.MethodInterceptor; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.creation.jmock.ClassImposterizer; /** * This {@link ProxyFactory} uses Mockito's jmock package to create proxies that * subclass from the target's class. * * @author rwoo */ public class SubclassProxyFactory implements ProxyFactory { /** * That proxy factory is used if this factory cannot be used. */ private ProxyFactory fallbackProxyFactory = new InterfaceOnlyProxyFactory(); /* * (non-Javadoc) * * @see * com.googlecode.catchexception.internal.ProxyFactory#createProxy(java. * lang.Object, java.lang.Class, boolean) */ @SuppressWarnings("unchecked") public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor) { // can we subclass the class of the target? if (!ClassImposterizer.INSTANCE.canImposterise(targetClass)) { // delegate return fallbackProxyFactory.<T> createProxy(targetClass, interceptor); } // create proxy T proxy; try { proxy = (T) ClassImposterizer.INSTANCE.imposterise(interceptor, targetClass); } catch (MockitoException e) { // delegate return fallbackProxyFactory.<T> createProxy(targetClass, interceptor); } return proxy; } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; @SuppressWarnings("javadoc") public class FinalMethodSomethingImpl extends PublicSomethingImpl { public final void doIt() { throw new IllegalArgumentException("test_abfdzuf"); } @Override final public void doThrow() { super.doThrow(); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; @SuppressWarnings("javadoc") public final class FinalSomethingImpl extends PublicSomethingImpl { }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; @SuppressWarnings("javadoc") public class PublicSomethingImpl implements Something { public PublicSomethingImpl() { super(); } public void doNothing() { // } public void doThrow() { throw new UnsupportedOperationException(); } public void doesNotBelongToAnyInterface() { // } public void doThrowAssertionError() { throw new AssertionError(123); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; @SuppressWarnings("javadoc") public class ProtectedSomethingImpl extends PublicSomethingImpl { protected ProtectedSomethingImpl() { super(); } }
Java
/** * Copyright (C) 2011 rwoo@gmx.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.catchexception; @SuppressWarnings("javadoc") public interface Something { public void doNothing(); public void doThrow(); public void doThrowAssertionError(); }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. */ public abstract class GCMBaseIntentService extends IntentService { public static final String TAG = "GCMBaseIntentService"; // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String mSenderId; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour // token used to check intent origin private static final String TOKEN = Long.toBinaryString(sRandom.nextLong()); private static final String EXTRA_TOKEN = "token"; /** * Subclasses must create a public no-arg constructor and pass the * sender id to be used for registration. */ protected GCMBaseIntentService(String senderId) { // name is used as base name for threads, etc. super("GCMIntentService-" + senderId + "-" + (++sCounter)); mSenderId = senderId; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); Log.v(TAG, "Received deleted messages " + "notification: " + total); onDeletedMessages(context, total); } catch (NumberFormatException e) { Log.e(TAG, "GCM returned invalid number of " + "deleted messages: " + sTotal); } } } else { // application is not using the latest GCM library Log.e(TAG, "Received unknown special message: " + messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { // make sure intent was generated by this class, not by a // malicious app. Log.e(TAG, "Received invalid token: " + token); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { GCMRegistrar.internalRegister(context, mSenderId); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { Log.v(TAG, "Releasing wakelock"); sWakeLock.release(); } else { // should never happen during normal workflow Log.e(TAG, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } Log.v(TAG, "Acquiring wakelock"); sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; Log.d(TAG, "Registration error: " + error); // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.putExtra(EXTRA_TOKEN, TOKEN); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { Log.d(TAG, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. */ public final class GCMRegistrar { private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ private static GCMBroadcastReceiver sRetryReceiver; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value GCMConstants#PERMISSION_GCM_INTENTS} permission. * <li>The {@link BroadcastReceiver}(s) handles the 3 GCM intents * ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE}, * {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}, * and {@value GCMConstants#INTENT_FROM_GCM_LIBRARY_RETRY}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length); } Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Found " + receivers.size() + " receivers for action " + action); } // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (! allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { setRetryBroadcastReceiver(context); GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { if (senderIds == null || senderIds.length == 0 ) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } String senders = builder.toString(); Log.v(TAG, "Registering app " + context.getPackageName() + " of senders " + senders); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); intent.putExtra(GCMConstants.EXTRA_SENDER, senders); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { setRetryBroadcastReceiver(context); GCMRegistrar.resetBackoff(context); internalUnregister(context); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { Log.v(TAG, "Unregistering receiver"); context.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; } } static void internalUnregister(Context context) { Log.v(TAG, "Unregistering app " + context.getPackageName() ); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); context.startService(intent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ private static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { sRetryReceiver = new GCMBroadcastReceiver(); String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); // must use a permission that is defined on manifest for sure String permission = category + ".permission.C2D_MESSAGE"; Log.v(TAG, "Registering receiver"); context.registerReceiver(sRetryReceiver, filter, permission, null); } } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { Log.v(TAG, "App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id"); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); Log.v(TAG, "Saving regId on app version " + appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { final SharedPreferences prefs = getGCMPreferences(context); Log.v(TAG, "Setting registered on server status as: " + flag); Editor editor = prefs.edit(); editor.putBoolean(PROPERTY_ON_SERVER, flag); editor.commit(); } /** * Checks whether the device was successfully registered in the server side. */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); return isRegistered; } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(),0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { Log.d(TAG, "resetting backoff for " + context.getPackageName()); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. */ public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to indicate the sender * account (a Google email) that owns the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to get the application * id. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * an error when the registration fails. See constants starting with ERROR_ * for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the {@link #INTENT_FROM_GCM_MESSAGE} intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@link #VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. */ public class GCMBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "GCMBroadcastReceiver"; @Override public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.IOException; /** * Exception thrown when GCM returned an error due to an invalid request. * <p> * This is equivalent to GCM posts that return an HTTP error different of 200. */ public final class InvalidRequestException extends IOException { private final int status; private final String description; public InvalidRequestException(int status) { this(status, null); } public InvalidRequestException(int status, String description) { super(getMessage(status, description)); this.status = status; this.description = description; } private static String getMessage(int status, String description) { StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } return base.toString(); } /** * Gets the HTTP Status Code. */ public int getHttpStatusCode() { return status; } /** * Gets the error description. */ public String getDescription() { return description; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; /** * Result of a GCM message request that returned HTTP status code 200. * * <p> * If the message is successfully created, the {@link #getMessageId()} returns * the message id and {@link #getErrorCodeName()} returns {@literal null}; * otherwise, {@link #getMessageId()} returns {@literal null} and * {@link #getErrorCodeName()} returns the code of the error. * * <p> * There are cases when a request is accept and the message successfully * created, but GCM has a canonical registration id for that device. In this * case, the server should update the registration id to avoid rejected requests * in the future. * * <p> * In a nutshell, the workflow to handle a result is: * <pre> * - Call {@link #getMessageId()}: * - {@literal null} means error, call {@link #getErrorCodeName()} * - non-{@literal null} means the message was created: * - Call {@link #getCanonicalRegistrationId()} * - if it returns {@literal null}, do nothing. * - otherwise, update the server datastore with the new id. * </pre> */ public final class Result implements Serializable { private final String messageId; private final String canonicalRegistrationId; private final String errorCode; static final class Builder { // optional parameters private String messageId; private String canonicalRegistrationId; private String errorCode; public Builder canonicalRegistrationId(String value) { canonicalRegistrationId = value; return this; } public Builder messageId(String value) { messageId = value; return this; } public Builder errorCode(String value) { errorCode = value; return this; } public Result build() { return new Result(this); } } private Result(Builder builder) { canonicalRegistrationId = builder.canonicalRegistrationId; messageId = builder.messageId; errorCode = builder.errorCode; } /** * Gets the message id, if any. */ public String getMessageId() { return messageId; } /** * Gets the canonical registration id, if any. */ public String getCanonicalRegistrationId() { return canonicalRegistrationId; } /** * Gets the error code, if any. */ public String getErrorCodeName() { return errorCode; } @Override public String toString() { StringBuilder builder = new StringBuilder("["); if (messageId != null) { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { builder.append(" canonicalRegistrationId=") .append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); } return builder.append(" ]").toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import com.google.android.gcm.server.Result.Builder; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); protected final Logger logger = Logger.getLogger(getClass().getName()); private final String key; /** * Default constructor. * * @param key API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent, including the device's registration id. * @param registrationId device where the message will be sent. * @param retries number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details) * * @throws IllegalArgumentException if registrationId is {@literal null}. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + registrationId); } result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable. * * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IllegalArgumentException if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = PARAM_PAYLOAD_PREFIX + entry.getKey(); String value = entry.getValue(); addParameter(body, key, URLEncoder.encode(value, UTF8)); } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, requestBody); int status = conn.getResponseCode(); if (status == 503) { logger.fine("GCM service is unavailable"); return null; } if (status != 200) { throw new InvalidRequestException(status); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { String line = reader.readLine(); if (line == null || line.equals("")) { throw new IOException("Received empty response from GCM service."); } String[] responseParts = split(line); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id line = reader.readLine(); if (line != null) { responseParts = split(line); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Received invalid second line from GCM: " + line); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Received invalid response from GCM: " + line); } } finally { reader.close(); } } finally { conn.disconnect(); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent. * @param regIds registration id of the devices that will receive * the message. * @param retries number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult = null; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } multicastResult = sendNoRetry(message, unsentRegIds); long multicastId = multicastResult.getMulticastId(); logger.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); // calculate summary int success = 0, failure = 0 , canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of devices * that should be retried. * * @param unsentRegIds list of devices that are still pending an update. * @param allResults map of status that will be updated. * @param multicastResult result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && error.equals(Constants.ERROR_UNAVAILABLE)) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return {@literal true} if the message was sent successfully, * {@literal false} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if message could not be sent or received. */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); int status = conn.getResponseCode(); String responseBody = getString(conn.getInputStream()); logger.finest("JSON response: " + responseBody); if (status != 200) { throw new InvalidRequestException(status, responseBody); } JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder() .messageId(messageId) .canonicalRegistrationId(canonicalRegId) .errorCode(error) .build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw new IOException("Error parsing JSON response: " + responseBody, e); } catch (CustomParserException e) { throw new IOException("Error parsing JSON response: " + responseBody, e); } } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name initial parameter for the POST. * @param value initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body HTTP POST body * @param name parameter's name * @param value parameter's value */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * * <p> * If the stream ends in a newline character, it will be stripped. */ protected static String getString(InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(nonNull(stream))); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; /** * Constants used on GCM service communication. */ public final class Constants { /** * Endpoint for sending messages. */ public static final String GCM_SEND_ENDPOINT = "https://android.googleapis.com/gcm/send"; /** * HTTP parameter for registration id. */ public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. */ public static final String PARAM_COLLAPSE_KEY = "collapse_key"; /** * HTTP parameter for delaying the message delivery if the device is idle. */ public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; /** * Prefix to HTTP parameter used to pass key-values in the message payload. */ public static final String PARAM_PAYLOAD_PREFIX = "data."; /** * Prefix to HTTP parameter used to set the message time-to-live. */ public static final String PARAM_TIME_TO_LIVE = "time_to_live"; /** * Too many messages sent by the sender. Retry after a while. */ public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded"; /** * Too many messages sent by the sender to a specific device. * Retry after a while. */ public static final String ERROR_DEVICE_QUOTA_EXCEEDED = "DeviceQuotaExceeded"; /** * Missing registration_id. * Sender should always add the registration_id to the request. */ public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration"; /** * Bad registration_id. Sender should remove this registration_id. */ public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration"; /** * The sender_id contained in the registration_id does not match the * sender_id used to register with the GCM servers. */ public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId"; /** * The user has uninstalled the application or turned off notifications. * Sender should stop sending messages to this device and delete the * registration_id. The client needs to re-register with the GCM servers to * receive notifications again. */ public static final String ERROR_NOT_REGISTERED = "NotRegistered"; /** * The payload of the message is too big, see the limitations. * Reduce the size of the message. */ public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig"; /** * Collapse key is required. Include collapse key in the request. */ public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey"; /** * Used to indicate that a particular message could not be sent because * the GCM servers were not available. Used only on JSON requests, as in * plain text requests unavailability is indicated by a 503 response. */ public static final String ERROR_UNAVAILABLE = "Unavailable"; /** * Token returned by GCM when a message was successfully sent. */ public static final String TOKEN_MESSAGE_ID = "id"; /** * Token returned by GCM when the requested registration id has a canonical * value. */ public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; /** * Token returned by GCM when there was an error sending a message. */ public static final String TOKEN_ERROR = "Error"; /** * JSON-only field representing the registration ids. */ public static final String JSON_REGISTRATION_IDS = "registration_ids"; /** * JSON-only field representing the payload data. */ public static final String JSON_PAYLOAD = "data"; /** * JSON-only field representing the number of successful messages. */ public static final String JSON_SUCCESS = "success"; /** * JSON-only field representing the number of failed messages. */ public static final String JSON_FAILURE = "failure"; /** * JSON-only field representing the number of messages with a canonical * registration id. */ public static final String JSON_CANONICAL_IDS = "canonical_ids"; /** * JSON-only field representing the id of the multicast request. */ public static final String JSON_MULTICAST_ID = "multicast_id"; /** * JSON-only field representing the result of each individual request. */ public static final String JSON_RESULTS = "results"; /** * JSON-only field representing the error field of an individual request. */ public static final String JSON_ERROR = "error"; /** * JSON-only field sent by GCM when a message was successfully sent. */ public static final String JSON_MESSAGE_ID = "message_id"; private Constants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * GCM message. * * <p> * Instances of this class are immutable and should be created using a * {@link Builder}. Examples: * * <strong>Simplest message:</strong> * <pre><code> * Message message = new Message.Builder().build(); * </pre></code> * * <strong>Message with optional attributes:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .build(); * </pre></code> * * <strong>Message with optional attributes and payload data:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .addData("key1", "value1") * .addData("key2", "value2") * .build(); * </pre></code> */ public final class Message implements Serializable { private final String collapseKey; private final Boolean delayWhileIdle; private final Integer timeToLive; private final Map<String, String> data; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; public Builder() { this.data = new LinkedHashMap<String, String>(); } /** * Sets the collapseKey property. */ public Builder collapseKey(String value) { collapseKey = value; return this; } /** * Sets the delayWhileIdle property (default value is {@literal false}). */ public Builder delayWhileIdle(boolean value) { delayWhileIdle = value; return this; } /** * Sets the time to live, in seconds. */ public Builder timeToLive(int value) { timeToLive = value; return this; } /** * Adds a key/value pair to the payload data. */ public Builder addData(String key, String value) { data.put(key, value); return this; } public Message build() { return new Message(this); } } private Message(Builder builder) { collapseKey = builder.collapseKey; delayWhileIdle = builder.delayWhileIdle; data = Collections.unmodifiableMap(builder.data); timeToLive = builder.timeToLive; } /** * Gets the collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Gets the delayWhileIdle flag. */ public Boolean isDelayWhileIdle() { return delayWhileIdle; } /** * Gets the time to live (in seconds). */ public Integer getTimeToLive() { return timeToLive; } /** * Gets the payload data, which is immutable. */ public Map<String, String> getData() { return data; } @Override public String toString() { StringBuilder builder = new StringBuilder("Message("); if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); } if (timeToLive != null) { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append(entry.getKey()).append("=").append(entry.getValue()) .append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Result of a GCM multicast message request . */ public final class MulticastResult implements Serializable { private final int success; private final int failure; private final int canonicalIds; private final long multicastId; private final List<Result> results; private final List<Long> retryMulticastIds; static final class Builder { private final List<Result> results = new ArrayList<Result>(); // required parameters private final int success; private final int failure; private final int canonicalIds; private final long multicastId; // optional parameters private List<Long> retryMulticastIds; public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; this.multicastId = multicastId; } public Builder addResult(Result result) { results.add(result); return this; } public Builder retryMulticastIds(List<Long> retryMulticastIds) { this.retryMulticastIds = retryMulticastIds; return this; } public MulticastResult build() { return new MulticastResult(this); } } private MulticastResult(Builder builder) { success = builder.success; failure = builder.failure; canonicalIds = builder.canonicalIds; multicastId = builder.multicastId; results = Collections.unmodifiableList(builder.results); List<Long> tmpList = builder.retryMulticastIds; if (tmpList == null) { tmpList = Collections.emptyList(); } retryMulticastIds = Collections.unmodifiableList(tmpList); } /** * Gets the multicast id. */ public long getMulticastId() { return multicastId; } /** * Gets the number of successful messages. */ public int getSuccess() { return success; } /** * Gets the total number of messages sent, regardless of the status. */ public int getTotal() { return success + failure; } /** * Gets the number of failed messages. */ public int getFailure() { return failure; } /** * Gets the number of successful messages that also returned a canonical * registration id. */ public int getCanonicalIds() { return canonicalIds; } /** * Gets the results of each individual message, which is immutable. */ public List<Result> getResults() { return results; } /** * Gets additional ids if more than one multicast message was sent. */ public List<Long> getRetryMulticastIds() { return retryMulticastIds; } @Override public String toString() { StringBuilder builder = new StringBuilder("MulticastResult(") .append("multicast_id=").append(multicastId).append(",") .append("total=").append(getTotal()).append(",") .append("success=").append(success).append(",") .append("failure=").append(failure).append(",") .append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); StringBuilder status = new StringBuilder(); if (devices.isEmpty()) { status.append("Message ignored as there is no device registered!"); } else { List<Result> results; // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); results = Arrays.asList(result); } else { // send a multicast message using JSON Message message = new Message.Builder().build(); MulticastResult result = sender.send(message, devices, 5); results = result.getResults(); } // analyze the results for (int i = 0; i < devices.size(); i++) { Result result = results.get(i); if (result.getMessageId() != null) { status.append("Succesfully sent message to device #").append(i); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); devices.set(i, canonicalRegId); status.append(". Also updated registration id!"); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it status.append("Unregistered device #").append(i); String regId = devices.get(i); Datastore.unregister(regId); } else { status.append("Error sending message to device #").append(i) .append(": ").append(error); } } status.append("<br/>"); } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); regIds.add(regId); } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); regIds.remove(regId); } /** * Gets all registered devices. */ public static List<String> getDevices() { return regIds; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); @Override public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } @Override public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, needs to check if it is // registered on our server as well. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(context, regId); // At this point all attempts to register with the app // server failed, so we need to unregister the device // from GCM - the app will try to register again when // it is restarted. Note that GCM will send an // unregistered callback upon completion, but // GCMIntentService.onUnregistered() will ignore it. if (!registered) { GCMRegistrar.unregister(context); } return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import static com.google.android.gcm.demo.app.CommonUtilities.TAG; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * * @return whether the registration succeeded or not. */ static boolean register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, context.getString( R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = context.getString(R.string.server_registered); CommonUtilities.displayMessage(context, message); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); CommonUtilities.displayMessage(context, message); return false; } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = context.getString(R.string.server_unregister_error, e.getMessage()); CommonUtilities.displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; /** * {@link IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); if (GCMRegistrar.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, registrationId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. Log.i(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String message = getString(R.string.gcm_message); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_stat_gcm; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, DemoActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/sendMessage").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON String key = Datastore.createMulticast(devices); queue.add(withUrl("/sendMessage").param( SendMessageServlet.PARAMETER_MULTICAST, key)); status = "Multicast message queued for " + devices.size() + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = new Message.Builder().build(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String encodedKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(encodedKey); Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, encodedKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(encodedKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, encodedKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Entity entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Entity entity = findDeviceByRegId(regId); Key key = entity.getKey(); datastore.delete(key); } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); } /** * Gets all registered devices. */ public static List<String> getDevices() { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(); List<String> devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } return devices; } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); Entity entity = preparedQuery.asSingleEntity(); return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); String encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } @Override public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; /** * This {@code WakefulBroadcastReceiver} takes care of creating and managing a * partial wake lock for your app. It passes off the work of processing the GCM * message to an {@code IntentService}, while ensuring that the device does not * go back to sleep in the transition. The {@code IntentService} calls * {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to * release the wake lock. */ public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.util.Log; /** * This {@code IntentService} does the actual handling of the GCM message. * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a * partial wake lock for this service while the service does its work. When the * service is finished, it calls {@code completeWakefulIntent()} to release the * wake lock. */ public class GcmIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GcmIntentService() { super("GcmIntentService"); } public static final String TAG = "GCM Demo"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. sendNotification("Received: " + extras.toString()); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(String msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, DemoActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_gcm) .setContentTitle("GCM Notification") .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** * Substitute you own sender ID here. This is the project number you got * from the API Console, as described in "Getting Started." */ String SENDER_ID = "Your-Sender-ID"; /** * Tag used on log messages. */ static final String TAG = "GCM Demo"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); Context context; String regid; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); context = getApplicationContext(); // Check device for Play Services APK. If check succeeds, proceed with GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } @Override protected void onResume() { super.onResume(); // Check device for Play Services APK. checkPlayServices(); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * Stores the registration ID and the app versionCode in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } /** * Gets the current registration ID for application on GCM service, if there is one. * <p> * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing * registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } // Send an upstream message. public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } } @Override protected void onDestroy() { super.onDestroy(); } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(DemoActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send * messages to your app. Not needed for this demo since the device sends upstream messages * to a server that echoes back the message using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { // Your implementation here. } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is thread-safe but not persistent (it will lost the data when the * app is restarted) - it is meant just as an example. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); synchronized (regIds) { regIds.add(regId); } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); synchronized (regIds) { regIds.remove(regId); } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); synchronized (regIds) { regIds.remove(oldId); regIds.add(newId); } } /** * Gets all registered devices. */ public static List<String> getDevices() { synchronized (regIds) { return new ArrayList<String>(regIds); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private static final int MULTICAST_SIZE = 1000; private Sender sender; private static final Executor threadPool = Executors.newFixedThreadPool(5); @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); status = "Sent message to one device: " + result; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == MULTICAST_SIZE || counter == total) { asyncSend(partialDevices); partialDevices.clear(); tasks++; } } status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } private void asyncSend(List<String> partialDevices) { // make a copy final List<String> devices = new ArrayList<String>(partialDevices); threadPool.execute(new Runnable() { public void run() { Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.send(message, devices, 5); } catch (IOException e) { logger.log(Level.SEVERE, "Error posting messages", e); return; } List<Result> results = multicastResult.getResults(); // analyze the results for (int i = 0; i < devices.size(); i++) { String regId = devices.get(i); Result result = results.get(i); String messageId = result.getMessageId(); if (messageId != null) { logger.fine("Succesfully sent message to device: " + regId + "; messageId = " + messageId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.info("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it logger.info("Unregistered device: " + regId); Datastore.unregister(regId); } else { logger.severe("Error sending message to " + regId + ": " + error); } } } }}); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private Message createMessage() { Message message = new Message.Builder().build(); return message; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = createMessage(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String multicastKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(multicastKey); Message message = createMessage(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, multicastKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, multicastKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/send").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); tasks++; } } status = "Queued tasks to send " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; /** * IntentService responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered, registrationId)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); ServerUtilities.unregister(context, registrationId); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message. Extras: " + intent.getExtras()); String message = getString(R.string.gcm_message); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_stat_gcm; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, DemoActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import static com.google.android.gcm.demo.app.CommonUtilities.TAG; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * */ static void register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, context.getString( R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = context.getString(R.string.server_registered); CommonUtilities.displayMessage(context, message); return; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i + ":" + e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); CommonUtilities.displayMessage(context, message); } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = context.getString(R.string.server_unregister_error, e.getMessage()); CommonUtilities.displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gcm; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to indicate which senders (Google API project ids) can send messages to * the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to get the application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate an error when the registration fails. * See constants starting with ERROR_ for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * to indicate which sender (Google API project id) sent the message. */ public static final String EXTRA_FROM = "from"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.util.Log; /** * Custom logger. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated class GCMLogger { private final String mTag; // can't use class name on TAG since size is limited to 23 chars private final String mLogPrefix; GCMLogger(String tag, String logPrefix) { mTag = tag; mLogPrefix = logPrefix; } /** * Logs a message on logcat. * * @param priority logging priority * @param template message's template * @param args list of arguments */ protected void log(int priority, String template, Object... args) { if (Log.isLoggable(mTag, priority)) { String message = String.format(template, args); Log.println(priority, mTag, mLogPrefix + message); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public abstract class GCMBaseIntentService extends IntentService { /** * Old TAG used for logging. Marked as deprecated since it should have * been private at first place. */ @Deprecated public static final String TAG = "GCMBaseIntentService"; private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService", "[" + getClass().getName() + "]: "); // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; mLogger.log(Log.VERBOSE, "Intent service name: %s", name); } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); mLogger.log(Log.VERBOSE, "Received notification for %d deleted" + "messages", total); onDeletedMessages(context, total); } catch (NumberFormatException e) { mLogger.log(Log.ERROR, "GCM returned invalid " + "number of deleted messages (%d)", sTotal); } } } else { // application is not using the latest GCM library mLogger.log(Log.ERROR, "Received unknown special message: %s", messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String packageOnIntent = intent.getPackage(); if (packageOnIntent == null || !packageOnIntent.equals( getApplicationContext().getPackageName())) { mLogger.log(Log.ERROR, "Ignoring retry intent from another package (%s)", packageOnIntent); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.release(); } else { // should never happen during normal workflow mLogger.log(Log.ERROR, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { GCMRegistrar.cancelAppPendingIntent(); String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, " + "error = %s, unregistered = %s", registrationId, error, unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); mLogger.log(Log.DEBUG, "Scheduling registration retry, backoff = %d (%d)", nextAttempt, backoffTimeMs); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.setPackage(context.getPackageName()); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { mLogger.log(Log.VERBOSE, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public class GCMBroadcastReceiver extends BroadcastReceiver { private static boolean mReceiverSet = false; private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver", "[" + getClass().getName() + "]: "); @Override public final void onReceive(Context context, Intent intent) { mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(context, getClass().getName()); } String className = getGCMIntentServiceClassName(context); mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ // guarded by GCMRegistrar.class private static GCMBroadcastReceiver sRetryReceiver; // guarded by GCMRegistrar.class private static Context sRetryReceiverContext; // guarded by GCMRegistrar.class private static String sRetryReceiverClassName; // guarded by GCMRegistrar.class private static PendingIntent sAppPendingIntent; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} * permission. * <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * and * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } log(context, Log.VERBOSE, "number of receivers for %s: %d", packageName, receivers.length); Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } log(context, Log.VERBOSE, "Found %d receivers for action %s", receivers.size(), action); // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); log(context, Log.VERBOSE, "Registering app for senders %s", flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } static void internalUnregister(Context context) { log(context, Log.VERBOSE, "Unregistering app"); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { log(context, Log.VERBOSE, "Unregistering retry receiver"); sRetryReceiverContext.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; sRetryReceiverContext = null; } } static synchronized void cancelAppPendingIntent() { if (sAppPendingIntent != null) { sAppPendingIntent.cancel(); sAppPendingIntent = null; } } private synchronized static void setPackageNameExtra(Context context, Intent intent) { if (sAppPendingIntent == null) { log(context, Log.VERBOSE, "Creating pending intent to get package name"); sAppPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0); } intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, sAppPendingIntent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen log(context, Log.ERROR, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { log(context, Log.ERROR, "Could not create instance of %s. " + "Using %s directly.", sRetryReceiverClassName, GCMBroadcastReceiver.class.getName()); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); log(context, Log.VERBOSE, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(Context context, String className) { log(context, Log.VERBOSE, "Setting the name of retry receiver class to %s", className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { log(context, Log.VERBOSE, "App version changed from %d to %d;" + "resetting registration id", oldVersion, newVersion); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * <p>As a side-effect, it also expires the registeredOnServer property. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { setRegisteredOnServer(context, null, 0); return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; setRegisteredOnServer(context, flag, expirationTime); } private static void setRegisteredOnServer(Context context, Boolean flag, long expirationTime) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); if (flag != null) { editor.putBoolean(PROPERTY_ON_SERVER, flag); log(context, Log.VERBOSE, "Setting registeredOnServer flag as %b until %s", flag, new Timestamp(expirationTime)); } else { log(context, Log.VERBOSE, "Setting registeredOnServer expiration to %s", new Timestamp(expirationTime)); } editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { log(context, Log.VERBOSE, "flag expired on: %s", new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { log(context, Log.VERBOSE, "Resetting backoff"); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } /** * Logs a message on logcat. * * @param context application's context. * @param priority logging priority * @param template message's template * @param args list of arguments */ private static void log(Context context, int priority, String template, Object... args) { if (Log.isLoggable(TAG, priority)) { String message = String.format(template, args); Log.println(priority, TAG, "[" + context.getPackageName() + "]: " + message); } } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * GCM message. * * <p> * Instances of this class are immutable and should be created using a * {@link Builder}. Examples: * * <strong>Simplest message:</strong> * <pre><code> * Message message = new Message.Builder().build(); * </pre></code> * * <strong>Message with optional attributes:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .build(); * </pre></code> * * <strong>Message with optional attributes and payload data:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .addData("key1", "value1") * .addData("key2", "value2") * .build(); * </pre></code> */ public final class Message implements Serializable { private final String collapseKey; private final Boolean delayWhileIdle; private final Integer timeToLive; private final Map<String, String> data; private final Boolean dryRun; private final String restrictedPackageName; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; private Boolean dryRun; private String restrictedPackageName; public Builder() { this.data = new LinkedHashMap<String, String>(); } /** * Sets the collapseKey property. */ public Builder collapseKey(String value) { collapseKey = value; return this; } /** * Sets the delayWhileIdle property (default value is {@literal false}). */ public Builder delayWhileIdle(boolean value) { delayWhileIdle = value; return this; } /** * Sets the time to live, in seconds. */ public Builder timeToLive(int value) { timeToLive = value; return this; } /** * Adds a key/value pair to the payload data. */ public Builder addData(String key, String value) { data.put(key, value); return this; } /** * Sets the dryRun property (default value is {@literal false}). */ public Builder dryRun(boolean value) { dryRun = value; return this; } /** * Sets the restrictedPackageName property. */ public Builder restrictedPackageName(String value) { restrictedPackageName = value; return this; } public Message build() { return new Message(this); } } private Message(Builder builder) { collapseKey = builder.collapseKey; delayWhileIdle = builder.delayWhileIdle; data = Collections.unmodifiableMap(builder.data); timeToLive = builder.timeToLive; dryRun = builder.dryRun; restrictedPackageName = builder.restrictedPackageName; } /** * Gets the collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Gets the delayWhileIdle flag. */ public Boolean isDelayWhileIdle() { return delayWhileIdle; } /** * Gets the time to live (in seconds). */ public Integer getTimeToLive() { return timeToLive; } /** * Gets the dryRun flag. */ public Boolean isDryRun() { return dryRun; } /** * Gets the restricted package name. */ public String getRestrictedPackageName() { return restrictedPackageName; } /** * Gets the payload data, which is immutable. */ public Map<String, String> getData() { return data; } @Override public String toString() { StringBuilder builder = new StringBuilder("Message("); if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); } if (timeToLive != null) { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (dryRun != null) { builder.append("dryRun=").append(dryRun).append(", "); } if (restrictedPackageName != null) { builder.append("restrictedPackageName=").append(restrictedPackageName).append(", "); } if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append(entry.getKey()).append("=").append(entry.getValue()) .append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.IOException; /** * Exception thrown when GCM returned an error due to an invalid request. * <p> * This is equivalent to GCM posts that return an HTTP error different of 200. */ public final class InvalidRequestException extends IOException { private final int status; private final String description; public InvalidRequestException(int status) { this(status, null); } public InvalidRequestException(int status, String description) { super(getMessage(status, description)); this.status = status; this.description = description; } private static String getMessage(int status, String description) { StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } return base.toString(); } /** * Gets the HTTP Status Code. */ public int getHttpStatusCode() { return status; } /** * Gets the error description. */ public String getDescription() { return description; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import com.google.android.gcm.server.Result.Builder; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); protected static final Logger logger = Logger.getLogger(Sender.class.getName()); private final String key; /** * Default constructor. * * @param key API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent, including the device's registration id. * @param registrationId device where the message will be sent. * @param retries number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details). * * @throws IllegalArgumentException if registrationId is {@literal null}. * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IOException if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + registrationId); } result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent. * @param regIds registration id of the devices that will receive * the message. * @param retries number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { multicastResult = null; attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } try { multicastResult = sendNoRetry(message, unsentRegIds); } catch(IOException e) { // no need for WARNING since exception might be already logged logger.log(Level.FINEST, "IOException on attempt " + attempt, e); } if (multicastResult != null) { long multicastId = multicastResult.getMulticastId(); logger.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; } else { tryAgain = attempt <= retries; } if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (multicastIds.isEmpty()) { // all JSON posts failed due to GCM unavailability throw new IOException("Could not post JSON requests to GCM after " + attempt + " attempts"); } // calculate summary int success = 0, failure = 0 , canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of devices * that should be retried. * * @param unsentRegIds list of devices that are still pending an update. * @param allResults map of status that will be updated. * @param multicastResult result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE) || error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch(IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder() .messageId(messageId) .canonicalRegistrationId(canonicalRegId) .errorCode(error) .build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } } private IOException newIoException(String responseBody, Exception e) { // log exception, as IOException constructor that takes a message and cause // is only available on Java 6 String msg = "Error parsing JSON response (" + responseBody + ")"; logger.log(Level.WARNING, msg, e); return new IOException(msg + ":" + e); } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore error logger.log(Level.FINEST, "IOException closing stream", e); } } } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } /** * Makes an HTTP POST request to a given endpoint. * * <p> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * * @return the underlying connection. * * @throws IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name initial parameter for the POST. * @param value initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body HTTP POST body. * @param name parameter's name. * @param value parameter's value. */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * <p> * If the stream ends in a newline character, it will be stripped. * <p> * If the stream is {@literal null}, returns an empty string. */ protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } private static String getAndClose(InputStream stream) throws IOException { try { return getString(stream); } finally { if (stream != null) { close(stream); } } } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; /** * Result of a GCM message request that returned HTTP status code 200. * * <p> * If the message is successfully created, the {@link #getMessageId()} returns * the message id and {@link #getErrorCodeName()} returns {@literal null}; * otherwise, {@link #getMessageId()} returns {@literal null} and * {@link #getErrorCodeName()} returns the code of the error. * * <p> * There are cases when a request is accept and the message successfully * created, but GCM has a canonical registration id for that device. In this * case, the server should update the registration id to avoid rejected requests * in the future. * * <p> * In a nutshell, the workflow to handle a result is: * <pre> * - Call {@link #getMessageId()}: * - {@literal null} means error, call {@link #getErrorCodeName()} * - non-{@literal null} means the message was created: * - Call {@link #getCanonicalRegistrationId()} * - if it returns {@literal null}, do nothing. * - otherwise, update the server datastore with the new id. * </pre> */ public final class Result implements Serializable { private final String messageId; private final String canonicalRegistrationId; private final String errorCode; public static final class Builder { // optional parameters private String messageId; private String canonicalRegistrationId; private String errorCode; public Builder canonicalRegistrationId(String value) { canonicalRegistrationId = value; return this; } public Builder messageId(String value) { messageId = value; return this; } public Builder errorCode(String value) { errorCode = value; return this; } public Result build() { return new Result(this); } } private Result(Builder builder) { canonicalRegistrationId = builder.canonicalRegistrationId; messageId = builder.messageId; errorCode = builder.errorCode; } /** * Gets the message id, if any. */ public String getMessageId() { return messageId; } /** * Gets the canonical registration id, if any. */ public String getCanonicalRegistrationId() { return canonicalRegistrationId; } /** * Gets the error code, if any. */ public String getErrorCodeName() { return errorCode; } @Override public String toString() { StringBuilder builder = new StringBuilder("["); if (messageId != null) { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { builder.append(" canonicalRegistrationId=") .append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); } return builder.append(" ]").toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Result of a GCM multicast message request . */ public final class MulticastResult implements Serializable { private final int success; private final int failure; private final int canonicalIds; private final long multicastId; private final List<Result> results; private final List<Long> retryMulticastIds; public static final class Builder { private final List<Result> results = new ArrayList<Result>(); // required parameters private final int success; private final int failure; private final int canonicalIds; private final long multicastId; // optional parameters private List<Long> retryMulticastIds; public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; this.multicastId = multicastId; } public Builder addResult(Result result) { results.add(result); return this; } public Builder retryMulticastIds(List<Long> retryMulticastIds) { this.retryMulticastIds = retryMulticastIds; return this; } public MulticastResult build() { return new MulticastResult(this); } } private MulticastResult(Builder builder) { success = builder.success; failure = builder.failure; canonicalIds = builder.canonicalIds; multicastId = builder.multicastId; results = Collections.unmodifiableList(builder.results); List<Long> tmpList = builder.retryMulticastIds; if (tmpList == null) { tmpList = Collections.emptyList(); } retryMulticastIds = Collections.unmodifiableList(tmpList); } /** * Gets the multicast id. */ public long getMulticastId() { return multicastId; } /** * Gets the number of successful messages. */ public int getSuccess() { return success; } /** * Gets the total number of messages sent, regardless of the status. */ public int getTotal() { return success + failure; } /** * Gets the number of failed messages. */ public int getFailure() { return failure; } /** * Gets the number of successful messages that also returned a canonical * registration id. */ public int getCanonicalIds() { return canonicalIds; } /** * Gets the results of each individual message, which is immutable. */ public List<Result> getResults() { return results; } /** * Gets additional ids if more than one multicast message was sent. */ public List<Long> getRetryMulticastIds() { return retryMulticastIds; } @Override public String toString() { StringBuilder builder = new StringBuilder("MulticastResult(") .append("multicast_id=").append(multicastId).append(",") .append("total=").append(getTotal()).append(",") .append("success=").append(success).append(",") .append("failure=").append(failure).append(",") .append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; /** * Constants used on GCM service communication. */ public final class Constants { /** * Endpoint for sending messages. */ public static final String GCM_SEND_ENDPOINT = "https://android.googleapis.com/gcm/send"; /** * HTTP parameter for registration id. */ public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. */ public static final String PARAM_COLLAPSE_KEY = "collapse_key"; /** * HTTP parameter for delaying the message delivery if the device is idle. */ public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; /** * HTTP parameter for telling gcm to validate the message without actually sending it. */ public static final String PARAM_DRY_RUN = "dry_run"; /** * HTTP parameter for package name that can be used to restrict message delivery by matching * against the package name used to generate the registration id. */ public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; /** * Prefix to HTTP parameter used to pass key-values in the message payload. */ public static final String PARAM_PAYLOAD_PREFIX = "data."; /** * Prefix to HTTP parameter used to set the message time-to-live. */ public static final String PARAM_TIME_TO_LIVE = "time_to_live"; /** * Too many messages sent by the sender. Retry after a while. */ public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded"; /** * Too many messages sent by the sender to a specific device. * Retry after a while. */ public static final String ERROR_DEVICE_QUOTA_EXCEEDED = "DeviceQuotaExceeded"; /** * Missing registration_id. * Sender should always add the registration_id to the request. */ public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration"; /** * Bad registration_id. Sender should remove this registration_id. */ public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration"; /** * The sender_id contained in the registration_id does not match the * sender_id used to register with the GCM servers. */ public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId"; /** * The user has uninstalled the application or turned off notifications. * Sender should stop sending messages to this device and delete the * registration_id. The client needs to re-register with the GCM servers to * receive notifications again. */ public static final String ERROR_NOT_REGISTERED = "NotRegistered"; /** * The payload of the message is too big, see the limitations. * Reduce the size of the message. */ public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig"; /** * Collapse key is required. Include collapse key in the request. */ public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey"; /** * A particular message could not be sent because the GCM servers were not * available. Used only on JSON requests, as in plain text requests * unavailability is indicated by a 503 response. */ public static final String ERROR_UNAVAILABLE = "Unavailable"; /** * A particular message could not be sent because the GCM servers encountered * an error. Used only on JSON requests, as in plain text requests internal * errors are indicated by a 500 response. */ public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; /** * Time to Live value passed is less than zero or more than maximum. */ public static final String ERROR_INVALID_TTL= "InvalidTtl"; /** * Token returned by GCM when a message was successfully sent. */ public static final String TOKEN_MESSAGE_ID = "id"; /** * Token returned by GCM when the requested registration id has a canonical * value. */ public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; /** * Token returned by GCM when there was an error sending a message. */ public static final String TOKEN_ERROR = "Error"; /** * JSON-only field representing the registration ids. */ public static final String JSON_REGISTRATION_IDS = "registration_ids"; /** * JSON-only field representing the payload data. */ public static final String JSON_PAYLOAD = "data"; /** * JSON-only field representing the number of successful messages. */ public static final String JSON_SUCCESS = "success"; /** * JSON-only field representing the number of failed messages. */ public static final String JSON_FAILURE = "failure"; /** * JSON-only field representing the number of messages with a canonical * registration id. */ public static final String JSON_CANONICAL_IDS = "canonical_ids"; /** * JSON-only field representing the id of the multicast request. */ public static final String JSON_MULTICAST_ID = "multicast_id"; /** * JSON-only field representing the result of each individual request. */ public static final String JSON_RESULTS = "results"; /** * JSON-only field representing the error field of an individual request. */ public static final String JSON_ERROR = "error"; /** * JSON-only field sent by GCM when a message was successfully sent. */ public static final String JSON_MESSAGE_ID = "message_id"; private Constants() { throw new UnsupportedOperationException(); } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Entity implementation class for Entity: Page * */ @Entity @Table(name = "page") @NamedQueries({ @NamedQuery(name = "Page.findByPacode", query = "SELECT p FROM Page p WHERE p.pacode = :pacode") }) public class Page implements Serializable { private static final long serialVersionUID = -496450448502306401L; @Id @Column(name="pacode") @GeneratedValue(strategy = GenerationType.SEQUENCE) @OneToMany(mappedBy = "page", cascade={CascadeType.PERSIST}) private int pacode; @Column(name = "description", nullable = false, length = 50) private String description; public Page() { } public Page(String page) { this.description = page; } public int getPacode() { return this.pacode; } public void setPacode(int pacode) { this.pacode = pacode; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Page other = (Page) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "person") @NamedQueries({ @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"), @NamedQuery(name = "Person.findByDocument", query = "SELECT p FROM Person p WHERE p.document = :document") }) public class Person implements Serializable { private static final long serialVersionUID = -1763248351730477102L; public Person(){ this.setAddress(new Address()); this.setPersonType(new PersonType()); this.setBirthDate(new Date()); } @Id @Column(name = "document", length = 14) @OneToMany(mappedBy="person", cascade = {CascadeType.PERSIST}) private String document; @Column(name = "name", nullable = false, length = 80) private String name; @ManyToOne @JoinColumn(name = "adcode", nullable = false) private Address address; @ManyToOne @JoinColumn(name = "ptcode", nullable = false) private PersonType personType; @Column(name = "addressNumber") private int addressNumber; @Column(name = "complement", length = 50) private String complement; @Temporal(TemporalType.DATE) @Column(name = "birthDate", nullable = false) private Date birthDate; @Column(name = "phone1", length = 12) private String phone1; @Column(name = "phone2", length = 12) private String phone2; @Column(name = "email", length = 80) private String email; public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public PersonType getPersonType() { return personType; } public void setPersonType(PersonType personType) { this.personType = personType; } public int getAddressNumber() { return addressNumber; } public void setAddressNumber(int addressNumber) { this.addressNumber = addressNumber; } public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((document == null) ? 0 : document.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (document == null) { if (other.document != null) return false; } else if (!document.equals(other.document)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "neighborhood") @NamedQueries(value = { @NamedQuery(name = "Neighborhood.getNeighborhoodList", query = "SELECT n FROM Neighborhood n"), @NamedQuery(name = "Neighborhood.getNeighborhoodByNhcode", query = "SELECT n FROM Neighborhood n WHERE n.nhcode = :nhcode") }) public class Neighborhood implements Serializable { private static final long serialVersionUID = -6548967225000019436L; public Neighborhood() { this.setName(""); this.setCity(new City()); } @Id @Column(name="nhcode") @OneToMany(mappedBy="neighborhood") private int nhcode; @ManyToOne @JoinColumn(name="cicode", nullable=false) private City city; @Column(name="name", nullable=false, length=72) private String name; public int getNhcode() { return nhcode; } public void setNhcode(int nhcode) { this.nhcode = nhcode; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nhcode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Neighborhood other = (Neighborhood) obj; if (nhcode != other.nhcode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "product") @NamedQueries(value = { @NamedQuery(name = "Product.getProductList", query = "SELECT p FROM Product p"), @NamedQuery(name = "Product.getProductListWhereReturnIsNull", query = "SELECT p FROM Product p WHERE p.returnDate IS NULL"), @NamedQuery(name = "Product.getProductByBarcode", query = "SELECT p FROM Product p WHERE p.barcode = :barcode"), @NamedQuery(name = "Product.getProductByNumber", query = "SELECT p FROM Product p WHERE p.proNumber = :proNumber"), @NamedQuery(name = "Product.getProductByCover", query = "SELECT p FROM Product p WHERE p.cover = :cover"), @NamedQuery(name = "Product.getProductByBarcodeAndNumber", query = "SELECT p FROM Product p WHERE p.barcode = :barcode AND p.proNumber= :proNumber") }) public class Product implements Serializable { private static final long serialVersionUID = 5405728628984307490L; public Product(){ this.setDistributor(new Distributor()); this.setGenre(new Genre()); this.setPublisher(new Publisher()); this.setReceiptDate(new Date()); this.setReturnDate(new Date()); } @Id @Column(name="prcode") @OneToMany(mappedBy="product") @GeneratedValue(strategy=GenerationType.SEQUENCE) private long prcode; @Column(name = "barcode", length = 23, nullable = false) private String barcode; @Column(name = "pronumber", length = 5, nullable = true) private String proNumber; @Column(name = "name", nullable = false, length = 50) private String name; @Column(name = "cover", nullable = false, length = 100) private String cover; @Column(name = "price", nullable = false, precision = 10, scale=2) private BigDecimal price; @Column(name = "qtd", nullable = false) private int qtd; @Column(name = "receivedQtd", nullable = false) private int receivedQtd; @Temporal(TemporalType.DATE) @Column(name = "receiptDate", nullable = false) private Date receiptDate; @Temporal(TemporalType.DATE) @Column(name = "returnDate", nullable = true) private Date returnDate; @ManyToOne @JoinColumn(name = "pucode", nullable = true) private Publisher publisher; @ManyToOne @JoinColumn(name = "dicode", nullable = true) private Distributor distributor; @ManyToOne @JoinColumn(name = "gecode", nullable = true) private Genre genre; public long getPrcode() { return prcode; } public void setPrcode(long prcode) { this.prcode = prcode; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getProNumber() { return proNumber; } public void setProNumber(String proNumber) { this.proNumber = proNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public int getQtd() { return qtd; } public void setQtd(int qtd) { this.qtd = qtd; } public int getReceivedQtd() { return receivedQtd; } public void setReceivedQtd(int receivedQtd) { this.receivedQtd = receivedQtd; } public Date getReceiptDate() { return receiptDate; } public void setReceiptDate(Date receiptDate) { this.receiptDate = receiptDate; } public Date getReturnDate() { return returnDate; } public void setReturnDate(Date returnDate) { this.returnDate = returnDate; } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } public Distributor getDistributor() { return distributor; } public void setDistributor(Distributor distributor) { this.distributor = distributor; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((barcode == null) ? 0 : barcode.hashCode()); result = prime * result + ((proNumber == null) ? 0 : proNumber.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Product other = (Product) obj; if (barcode == null) { if (other.barcode != null) return false; } else if (!barcode.equals(other.barcode)) return false; if (proNumber == null) { if (other.proNumber != null) return false; } else if (!proNumber.equals(other.proNumber)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "distributor") @NamedQueries(value = { @NamedQuery(name = "Distributor.getDistributorList", query = "SELECT d FROM Distributor d"), @NamedQuery(name = "Distributor.getDistributorByDicode", query = "SELECT d FROM Distributor d WHERE d.dicode = :dicode") }) public class Distributor implements Serializable { private static final long serialVersionUID = -5032574662192861153L; public Distributor() { this.setDicode(0); this.setPerson(new Person()); } @Id @Column(name = "dicode") @OneToMany(mappedBy = "distributor") @GeneratedValue(strategy = GenerationType.SEQUENCE) private int dicode; @OneToOne(cascade = {CascadeType.PERSIST}) @JoinColumn(name = "document", nullable = false) private Person person; @Column(name = "segment", length = 50) private String segment; public String getSegment() { return segment; } public void setSegment(String segment) { this.segment = segment; } public int getDicode() { return dicode; } public void setDicode(int dicode) { this.dicode = dicode; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getFormattedDocument() { return this.person.getDocument().substring(0, 2) + "." + this.person.getDocument().substring(2, 5) + "." + this.person.getDocument().substring(5, 8) + "/" + this.person.getDocument().substring(8, 11) + "-" + this.person.getDocument().substring(11, 12); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + dicode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Distributor other = (Distributor) obj; if (dicode != other.dicode) return false; return true; } }
Java