/** For debug - and possibly show the info, allow device selection. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { GeatteRegisterRequestInfo reqInfo = GeatteRegisterRequestInfo.processRequest(req, resp, getServletContext()); if (reqInfo == null) { return; } resp.setContentType("application/json"); JSONObject regs = new JSONObject(); try { regs.put("userEmail", reqInfo.getUserEmail()); JSONArray devices = new JSONArray(); for (DeviceInfo di : reqInfo.devices) { JSONObject dijson = new JSONObject(); dijson.put("key", di.getKey().toString()); dijson.put("deviceName", di.getDeviceName()); dijson.put("type", di.getType()); dijson.put("registrationId", di.getDeviceRegistrationID()); dijson.put("timestamp", di.getRegistrationTimestamp()); devices.put(dijson); } regs.put("devices", devices); PrintWriter out = resp.getWriter(); regs.write(out); } catch (JSONException e) { throw new IOException(e); } }
public static String sendMessage(ServletContext context, String recipient, String message) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String sender = "nobody"; if (user != null) { sender = user.getEmail(); } log.info("sendMessage: sender = " + sender); log.info("sendMessage: recipient = " + recipient); log.info("sendMessage: message = " + message); // ok = we sent to at least one device. boolean ok = false; // Send push message to phone C2DMessaging push = C2DMessaging.get(context); boolean res = false; String collapseKey = "" + message.hashCode(); // delete will fail if the pm is different than the one used to // load the object - we must close the object when we're done List<DeviceInfo> registrations = null; registrations = DeviceInfo.getDeviceInfoForUser(recipient); log.info("sendMessage: got " + registrations.size() + " registrations"); // Deal with upgrades and multi-device: // If user has one device with an old version and few new ones - // the old registration will be deleted. if (registrations.size() > 1) { // Make sure there is no 'bare' registration // Keys are sorted - check the first DeviceInfo first = registrations.get(0); Key oldKey = first.getKey(); if (oldKey.toString().indexOf("#") < 0) { // multiple devices, first is old-style. registrations.remove(0); // don't send to it pm.deletePersistent(first); } } int numSendAttempts = 0; for (DeviceInfo deviceInfo : registrations) { if (!"ac2dm".equals(deviceInfo.getType())) { continue; // user-specified device type } res = doSendViaC2dm(message, sender, push, collapseKey, deviceInfo); numSendAttempts++; if (res) { ok = true; } } if (ok) { return "Success: Message sent"; } else if (numSendAttempts == 0) { return "Failure: User " + recipient + " not registered"; } else { return "Failure: Unable to send message"; } } catch (Exception e) { return "Failure: Got exception " + e; } finally { pm.close(); } }