public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    final String query = req.getParameter(APIConstants.QUERY);
    double lat = 0.0;
    double lng = 0.0;
    int maxDistance = 2000;
    int maxResults = 20;
    String[] searchTerms = {};

    // Get lat and long
    try {
      lat = Double.parseDouble(req.getParameter(APIConstants.LAT));
      lng = Double.parseDouble(req.getParameter(APIConstants.LNG));
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    // Preset Defaults
    try {
      maxDistance = Integer.parseInt(req.getParameter(APIConstants.DISTANCE));
      maxResults = Integer.parseInt(req.getParameter(APIConstants.LIMIT));
    } catch (Exception e) {
      // No big deal, defaults set
    }

    if (null != query && !query.isEmpty()) searchTerms = query.split(" ");

    List<RestaurantLite> restaurants =
        ConvertToLite.convertRestaurants(
            TDQueryUtils.searchGeoItems(
                searchTerms, new Point(lat, lng), maxResults, maxDistance, new Restaurant()));

    if (!restaurants.isEmpty()) {
      final JSONArray jsonArray = new JSONArray();

      // Traverse each restaurant
      for (final RestaurantLite r : restaurants) {
        try {
          // Put it in the array
          jsonArray.put(new JSONObject(new Gson().toJson(r)));
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }

      // Write success with Array
      resp.getWriter()
          .write(APIUtils.generateJSONSuccessMessage(RestaurantConstants.RESTAURANTS, jsonArray));
    } else resp.getWriter().write(APIUtils.generateJSONFailureMessage("No restaurants found."));
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // Get the writer
    PrintWriter writer = resp.getWriter();

    // Grab the IP Address from the Request
    final String ipAddress = req.getRemoteAddr();
    // final String ipAddress = "24.205.94.144";

    // Check that it is not null or empty
    if (null != ipAddress && !ipAddress.isEmpty()) {
      try {

        if (DEBUG) System.out.println("Looking up Ip: " + ipAddress);

        // Get the Address as a TDPoint
        final TDPoint point = GeoUtils.reverseIP(ipAddress);

        if (DEBUG) System.out.println(point.toString());

        // Convert to JSON Object
        final JSONObject json = new JSONObject(new Gson().toJson(point));

        // Send JSON to User
        writer.write(APIUtils.generateJSONSuccessMessage(json));
        writer.flush();
        writer.close();

      } catch (Exception e) {
        e.printStackTrace();
        writer.write(APIUtils.generateJSONFailureMessage(e));
        writer.flush();
        writer.close();
      }

    } else {

      // Inform user, IP Address was not found
      writer.write(APIUtils.generateJSONFailureMessage("No IpAddress Was Found"));
      writer.flush();
      writer.close();
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // topdish1.appspot.com/api/dishDetail?id[]=1&id[]=2&id[]=5...

    String[] ids = req.getParameterValues(APIConstants.ID_ARRAY);
    Set<Key> dishKeys = new HashSet<Key>();

    for (int i = 0; i < ids.length; i++) {
      try {
        Long id = Long.parseLong(ids[i]);
        dishKeys.add(KeyFactory.createKey(Dish.class.getSimpleName(), id));
      } catch (NumberFormatException e) {
        // malformed input
      } catch (JDOObjectNotFoundException e) {
        // object not found, skipping
      }
    }

    final Set<Dish> dishes = Datastore.get(dishKeys);
    final Set<DishLite> dishLites = ConvertToLite.convertDishes(dishes);

    if (!dishLites.isEmpty()) {
      final JSONArray array = new JSONArray();

      // Traverse dishes
      for (final DishLite dish : dishLites) {
        try {
          // Put a new JSONObject of the Dish in the Array
          array.put(new JSONObject(new Gson().toJson(dish)));

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      // Return array (empty or not)
      resp.getWriter().write(APIUtils.generateJSONSuccessMessage(DishConstants.DISHES, array));
    } else resp.getWriter().write(APIUtils.generateJSONFailureMessage("No dishes found"));
  }
  /**
   * Handles both a POST and a GET <br>
   * Note: This is required as the POST will come from a Mobile User, where as the GET will occur on
   * redirect from Google Auth
   *
   * @param req - the request
   * @param resp - the response
   * @throws ServletException
   * @throws IOException
   */
  private void doLogic(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // Get Writer
    final PrintWriter pw = resp.getWriter();

    try {

      // Get redirection url
      final String redirect = req.getParameter(APIConstants.REDIRECT);

      Logger.getLogger(TAG).info("Final Redirection is: " + redirect);

      // If login was successful (or user is already logged in)
      if (TDUserService.isGoogleUser(req)) {
        Logger.getLogger(TAG).info("User logged in, redirecting to: " + redirect);

        try {

          TDUser user = null;

          try {
            // Get the user
            user = TDUserService.getUser(req.getSession());
          } catch (Exception e) {

            Logger.getLogger(TAG).info(e.getMessage() + " means no user.");
          }

          if (null == user) {
            Logger.getLogger(TAG).info("No user exists, creating a new user");
            final User gUser = UserServiceFactory.getUserService().getCurrentUser();
            final String nickname =
                (null != gUser.getNickname()
                        && !gUser.getNickname().isEmpty()
                        && gUser.getNickname().indexOf("@") >= 0
                    ? (gUser.getNickname().substring(0, gUser.getNickname().indexOf("@")))
                    : gUser.getEmail());
            user = new TDUser(gUser, nickname, gUser.getEmail());
            Datastore.put(user);
          } else {
            Logger.getLogger(TAG).info("User " + user.getKey() + " found.");
          }

          Logger.getLogger(TAG).info("User's API Key is: " + user.getApiKey());

          // Redirect to given url with the TDUser Id
          resp.sendRedirect(
              redirect
                  + (redirect.contains("?") ? "&" : "?")
                  + UserConstants.TDUSER_ID
                  + "="
                  + user.getKey().getId()
                  + "&"
                  + UserConstants.API_KEY
                  + "="
                  + URLEncoder.encode(user.getApiKey(), "UTF-8"));
        } catch (Exception e) {
          Logger.getLogger(TAG).error(e.getMessage(), e);
          // Ensure some kind of redirect
          resp.sendRedirect(redirect);
        }
      } else {
        // Create a url
        final String url = TDUserService.getGoogleLoginURL("/api/googleAuth?redirect=" + redirect);
        Logger.getLogger(TAG).info("User not logged in. Sending to Google Auth, URL: " + url);

        // Redirect to that url
        resp.sendRedirect(url);
      }
    } catch (Exception e) {
      e.printStackTrace();
      Logger.getLogger(TAG).error(e.getMessage());
      // Notify of error
      pw.write(APIUtils.generateJSONFailureMessage(e));
    } finally {
      pw.flush();
      pw.close();
    }
  }