/src/com/foursquare/examples/push/PushHandler.java

http://github.com/zackzachariah/Foursquare-Welcome-Screen · Java · 71 lines · 52 code · 10 blank · 9 comment · 11 complexity · 7eca7865d37d425755b33cd6dc2dfc68 MD5 · raw file

  1. package com.foursquare.examples.push;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import java.util.logging.Logger;
  5. import javax.jdo.PersistenceManager;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.json.JSONException;
  10. import org.json.JSONObject;
  11. import com.foursquare.examples.push.models.ChannelRecord;
  12. import com.foursquare.examples.push.util.Common;
  13. /**
  14. * The landing point for pushes from foursquare. Ensures that the push secret value is correct,
  15. * then parses the JSON and pushes the results out to the approrpiate clients.
  16. */
  17. @SuppressWarnings("serial")
  18. public class PushHandler extends HttpServlet {
  19. private static final Logger log = Logger.getLogger(PushHandler.class.getName());
  20. public void doPost(HttpServletRequest req, HttpServletResponse resp)
  21. throws IOException {
  22. String pushSecret = req.getParameter("secret");
  23. String pushBody = req.getParameter("checkin");
  24. log.info("Push received: " + pushBody);
  25. if (pushSecret != null && pushBody != null && pushSecret.equals(Common.PUSH_SECRET)) {
  26. try {
  27. handlePush(pushBody);
  28. } catch (JSONException e) {
  29. log.warning("Had a terrible run-in with invalid JSON!\n" + e.getMessage()
  30. + "\n" + pushBody);
  31. }
  32. }
  33. }
  34. // Parse the json and send the messages.
  35. private void handlePush(String pushBody) throws JSONException {
  36. JSONObject pushJson = new JSONObject(pushBody);
  37. // Read out the isMayor flag. This is so complicated since it could be not present if false.
  38. // If it isn't present, a JSON exception is thrown. So, we catch that and make it false.
  39. boolean isMayor = false;
  40. try {
  41. Boolean mayorness = pushJson.getBoolean("isMayor");
  42. isMayor = (mayorness != null && mayorness);
  43. } catch (JSONException e) { isMayor = false; }
  44. // Load in the required information. These will throw an exception if missing, which is OK
  45. // since we couldn't continue if any of them aren't there.
  46. String vid = pushJson.getJSONObject("venue").getString("id");
  47. JSONObject user = pushJson.getJSONObject("user");
  48. String name = user.getString("firstName");
  49. String photo = user.getString("photo");
  50. photo.replace("_thumbs", "");
  51. if (vid != null && name != null) {
  52. PersistenceManager pm = Common.getPM();
  53. try {
  54. List<String> targetClients = ChannelRecord.loadOrCreate(pm, vid).clientIds();
  55. Common.sendUpdate(targetClients, Common.checkinToJson(name, photo, isMayor));
  56. } finally {
  57. pm.close();
  58. }
  59. }
  60. }
  61. }