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