コード例 #1
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      if (HttpUtils.isEmptyAny(request, "type")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      } else {
        String type = request.getParameter("type");
        int appId = NumberUtils.getInt(request.getHeader(Commons.APP_HEADER), -1);
        JSONObject reply = new JSONObject();

        String latStr = request.getParameter("lat");
        String lngStr = request.getParameter("lng");
        if (StringUtils.isNotEmpty(latStr) && StringUtils.isNotEmpty(lngStr)) {
          try {
            Landmark l = new Landmark();
            l.setLatitude(GeocodeUtils.getLatitude(latStr));
            l.setLongitude(GeocodeUtils.getLongitude(lngStr));
            logger.log(Level.INFO, "User location is " + latStr + "," + lngStr);
            // persist location

            l.setName(Commons.MY_POSITION_LAYER);
            boolean isSimilarToNewest = LandmarkPersistenceWebUtils.isSimilarToNewest(l);
            if (!isSimilarToNewest) {
              String u =
                  StringUtil.getUsername(
                      request.getAttribute("username"), request.getParameter("username"));
              if (u != null && u.length() % 4 == 0) {
                try {
                  u = new String(Base64.decode(u));
                } catch (Exception e) {
                  // from version 1086, 86 username is Base64 encoded string
                }
              }
              l.setUsername(u);
              String socialIds = request.getParameter("socialIds");

              LandmarkPersistenceWebUtils.setFlex(l, request);
              l.setLayer(Commons.MY_POS_CODE);

              LandmarkPersistenceUtils.persistLandmark(l, GoogleCacheProvider.getInstance());

              if (l.getId() > 0) {
                LandmarkPersistenceWebUtils.notifyOnLandmarkCreation(
                    l, request.getHeader("User-Agent"), socialIds);
              }
            }
          } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
          }
        } else {
          logger.log(Level.INFO, "No user location provided");
        }

        if (StringUtils.equals(type, "v")) {
          // check for version
          reply.put("type", type);
          if (appId == 0) {
            // LM
            String version =
                ConfigurationManager.getParam(
                    net.gmsworld.server.config.ConfigurationManager.LM_VERSION, "0");
            reply.put("value", version);
          } else if (appId == 1) {
            // DA
            String version =
                ConfigurationManager.getParam(
                    net.gmsworld.server.config.ConfigurationManager.DA_VERSION, "0");
            reply.put("value", version);
          }
        } else if (StringUtils.equals(type, "u")) {
          // engagement
          String email = request.getParameter("e");
          long lastStartupTime = NumberUtils.getLong(request.getParameter("lst"), -1);
          String useCount = request.getParameter("uc");
          Calendar cal = Calendar.getInstance();
          cal.setTimeInMillis(lastStartupTime);
          logger.log(
              Level.INFO,
              "Received usage notification from "
                  + (email != null ? email : "guest")
                  + " last startup time: "
                  + DateFormat.getDateTimeInstance().format(cal.getTime())
                  + ", use count: "
                  + useCount);
          int minInterval =
              NumberUtils.getInt(
                  ConfigurationManager.getParam(
                      net.gmsworld.server.config.ConfigurationManager.NOTIFICATIONS_INTERVAL, "14"),
                  14);
          int maxInterval = 31;
          long interval = System.currentTimeMillis() - lastStartupTime;
          if (interval > (minInterval * ONE_DAY)
              && interval < (maxInterval * ONE_DAY)
              && email != null) {
            // send email notification if lastStartupTime > week ago
            // send not more that once a week
            logger.log(Level.WARNING, email + " should be engaged to run Landmark Manager!");
            MailUtils.sendEngagementMessage(email, getServletContext());
            reply =
                new JSONObject()
                    .put("status", "engaged")
                    .put("timestamp", System.currentTimeMillis());
          } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            reply = new JSONObject().put("status", "accepted");
          }
        }
        out.print(reply.toString());
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
      out.close();
    }
  }
コード例 #2
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      // THIS is for NOKIA application
      Logger.getLogger(FBPlacesServlet.class.getName())
          .log(Level.SEVERE, "Oops !!! Somebody called " + FBPlacesServlet.class.getName());

      if (HttpUtils.isEmptyAny(request, "latitude", "longitude", "distance")) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      } else {
        String latitude = request.getParameter("latitude");
        String longitude = request.getParameter("longitude");
        String distance = request.getParameter("distance");
        int limit = NumberUtils.getInt(request.getParameter("limit"), 30);

        FacebookClient facebookClient =
            FacebookUtils.getFacebookClient(Commons.getProperty(Property.fb_app_token));

        String query = request.getParameter("q");
        JsonObject placesSearch = null;

        if (query != null && query.length() > 0) {
          placesSearch =
              facebookClient.fetchObject(
                  "search",
                  JsonObject.class,
                  Parameter.with("type", "place"),
                  Parameter.with("center", latitude + "," + longitude),
                  Parameter.with("distance", distance),
                  Parameter.with("q", query),
                  Parameter.with("limit", limit));
        } else {
          placesSearch =
              facebookClient.fetchObject(
                  "search",
                  JsonObject.class,
                  Parameter.with("type", "place"),
                  Parameter.with("center", latitude + "," + longitude),
                  Parameter.with("distance", distance),
                  Parameter.with("limit", limit));
        }

        JsonArray data = placesSearch.getJsonArray("data");

        ArrayList<Object> jsonArray = new ArrayList<Object>();
        String output = "";

        if (request.getParameter("version") != null
            && request.getParameter("version").equals("3")) {

          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            jsonObject.put("name", place.getString("name"));
            jsonObject.put("url", place.getString("id"));

            Map<String, String> desc = new HashMap<String, String>();
            if (place.has("category")) {
              desc.put("category", place.getString("category"));
            }
            JsonObject location = place.getJsonObject("location");
            Iterator<?> iter = location.sortedKeys();
            while (iter.hasNext()) {
              String next = (String) iter.next();
              if (!(next.equals("latitude") || next.equals("longitude"))) {
                desc.put(next, location.getString(next));
              }
            }
            jsonObject.put("desc", desc);
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("ResultSet", jsonArray);
          output = json.toString();

        } else if (request.getParameter("version") != null
            && request.getParameter("version").equals("2")) {

          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            jsonObject.put("name", place.getString("name"));
            jsonObject.put("desc", place.getString("id"));
            JsonObject location = place.getJsonObject("location");
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("ResultSet", jsonArray);
          output = json.toString();

        } else {
          // data
          for (int i = 0; i < data.length(); i++) {
            Map<String, Object> jsonObject = new HashMap<String, Object>();
            JsonObject place = (JsonObject) data.get(i);
            if (place.has("name")) {
              jsonObject.put("name", place.getString("name"));
            } else {
              jsonObject.put("name", place.getString("id"));
            }
            jsonObject.put("id", place.getString("id"));
            JsonObject location = place.getJsonObject("location");
            jsonObject.put("lat", MathUtils.normalizeE6(location.getDouble("latitude")));
            jsonObject.put("lng", MathUtils.normalizeE6(location.getDouble("longitude")));
            jsonArray.add(jsonObject);
          }

          JSONObject json = new JSONObject().put("data", jsonArray);
          output = json.toString();
        }

        out.println(output);
      }
    } catch (Exception ex) {
      Logger.getLogger(FBPlacesServlet.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
      if (ex instanceof FacebookOAuthException) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } finally {
      out.close();
    }
  }