예제 #1
0
  @Override
  public final void service(final HttpServletRequest req, final HttpServletResponse res)
      throws IOException {

    final HTTPContext http = new HTTPContext(req, res, this);
    final boolean restxq = this instanceof RestXqServlet;
    try {
      run(http);
      http.log("", SC_OK);
    } catch (final HTTPException ex) {
      http.status(ex.getStatus(), Util.message(ex), restxq);
    } catch (final LoginException ex) {
      http.status(SC_UNAUTHORIZED, Util.message(ex), restxq);
    } catch (final IOException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final QueryException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final Exception ex) {
      final String msg = Util.bug(ex);
      Util.errln(msg);
      http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq);
    } finally {
      if (Prop.debug) {
        Util.outln("_ REQUEST _________________________________" + Prop.NL + req);
        final Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
          final String key = en.nextElement();
          Util.outln(Text.LI + key + Text.COLS + req.getHeader(key));
        }
        Util.out("_ RESPONSE ________________________________" + Prop.NL + res);
      }
      http.close();
    }
  }
예제 #2
0
  /**
   * Validates the login. Writes the isValid flag into the session along with the current user.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean validateLogin(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // Creates a user database access bean.
    UserManager userManager = new UserManager();
    // (no setSession() here, since user may not exist yet)

    // Validates the login
    String username = req.getParameter("Username");
    String password = req.getParameter("Password");
    boolean isValid = userManager.isValidUser(username, password);
    boolean isAdmin = userManager.isAdmin(username);

    // To allow bootstrapping the system, if there are no users
    // yet, set this session valid, and grant admin privileges.
    if (userManager.getRecords().isEmpty()) {
      isValid = true;
      isAdmin = true;
    }

    if (isValid) {
      // Writes User object and validity flag to the session
      session.setAttribute("user", new User(username, password, isAdmin));
      session.setAttribute("isValid", new Boolean(isValid));
    } else {
      Util.putMessagePage(res, "Invalid user or password");
      return false;
    }
    return isValid;
  }
예제 #3
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);
    }
  }
예제 #4
0
  /**
   * Creates a db connecton.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean createDbConnection(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // At this point a driver and connection may already be set
    // up.  So here it first tests if a connection can be made.
    // If not, set params up, and test the setup.
    if (ConnManager.getConn() == null) {
      ConnManager.getInstance()
          .setLoginParams(
              session.getAttribute("dbtDbDriver"),
              session.getAttribute("dbtDbUrl"),
              session.getAttribute("dbtDbUser"),
              session.getAttribute("dbtDbPassword"));
      if (ConnManager.getConn() == null) {
        Util.putMessagePage(res, "Cannot login to DBT database");
        // Invalidates the session in case connection is "stuck" in error
        session.invalidate();
        return false;
      }
    }
    return true;
  }
예제 #5
0
  /**
   * Initializes the database context, based on the initial servlet context. Parses all context
   * parameters and passes them on to the database context.
   *
   * @param sc servlet context
   * @throws IOException I/O exception
   */
  public static synchronized void init(final ServletContext sc) throws IOException {
    // check if HTTP context has already been initialized
    if (init) return;
    init = true;

    // set web application path as home directory and HTTPPATH
    final String webapp = sc.getRealPath("/");
    Options.setSystem(Prop.PATH, webapp);
    Options.setSystem(GlobalOptions.WEBPATH, webapp);

    // bind all parameters that start with "org.basex." to system properties
    final Enumeration<String> en = sc.getInitParameterNames();
    while (en.hasMoreElements()) {
      final String key = en.nextElement();
      if (!key.startsWith(Prop.DBPREFIX)) continue;

      String val = sc.getInitParameter(key);
      if (key.endsWith("path") && !new File(val).isAbsolute()) {
        // prefix relative path with absolute servlet path
        Util.debug(key.toUpperCase(Locale.ENGLISH) + ": " + val);
        val = new IOFile(webapp, val).path();
      }
      Options.setSystem(key, val);
    }

    // create context, update options
    if (context == null) {
      context = new Context(false);
    } else {
      context.globalopts.setSystem();
      context.options.setSystem();
    }

    // start server instance
    if (!context.globalopts.get(GlobalOptions.HTTPLOCAL)) new BaseXServer(context);
  }
예제 #6
0
  /** Cracks the command and invokes the appropriate next screen */
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    try {
      // Sets up session tracking
      ServletContext context = getServletContext();
      HttpSession session = req.getSession();

      // Gets command, which says what button was pressed
      String command = req.getParameter("command");
      if (command == null) {
        Util.putMessagePage(res, "Please go back and use a button");
        return;
      }

      // "Exit" invalidates the session
      if (command.equals("Exit")) {
        Util.exitSession(session, res);
        return;
      }

      // "Relogin" invalidates the session and starts over
      if (command.equals("Relogin")) {
        session.invalidate();
        RequestDispatcher dispatcher = context.getRequestDispatcher(Util.BASE + "index.jsp");
        dispatcher.forward(req, res);
        return;
      }

      // At this point the session may be new, or may be already
      // validated.  If session is not valid, or if a login was
      // specified, do a dbt database login, and validate the
      // user's login.
      if (!Util.isSessionValid(session, null) || req.getParameter("Username") != null) {
        if (!createDbConnection(session, req, res)) return;
        if (!validateLogin(session, req, res)) return;
      }

      // Shows the DBT_DB records
      if (command.indexOf("Databases") > -1) {
        RequestDispatcher dispatcher = context.getRequestDispatcher(Util.BASE + "ShowDbs.jsp");
        dispatcher.forward(req, res);
        return;
      }

      // Displays all the history records
      if (command.indexOf("History") > -1) {
        RequestDispatcher dispatcher = context.getRequestDispatcher(Util.BASE + "ShowHistory.jsp");
        dispatcher.forward(req, res);
        return;
      }

      // Changes the user's password
      if (command.indexOf("Password") > -1) {
        RequestDispatcher dispatcher =
            context.getRequestDispatcher(Util.BASE + "ChangePassword.jsp");
        dispatcher.forward(req, res);
        return;
      }

      // Performs admin functions
      if (command.indexOf("Admin") > -1) {
        RequestDispatcher dispatcher = context.getRequestDispatcher(Util.BASE + "AdminFnc.jsp");
        dispatcher.forward(req, res);
        return;
      }

      Util.putMessagePage(
          res, "<p>Dbtracker internal error<p>Unknown command in " + getServletInfo());
    } catch (ServletException e) {
      throw e;
    } catch (IOException e) {
      throw e;
    } catch (Throwable t) {
      Util.putExceptionPage(res, t);
    }
  }