protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    if (pathInfo.equals("/")) {
      HttpSession session = req.getSession();
      if (session == null) {
        resp.setStatus(401);
        return;
      }
      String username = (String) session.getAttribute("username");
      if (username == null) {
        resp.setStatus(401);
        return;
      }

      Map userMap = loadUserSettingsMap(username);
      if (userMap == null) {
        resp.setStatus(401);
        return;
      }
      Enumeration parameterNames = req.getParameterNames();
      while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        userMap.put(parameterName, req.getParameter(parameterName));
      }
      saveUserSettingsMap(username, userMap);
      return;
    }

    super.doPost(req, resp);
  }
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      userMap.clear();
    }
    String key = pathInfo.substring(1);
    userMap.remove(key);
    saveUserSettingsMap(username, userMap);
    return;
  }
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   Member unassigner = (Member) request.getSession(false).getAttribute(Member.class.toString());
   Identificator<Issue> idOfIssue = new Identificator<Issue>(request.getParameter("issue_id"));
   Issue issue = Issue.getInstance(idOfIssue);
   String[] idOfTags = request.getParameterValues("tag_id");
   int i = 0;
   boolean success = true;
   for (i = 0; i < idOfTags.length; i++) {
     Identificator<Tag> idOfTag = new Identificator<Tag>(idOfTags[i]);
     Tag tag = Tag.getInstance(idOfTag);
     if (tag != null) {
       issue = issue.unassignTag(unassigner, tag);
       success = (!issue.containsTag(tag)) && success;
     } else {
       success = true && success;
     }
   }
   if (success) {
     response.setStatus(HttpServletResponse.SC_OK);
     Page.ISSUE.setParameter("id", issue.getId());
     Page.ISSUE.redirect(request, response);
   } else {
     response.sendError(
         HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
         "Failed to proccess the request for unknown reason. Please check if input was correct.");
   }
 }
 private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt)
     throws IOException {
   setContentType(pResp, pContentType);
   pResp.setStatus(200);
   setNoCacheHeaders(pResp);
   PrintWriter writer = pResp.getWriter();
   writer.write(pJsonTxt);
 }
  /** {@inheritDoc} */
  @Override
  public void handle(String target, Request req, HttpServletRequest srvReq, HttpServletResponse res)
      throws IOException, ServletException {
    if (log.isDebugEnabled())
      log.debug("Handling request [target=" + target + ", req=" + req + ", srvReq=" + srvReq + ']');

    if (target.startsWith("/gridgain")) {
      processRequest(target, srvReq, res);

      req.setHandled(true);
    } else if (target.startsWith("/favicon.ico")) {
      if (favicon == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("image/x-icon");

      res.getOutputStream().write(favicon);
      res.getOutputStream().flush();

      req.setHandled(true);
    } else {
      if (dfltPage == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("text/html");

      res.getWriter().write(dfltPage);
      res.getWriter().flush();

      req.setHandled(true);
    }
  }
 /**
  * Sets a status and sends an info message.
  *
  * @param code status code
  * @param message info message
  * @throws IOException I/O exception
  */
 public void status(final int code, final String message) throws IOException {
   log(true, code, message);
   if (session != null) session.close();
   res.resetBuffer();
   res.setStatus(code);
   if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC);
   if (message != null) res.getOutputStream().write(token(message));
 }
Exemple #9
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);
    if (exception != null) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("\r\n");
      out.write("<title>Error Page</title>\r\n");
      out.write("</head>\r\n");
      out.write("\r\n");
      out.write("<body bgcolor=\"blue\">\r\n");
      out.write("\t<font size=\"16\" color=\"white\">Your page generated an error:\"<br />\r\n");
      out.write("\t\tException:<br /></font>\r\n");
      out.write("\t");
      out.print(exception.toString());
      out.write("\r\n");
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
 protected void handleDocument(
     HttpServletRequest request, HttpServletResponse response, Document doc) throws IOException {
   if (request.getPathInfo().equalsIgnoreCase("/load")) getXmlScoreBoard().loadDocument(doc);
   else if (request.getPathInfo().equalsIgnoreCase("/merge"))
     getXmlScoreBoard().mergeDocument(doc);
   else
     response.sendError(
         HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document");
   response.setContentType("text/plain");
   response.setStatus(HttpServletResponse.SC_OK);
 }
Exemple #11
0
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    String path = request.getRequestURI();
    // use routes if present
    if (this.routes != null) {
      String route = this.routes.getProperty(path);
      if (route != null) {
        path = route;
        // then we also need to replace the HttpServletRequest.getRequestURI method
        // request = getRequestWrapper(request, path);
      }
    }

    if (path.endsWith("/")) path += "index";
    String source = null;
    // check for changes first
    if (this.debug && contextCache.checkForChanges()) {
      if (this.pageInfoCache != null) this.pageInfoCache.clear();
    }
    ScriptContext context = contextCache.getContext();
    try {
      serve(request, response, context, path, null);
    } catch (Exception e) {
      int status = getStatus(e);
      response.setStatus(status);
      response.setContentType("text/plain");
      System.out.println(e.toString());
      if (errorPath != null && status >= 500) {
        try {
          serve(request, response, context, errorPath, e);
        } catch (Exception f) {
          e.printStackTrace(response.getWriter());
          response.getWriter().write("ERROR IN ERROR HANDLER PAGE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
          f.printStackTrace(response.getWriter());
        }
      } else if (debug && status == 500) {
        e.printStackTrace(response.getWriter());
      } else if (e instanceof JavaScriptException) {
        JavaScriptException je = (JavaScriptException) e;
        response.getWriter().write(je.getValue().toString());
      } else {
        response.getWriter().write(e.getMessage());
      }
    } finally {
      contextCache.returnContext(context);
    }
  }
  public static boolean saveFile(
      HttpServlet servlet,
      String contentPath,
      String path,
      HttpServletRequest req,
      HttpServletResponse res) {

    // @todo Need to use logServerAccess() below here.
    boolean debugRequest = Debug.isSet("SaveFile");
    if (debugRequest) log.debug(" saveFile(): path= " + path);

    String filename = contentPath + path; // absolute path
    File want = new File(filename);

    // backup current version if it exists
    int version = getBackupVersion(want.getParent(), want.getName());
    String fileSave = filename + "~" + version;
    File file = new File(filename);
    if (file.exists()) {
      try {
        IO.copyFile(filename, fileSave);
      } catch (IOException e) {
        log.error(
            "saveFile(): Unable to save copy of file "
                + filename
                + " to "
                + fileSave
                + "\n"
                + e.getMessage());
        return false;
      }
    }

    // save new file
    try {
      OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
      IO.copy(req.getInputStream(), out);
      out.close();
      if (debugRequest) log.debug("saveFile(): ok= " + filename);
      res.setStatus(HttpServletResponse.SC_CREATED);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1));
      return true;
    } catch (IOException e) {
      log.error(
          "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage());
      return false;
    }
  }
Exemple #13
0
  /**
   * Sets a status and sends an info message.
   *
   * @param code status code
   * @param message info message
   * @param error treat as error (use web server standard output)
   * @throws IOException I/O exception
   */
  public void status(final int code, final String message, final boolean error) throws IOException {
    try {
      log(message, code);
      res.resetBuffer();
      if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC);

      if (error && code >= SC_BAD_REQUEST) {
        res.sendError(code, message);
      } else {
        res.setStatus(code);
        if (message != null) res.getOutputStream().write(token(message));
      }
    } catch (final IllegalStateException ex) {
      log(Util.message(ex), SC_INTERNAL_SERVER_ERROR);
    }
  }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    String sid = req.getParameter("sid");
    String gameId = req.getParameter("game");
    String action = req.getParameter("action");

    HanabiUser user = s.getUserBySession(sid);
    HanabiGame game = s.getGame(gameId);

    try {

      String message;
      if (action.equals("play_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.PlayCardResult rv = game.playCard(slot);
        message = "It was a " + rv.card + "; " + (rv.success ? "Success!" : "Oops!");
      } else if (action.equals("discard_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.Card c = game.discardCard(slot);
        message = "It was a " + c;
      } else if (action.equals("give_hint")) {
        doGiveHint(game, req, resp);
        return;
      } else {
        message = "don't know how to " + action;
      }

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());

      out.writeStartObject();
      out.writeStringField("message", message);
      out.writeEndObject();
      out.close();

    } catch (HanabiException e) {

      resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());
      out.writeStartObject();
      out.writeStringField("status", "error");
      out.writeStringField("message", e.toString());
      out.writeEndObject();
      out.close();
    }
  }
Exemple #15
0
  protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
      if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest));

      // getRequestURL is the exact string used by the caller in the request.
      // Internally, it's the "request URI" that names the service

      // String requestURL = httpRequest.getRequestURL().toString() ;
      String uri = httpRequest.getRequestURI();

      if (uri.length() > urlLimit) {
        httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
        return;
      }

      String serviceURI = chooseServiceURI(uri, httpRequest);
      serviceURI = Service.canonical(serviceURI);

      String sender = httpRequest.getRemoteAddr();
      log.info("[" + sender + "] Service URI = <" + serviceURI + ">");

      // MIME-Type
      String contentType = httpRequest.getContentType();

      //            if ( Joseki.contentSPARQLUpdate.equals(contentType) ||
      //                Joseki.contentSPARQLUpdate_X.equals(contentType) )
      //            {}

      Request request = setupRequest(serviceURI, httpRequest);
      request.setParam(Joseki.VERB, httpRequest.getMethod());

      Response response = new ResponseHttp(request, httpRequest, httpResponse);
      Dispatcher.dispatch(serviceURI, request, response);
    } catch (Exception ex) {
      try {
        log.warn("Internal server error", ex);
        //                httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ;
        //                httpResponse.flushBuffer() ;
        //                httpResponse.getWriter().close() ;
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      } catch (Exception e) {
      }
    }
  }
Exemple #16
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String path = request.getPathInfo();
    boolean htmlOutput = true;
    String language = null;
    String contentType = "text/html; charset='utf-8'";

    if (path != null) {
      if (path.endsWith(".rdf")) {
        contentType = "application/rdf+xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".xml")) {
        contentType = "application/xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".n3")) {
        contentType = "text/n3; charset='utf-8'";
        htmlOutput = false;
        language = "N3";
      }
    }

    response.setContentType(contentType);
    response.setStatus(HttpServletResponse.SC_OK);

    Writer writer = response.getWriter();

    synchronized (board) {
      if (htmlOutput) {
        writer.write(
            "<!DOCTYPE html>\n"
                + "<html lang='en'>"
                + "<head><meta charset='utf-8'/><title>MATe model</title></head>"
                + "<body><ul>");
        StmtIterator it = model.listStatements();
        /* TODO: well, this could be prettier */
        while (it.hasNext()) writer.write("<li>" + it.nextStatement() + "</li>");
        writer.write("<ul></body></html>");
      } else model.write(writer, language);
    }
  }
 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   String[] driverStrings = null;
   if (req.getParameterValues("driver") != null) {
     driverStrings = req.getParameterValues("driver");
   }
   if (driverStrings != null && driverStrings.length > 5) {
     resp.setStatus(400);
   } else {
     NascarConfig config = NascarConfigSingleton.get();
     List<Driver> drivers =
         DatastoreManager.getDriversByNamesAndRace(driverStrings, config.getRaceKey());
     Owner owner = DatastoreManager.getCurrentOwner();
     Lineup lineup = new Lineup(config.getRaceKey());
     boolean driversAdded = lineup.setDrivers(drivers);
     if (driversAdded) {
       Team team = owner.getTeam();
       team.setLineup(lineup);
       DatastoreManager.persistObject(team);
     }
   }
   resp.sendRedirect(req.getRequestURI());
 }
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!path.equals(request.getRequestURI())) {
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/plain");

    PrintWriter out = null;
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

      out = response.getWriter();

      Map<String, Endpoint> endpointMap = tracker.getEndpointMap();
      Map<String, Long> expirationMap = tracker.getExpirationMap();

      out.println("Active sessions:");
      out.println();

      for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) {
        String key = ep.getKey();
        out.print(ep.getKey());
        out.print(" => ");
        out.print(ep.getValue());

        Long expiration = expirationMap.get(key);
        if (expiration == null) {
          out.println(" (expiration unknown)");
        } else {
          out.print(" (expires ");
          out.print(df.format(new Date(expiration)));
          out.println(")");
        }
      }

      out.println();
      out.println("Events:");
      out.println();

      for (EndpointEvent event : tracker.getEvents()) {
        out.print(df.format(new Date(event.getTimestamp())));
        out.print(" ");
        out.print(event.getStatus().name());
        out.print(" ");
        out.print(event.getConnectionId());
        out.print(" ");
        out.print(event.getDetails());
        out.println();
      }
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Throwable ignored) {
      }
    }
    baseRequest.setHandled(true);
  }
  /**
   * Process HTTP request.
   *
   * @param act Action.
   * @param req Http request.
   * @param res Http response.
   */
  private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    GridRestCommand cmd = command(req);

    if (cmd == null) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    if (!authChecker.apply(req.getHeader("X-Signature"))) {
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return;
    }

    GridRestResponse cmdRes;

    Map<String, Object> params = parameters(req);

    try {
      GridRestRequest cmdReq = createRequest(cmd, params, req);

      if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq);

      cmdRes = hnd.handle(cmdReq);

      if (cmdRes == null)
        throw new IllegalStateException("Received null result from handler: " + hnd);

      byte[] sesTok = cmdRes.sessionTokenBytes();

      if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok));

      res.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      res.setStatus(HttpServletResponse.SC_OK);

      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage());
    } catch (Throwable e) {
      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      throw e;
    }

    JsonConfig cfg = new GridJettyJsonConfig();

    // Workaround for not needed transformation of string into JSON object.
    if (cmdRes.getResponse() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC);

    if (cmdRes.getResponse() instanceof GridClientTaskResultBean
        && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC);

    JSON json;

    try {
      json = JSONSerializer.toJSON(cmdRes, cfg);
    } catch (JSONException e) {
      U.error(log, "Failed to convert response to JSON: " + cmdRes, e);

      json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg);
    }

    try {
      if (log.isDebugEnabled())
        log.debug("Parsed command response into JSON object: " + json.toString(2));

      res.getWriter().write(json.toString());

      if (log.isDebugEnabled())
        log.debug(
            "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']');
    } catch (IOException e) {
      U.error(log, "Failed to send HTTP response: " + json.toString(2), e);
    }
  }
Exemple #20
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String verifypassword = request.getParameter("verifypassword");
    Map<String, String> myResponse = new HashMap<String, String>();
    PrintWriter out = response.getWriter();
    if (email.matches(
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) // make sure email is properly
    // formatted
    {
      try {

        MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
        DB db = mongoURI.connectDB(); // instance of databse
        db.authenticate(mongoURI.getUsername(), mongoURI.getPassword()); // authenticates d
        // Set<string> accounts = db.getCollectionName("accounts");
        // Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
        // DB db = mongo.getDB("fourup"); //gets fourup database
        DBCollection accounts = db.getCollection("accounts"); // creates collection for accounts	
        BasicDBObject query = new BasicDBObject(); // creates a basic object named query
        query.put("email", email); // sets email to email
        DBCursor cursor = accounts.find(query);
        if (cursor.size() > 0) // check if email has already been registered
        {
          myResponse.put("Status", "Error");
          myResponse.put("Error", "Account already exists using this email address.");
        } else // since email doesn't currently exist in DB, go ahead and register user
        {
          if (password.equals(
              verifypassword)) // check that both of the passwords entered match each other
          {
            BasicDBObject document = new BasicDBObject();
            int salt = getSalt();
            String hpass = passwrdHash(password, salt);
            document.put("email", email);
            document.put("salt", salt);
            document.put("password", hpass); // this is where we need to hash the password
            accounts.insert(document);
            myResponse.put("Status", "Sucess");
            myResponse.put("Sucess", "Account has been Created");
            AccountObject user = new AccountObject(email, hpass);
            // set session
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", email);
            // return cookie
            Cookie cookie = new Cookie("fourupCookie", email); // add the login information here
            response.addCookie(cookie);
            // redirect to homepage
            String message = "this is a test";
            myResponse.put("html", "<html></html>");
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            // response.sendRedirect("index.html"); //should add check to index page for cookie with
            // login information
          } else {
            myResponse.put("Status", "Failed");
            myResponse.put("Failed", "Passwords do not match.");
          }
        }

      } catch (MongoException e) {

        out.write(e.getMessage());
      }
    } else {
      myResponse.put("Status", "Invalid");
      myResponse.put(
          "Invalid", "The email address has not been entered correctly."); // should output error
    }

    String strResponse = new Gson().toJson(myResponse);
    response.getWriter().write(strResponse);
    response.getWriter().close();
  }
Exemple #21
0
 // HEAD not allowed
 public void doHead(HttpServletRequest request, HttpServletResponse response) {
   response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
 }
  /**
   * This method handles PUT requests from the client. PUT requests will come from the applet
   * portion of this application and are the way that images and other files can be posted to the
   * server.
   *
   * @param request the HTTP request object
   * @param response the HTTP response object
   * @exception ServletException
   * @exception IOException
   */
  public void doPut(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    /*
     * The Scan applet will zip all the files together to create a
     * faster upload and to use just one server connection.
     */
    ZipInputStream in = new ZipInputStream(request.getInputStream());

    /*
     * This will write all the files to a directory on the server.
     */
    try {
      try {

        File file = new File("scan");
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        String fileSize = null;
        while (true) {
          ZipEntry entry = in.getNextEntry();
          if (entry == null) {
            break;
          }
          File f = File.createTempFile("translate", entry.getName());
          FileOutputStream out = new FileOutputStream(f);
          FileInputStream inStream = null;
          try {
            int read;
            byte[] buf = new byte[2024];

            while ((read = in.read(buf)) > 0) {
              out.write(buf, 0, read);
            }
            out.close();
            inStream = new FileInputStream(f);
            System.out.println(entry.getSize());
            byte[] b = new byte[inStream.available()];
            inStream.read(b);
            System.out.println(b.length);
            com.itextpdf.text.Image image1 = com.itextpdf.text.Image.getInstance(b);
            image1.scalePercent(30);
            image1.setCompressionLevel(9);
            document.add(image1);
          } finally {
          }
        }
        document.close();
        //                fileSize = CommonUtils.getFileSize(file);
        //                DocumentStoreLogDAO documentStoreLogDAO = new DocumentStoreLogDAO();
        //                DocumentStoreLog documentStoreLog = null;
        //                DocumentStoreLog documentStore =
        // (DocumentStoreLog)session.getAttribute(CommonConstants.DOCUMENT_STORE_LOG);
        //                if(null != documentStore) {
        //                    documentStore.setFileSize(fileSize);
        //                }
        //                Transaction tx = documentStoreLogDAO.getSession().getTransaction();
        //                tx.begin();
        //                documentStoreLogDAO.save(documentStore);
        //                tx.commit();
      } catch (ZipException ze) {
        /*
         * We want to catch each sip exception separately because
         * there is a possibility that we can read more files from
         * the archive even if one of them is corrupted.
         */
        ze.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      in.close();
    }

    /*
     * Now that we have finished uploading the files
     * we will send a reponse to the server indicating
     * our success.
     */

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>ImageSrv</title></head></html>");
    out.flush();
    out.close();
    response.setStatus(HttpServletResponse.SC_OK);
  }
Exemple #23
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");
    }
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
  /**
   * Receives standard HTTP requests from the public <code>service</code> method and dispatches them
   * to the <code>do</code><i>Method</i> methods defined in this class. This method is an
   * HTTP-specific version of the {@link javax.servlet.Servlet#service} method. There's no need to
   * override this method.
   *
   * @param req the {@link HttpServletRequest} object that contains the request the client made of
   *     the servlet
   * @param resp the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @exception IOException if an input or output error occurs while the servlet is handling the
   *     HTTP request
   * @exception ServletException if the HTTP request cannot be handled
   * @see javax.servlet.Servlet#service
   */
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
      long lastModified = getLastModified(req);
      if (lastModified == -1) {
        // servlet doesn't support if-modified-since, no reason
        // to go through further expensive logic
        doGet(req, resp);
      } else {
        long ifModifiedSince;
        try {
          ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
        } catch (IllegalArgumentException iae) {
          // Invalid date header - proceed as if none was set
          ifModifiedSince = -1;
        }
        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
          // If the servlet mod time is later, call doGet()
          // Round down to the nearest second for a proper compare
          // A ifModifiedSince of -1 will always be less
          maybeSetLastModified(resp, lastModified);
          doGet(req, resp);
        } else {
          resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }
      }

    } else if (method.equals(METHOD_HEAD)) {
      long lastModified = getLastModified(req);
      maybeSetLastModified(resp, lastModified);
      doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
      doPost(req, resp);

    } else if (method.equals(METHOD_PUT)) {
      doPut(req, resp);

    } else if (method.equals(METHOD_DELETE)) {
      doDelete(req, resp);

    } else if (method.equals(METHOD_OPTIONS)) {
      doOptions(req, resp);

    } else if (method.equals(METHOD_TRACE)) {
      doTrace(req, resp);

    } else {
      //
      // Note that this means NO servlet supports whatever
      // method was requested, anywhere on this server.
      //

      String errMsg = lStrings.getString("http.method_not_implemented");
      Object[] errArgs = new Object[1];
      errArgs[0] = method;
      errMsg = MessageFormat.format(errMsg, errArgs);

      resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
  }
Exemple #26
0
  private boolean sendError(FacesContext context, String lifecycle, Exception e) {
    for (Throwable cause = e; cause != null; cause = cause.getCause()) {
      if (cause instanceof DisplayableException) {
        if (e instanceof RuntimeException) throw (RuntimeException) e;
        else throw new FacesException(e);
      } else if (cause instanceof ServletException) throw new FacesException(e);
      else if (cause instanceof JspException) throw new FacesException(e);
    }

    ExternalContext extContext = context.getExternalContext();
    Object response = extContext.getResponse();

    if (!(response instanceof HttpServletResponse)) {
      context.renderResponse();

      if (e instanceof RuntimeException) throw (RuntimeException) e;
      else throw new RuntimeException(e);
    }

    log.log(Level.WARNING, e.toString(), e);

    HttpServletResponse res = (HttpServletResponse) response;

    try {
      context.renderResponse();
      context.responseComplete();

      res.setStatus(500, "JSF Exception");
      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.println("<body>");

      out.println("<h3>JSF exception detected in " + lifecycle + " phase</h3>");

      String msg = e.getMessage();
      out.println("<span style='color:red;font:bold'>" + Html.escapeHtml(msg) + "</span><br/>");

      out.println("<h3>Context: " + context.getViewRoot() + "</h3>");
      out.println("<code><pre>");

      String errorId = null;

      if (e instanceof FacesException && msg.startsWith("id=")) {
        int p = msg.indexOf(' ');
        errorId = msg.substring(3, p);
      }

      printComponentTree(out, errorId, context, context.getViewRoot(), 0);

      out.println("</pre></code>");

      if (!Alarm.isTest()) {
        out.println("<h3>Stack Trace</h3>");
        out.println("<pre>");
        if (e.getCause() != null) e.getCause().printStackTrace(out);
        else e.printStackTrace(out);
        out.println("</pre>");
      }

      out.println("</body>");

      // clear, so we don't just loop
      Application app = context.getApplication();

      ViewHandler view = app.getViewHandler();

      UIViewRoot viewRoot = context.getViewRoot();

      viewRoot = view.createView(context, viewRoot.getViewId());

      context.setViewRoot(viewRoot);

      // view.writeState(context); // XXX: no need to output state, but review.

      return true;
    } catch (IOException e1) {
      throw new RuntimeException(e);
    }
  }
  // authentication request
  public String authRequest(
      String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
      throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print("OpenID realm wasn't initialized.");
      out.print("</h2>");

      // out.print(HTTPUtils.printStackTraceHTML(t));

      out.print("</div></body></html>");
      return null;
    }
    try {
      String returnAfterAuthentication = httpReq.getParameter("return_to");

      // configure the return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      String returnToUrl =
          httpReq.getRequestURL().toString()
              + "?is_return=true&exist_return="
              + returnAfterAuthentication;

      // perform discovery on the user-supplied identifier
      List<?> discoveries = manager.discover(userSuppliedString);

      // attempt to associate with the OpenID provider
      // and retrieve one service endpoint for authentication
      DiscoveryInformation discovered = manager.associate(discoveries);

      // store the discovery information in the user's session
      httpReq.getSession().setAttribute("openid-disc", discovered);

      // obtain a AuthRequest message to be sent to the OpenID provider
      AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

      if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
        SRegRequest sregReq = SRegRequest.createFetchRequest();

        sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

        authReq.addExtension(sregReq);
      } else {

        FetchRequest fetch = FetchRequest.createFetchRequest();

        fetch.addAttribute(
            AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
        fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

        // wants up to three email addresses
        fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

        authReq.addExtension(fetch);
      }

      if (!discovered.isVersion2()) {
        // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
        // The only method supported in OpenID 1.x
        // redirect-URL usually limited ~2048 bytes
        httpResp.sendRedirect(authReq.getDestinationUrl(true));
        return null;

      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

        Object OPEndpoint = authReq.getDestinationUrl(false);

        ServletOutputStream out = httpResp.getOutputStream();

        httpResp.setContentType("text/html; charset=UTF-8");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("    <title>OpenID HTML FORM Redirection</title>");
        out.println("</head>");
        out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
        out.println(
            "    <form name=\"openid-form-redirection\" action=\""
                + OPEndpoint
                + "\" method=\"post\" accept-charset=\"utf-8\">");

        Map<String, String> parameterMap = authReq.getParameterMap();
        for (Entry<String, String> entry : parameterMap.entrySet()) {
          out.println(
              "	<input type=\"hidden\" name=\""
                  + entry.getKey()
                  + "\" value=\""
                  + entry.getValue()
                  + "\"/>");
        }

        out.println("        <button type=\"submit\">Continue...</button>");
        out.println("    </form>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
      }
    } catch (OpenIDException e) {
      // present error to the user
      LOG.debug("OpenIDException", e);

      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print(e.getMessage());
      out.print("</h2>");

      Throwable t = e.getCause();
      if (t != null) {
        // t can be null
        out.print(HTTPUtils.printStackTraceHTML(t));
      }

      out.print("</div></body></html>");
    }

    return null;
  }
  /**
   * Send a permanent redirect (HTTP status 301 "Moved Permanently") response with the given target
   * path.
   *
   * <p>The given target path may be relative or absolute. If it is relative, it will be resolved
   * against the request URL.
   *
   * @param targetPath the path to which the client is redirected.
   * @param req the HttpServletRequest
   * @param res the HttpServletResponse
   * @throws IOException if can't write the response.
   */
  public static void sendPermanentRedirect(
      String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // Absolute URL needed so resolve the target path against the request URL.
    URI uri;
    try {
      uri = new URI(req.getRequestURL().toString());
    } catch (URISyntaxException e) {
      log.error(
          "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e);
      log.info(
          "sendPermanentRedirect(): "
              + UsageLog.closingMessageForRequestContext(
                  HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }
    String absolutePath = uri.resolve(targetPath).toString();
    absolutePath = res.encodeRedirectURL(absolutePath);

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    res.addHeader("Location", absolutePath);

    String title = "Permanently Moved - 301";
    String body =
        new StringBuilder()
            .append("<p>")
            .append("The requested URL <")
            .append(req.getRequestURL())
            .append("> has been permanently moved (HTTP status code 301).")
            .append(" Instead, please use the following URL: <a href=\"")
            .append(absolutePath)
            .append("\">")
            .append(absolutePath)
            .append("</a>.")
            .append("</p>")
            .toString();
    String htmlResp =
        new StringBuilder()
            .append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag())
            .append("<head><title>")
            .append(title)
            .append("</title></head><body>")
            .append("<h1>")
            .append(title)
            .append("</h1>")
            .append(body)
            .append("</body></html>")
            .toString();

    log.info("sendPermanentRedirect(): redirect to " + absolutePath);
    log.info(
        "sendPermanentRedirect(): "
            + UsageLog.closingMessageForRequestContext(
                HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length()));

    // Write the catalog out.
    PrintWriter out = res.getWriter();
    res.setContentType("text/html");
    out.print(htmlResp);
    out.flush();
  }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/plain");
   response.setStatus(HttpServletResponse.SC_OK);
   response.getWriter().write(request.getRemoteAddr());
 }
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param req request
   * @param res response
   * @param file must exists and not be a directory
   * @param contentType must not be null
   * @throws IOException or error
   */
  public static void returnFile(
      HttpServletRequest req, HttpServletResponse res, File file, String contentType)
      throws IOException {
    res.setContentType(contentType);

    // see if its a Range Request
    boolean isRangeRequest = false;
    long startPos = 0, endPos = Long.MAX_VALUE;
    String rangeRequest = req.getHeader("Range");
    if (rangeRequest != null) { // bytes=12-34 or bytes=12-
      int pos = rangeRequest.indexOf("=");
      if (pos > 0) {
        int pos2 = rangeRequest.indexOf("-");
        if (pos2 > 0) {
          String startString = rangeRequest.substring(pos + 1, pos2);
          String endString = rangeRequest.substring(pos2 + 1);
          startPos = Long.parseLong(startString);
          if (endString.length() > 0) endPos = Long.parseLong(endString) + 1;
          isRangeRequest = true;
        }
      }
    }

    // set content length
    long fileSize = file.length();
    long contentLength = fileSize;
    if (isRangeRequest) {
      endPos = Math.min(endPos, fileSize);
      contentLength = endPos - startPos;
    }

    if (contentLength > Integer.MAX_VALUE)
      res.addHeader(
          "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT
    else res.setContentLength((int) contentLength); // note HEAD only allows this

    String filename = file.getPath();
    boolean debugRequest = Debug.isSet("returnFile");
    if (debugRequest)
      log.debug(
          "returnFile(): filename = "
              + filename
              + " contentType = "
              + contentType
              + " contentLength = "
              + contentLength);

    // indicate we allow Range Requests
    res.addHeader("Accept-Ranges", "bytes");

    if (req.getMethod().equals("HEAD")) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0));
      return;
    }

    try {

      if (isRangeRequest) {
        // set before content is sent
        res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize);
        res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        FileCacheRaf.Raf craf = null;
        try {
          craf = fileCacheRaf.acquire(filename);
          IO.copyRafB(
              craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]);
          log.info(
              "returnFile(): "
                  + UsageLog.closingMessageForRequestContext(
                      HttpServletResponse.SC_PARTIAL_CONTENT, contentLength));
          return;
        } finally {
          if (craf != null) fileCacheRaf.release(craf);
        }
      }

      // Return the file
      ServletOutputStream out = res.getOutputStream();
      IO.copyFileB(file, out, 60000);
      res.flushBuffer();
      out.close();
      if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength));
    }

    // @todo Split up this exception handling: those from file access vs those from dealing with
    // response
    //       File access: catch and res.sendError()
    //       response: don't catch (let bubble up out of doGet() etc)
    catch (FileNotFoundException e) {
      log.error("returnFile(): FileNotFoundException= " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (java.net.SocketException e) {
      log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage());
      log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
    } catch (IOException e) {
      String eName =
          e.getClass().getName(); // dont want compile time dependency on ClientAbortException
      if (eName.equals("org.apache.catalina.connector.ClientAbortException")) {
        log.info(
            "returnFile(): ClientAbortException while sending file: "
                + filename
                + " "
                + e.getMessage());
        log.info(
            "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
        return;
      }

      log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e);
      log.error(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted())
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage());
    }
  }