예제 #1
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    // Skip oauth for local connections
    if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) {
      // Read the OAuth parameters from the request
      OAuthServletRequest request = new OAuthServletRequest(httpRequest);
      OAuthParameters params = new OAuthParameters();
      params.readRequest(request);

      String consumerKey = params.getConsumerKey();

      // Set the secret(s), against which we will verify the request
      OAuthSecrets secrets = new OAuthSecrets();
      secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey));

      // Check that the timestamp has not expired
      String timestampStr = params.getTimestamp();
      if (timestampStr == null) {
        logger.warn("Missing OAuth headers");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers");
        return;
      }

      long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds
      long currentTime = System.currentTimeMillis();

      // if the message is older than 5 min it is no good
      if (Math.abs(msgTime - currentTime) > 300000) {
        logger.warn(
            "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired");
        return;
      }

      // Verify the signature
      try {
        if (!OAuthSignature.verify(request, params, secrets)) {
          logger.warn("Invalid OAuth signature");

          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature");
          return;
        }
      } catch (OAuthSignatureException e) {
        logger.warn("OAuth exception", e);

        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request");
        return;
      }
    }

    filterChain.doFilter(servletRequest, servletResponse);
  }
예제 #2
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();

    // All request in GET method must be certificated
    Object obj = session.getAttribute("device_id");

    if (!(obj instanceof Long)) {
      // Client must be login first, then use Mobile service
      response.setStatus(404);
      return;
    }

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Here is tracked's id
    Long device_id = (Long) obj;

    // Determine operation type
    String op = request.getParameter("op");
    if (op == null) op = "";

    // Get current track
    Long track_id = null;
    obj = session.getAttribute("track_id");
    if (obj instanceof Long) {
      track_id = (Long) obj;
    }

    if (op.equals("logout")) {
      // Client request a logout operation
      session.removeAttribute("device_id");
      session.removeAttribute("track_id");
      out.print("OK," + device_id);
    } else if (op.equals("latlng")) {
      // Client insert update it's location in latitude/longitude

      // If it's a first waypoint, create a new track
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      // Parse latitude, longitude from request
      double lat = Double.parseDouble(request.getParameter("lat"));
      double lng = Double.parseDouble(request.getParameter("lng"));

      long speed = -1L;
      try {
        // Try to get speed from request
        speed = Long.parseLong(request.getParameter("spd"));
      } catch (Exception ex) {
      }

      if (speed < 0) {
        // Client don't send speed to server
        try {
          // Calculate speed manually
          double lastLat = (Double) session.getAttribute("latitude");
          double lastLng = (Double) session.getAttribute("longitude");
          long time = (Long) session.getAttribute("time");
          long distance = Utils.getDistance(lastLat, lastLng, lat, lng);
          speed = distance * 1000 / Math.abs(time - System.currentTimeMillis());
        } catch (Exception ex) {
          speed = 0L;
        }
      }

      // Insert new point into server
      ServiceResult<CWaypoint> result = db.insertWaypoint(track_id, lat, lng, speed);
      CWaypoint cwaypoint = result.getResult();
      if (result.isOK()) {
        // OK,latitude,longitude,speed(m/s),time,trackid
        session.setAttribute("latitude", lat);
        session.setAttribute("longitude", lng);
        session.setAttribute("time", cwaypoint.getTime().getTime());
        out.print(
            "OK,"
                + cwaypoint.getLat()
                + ","
                + cwaypoint.getLng()
                + ","
                + cwaypoint.getSpeed()
                + ","
                + cwaypoint.getTime().getTime()
                + ","
                + cwaypoint.getTrackID());
      }
    } else if (op.equals("cellid")) {
      // Client send it's location by cellular technique
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      try {
        int cell = Integer.parseInt(request.getParameter("cell"));
        int lac = Integer.parseInt(request.getParameter("lac"));
        Geocode geocode = Utils.getLocation(cell, lac);
        out.println(geocode.getLatitude() + "," + geocode.getLongitude());
      } catch (Exception ex) {
      }

      // TODO Implements cellular method to calculate location of a mobile
      out.println("Not implement");
    } else if (op.equals("newtrack")) {
      // Client request to create a new track
      track_id = db.newTrack(device_id).getResult().getTrackID();
      session.setAttribute("track_id", track_id);
      out.print("OK," + track_id);
    } else if (op.equals("changepass")) {
      String newpass = request.getParameter("newpass");
      if (newpass != null) {
        CTracked ctracked = new CTracked();
        ctracked.setUsername(device_id);
        ctracked.setPassword(newpass);
        if (db.updateTracked(ctracked).isOK()) {
          out.println("OK," + device_id);
        }
      }
    } else if (op.equals("config")) {
      CTracked ctracked = db.getTracked(device_id).getResult();
      Integer interval = ctracked.getIntervalGps();
      if (interval == null) interval = 10;
      out.print("OK," + interval + ",");
      byte[] b = ctracked.getSchedule();
      if (b == null) {
        for (int i = 0; i < 23; i++) {
          out.print("1.");
        }
        out.println(1);
      } else {
        for (int i = 0; i < 23; i++) {
          out.print(b[i] + ".");
        }
        out.println(b[23]);
      }
    } else if (op.equals("amilogin")) {
      out.println("OK");
    }
  }
예제 #3
0
  private String processRequest(
      HttpServletRequest request, HttpServletResponse response, ConnectionPool conPool)
      throws Exception {
    // getting id parameters
    ParameterParser parameter = new ParameterParser(request);
    String bookID = parameter.getString(bookInterface.FIELD_ID, null);
    String sellerID = parameter.getString(bookInterface.FIELD_SELLERID, null);
    String message = parameter.getString(FIELD_MESSAGE, null);
    int codeID = parameter.getInt(bookInterface.FIELD_HIDDENID, 0);
    // get buyer's user object
    User user = (User) request.getSession().getAttribute(StringInterface.USERATTR);
    // security feauture:
    // if one of ids is missing or incorrect return false
    if (bookID == null
        || sellerID == null
        || codeID == 0
        || bookID.length() != booksTable.ID_LENGTH
        || sellerID.length() != usersTable.ID_LENGTH
        || codeID != Math.abs(bookID.hashCode())) {
      return "We were unable to find the book you specified! Please make sure that the book id is correct.";
    }
    if (user.getID().equals(sellerID)) {
      return "You may not purchase an item from yourself!";
    }
    // get connection
    Connection con = conPool.getConnection();
    try {
      booksTable book = generalUtils.getBook(bookID, con);
      /*security feauture:
       *check seller id == passed hidden id
       *book != null
       */
      if (book == null || !book.getSellerID().equals(sellerID)) {
        return "We were unable to find the book you specified! Please make sure that the book id is correct.";
      }
      usersTable sellerInfo = userUtils.getUserInfo(sellerID, con);
      usersTable buyerInfo = userUtils.getUserInfo(user.getID(), con);
      collegeTable college = getCollege(book.getCollegeID() + "", con);
      // if still here continue
      if (message == null) {
        request.setAttribute(ATTR_BOOK, book);
        request.setAttribute(ATTR_SELLER, sellerInfo);
        request.setAttribute(ATTR_BUYER, buyerInfo);
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATH_BUY_CONFIRM);
        rd.include(request, response);
        return null;
      } else if (buy(book, user, con)) {
        // sending email to buyer
        request.setAttribute(mailInterface.USERATTR, buyerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, buyerInfo.getEmail());
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute("book_id", bookID);
        request.setAttribute("seller_id", sellerID);

        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHBIDCONFIRMATION);
        rd.include(request, response);
        // sending email to seller
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        request.setAttribute(mailInterface.USERATTR, sellerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, sellerInfo.getEmail());
        request.setAttribute(mailInterface.MESSAGEATTR, message);
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute(mailInterface.MOREATTR, buyerInfo);

        request.setAttribute("book_id", bookID);
        request.setAttribute("buyer_id", user.getID());
        rd = getServletContext().getRequestDispatcher(PATHBOOKUPDATE);
        rd.include(request, response);
        // showing success message
        rd = getServletContext().getRequestDispatcher(PATH_BUY_SUCCESS);
        rd.include(request, response);
        return null;
      } else {
        throw new Exception("failed to process with buy");
      }
    } catch (Exception e) {
      throw e;
    } finally {
      // recycle
      conPool.free(con);
      con = null;
    }
  }