private void requestDispatch(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String page)
      throws ServletException, IOException {

    ctx.getRequestDispatcher(page).include(req, resp);
  }
예제 #2
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext sc = this.getServletContext();
    RequestDispatcher rd1 = sc.getRequestDispatcher(brett);

    String name = request.getParameter("name2");
    String farbe = this.farbeGegner(request, response);
    request.getSession().setAttribute("farbe2", farbe);
    Index.getGame().setNameWeb(name);

    Index.getGame()
        .addSpieler(
            name, Index.getGame().bestimmeFarbe(farbe), Index.getGame().bestimmeKI("Mensch"));
    Index.getGame().starteSpiel();
    this.brettRufen(request, response);
    rd1.forward(request, response);
  }
예제 #3
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession session = req.getSession(false);
   ServletContext sc = getServletContext();
   RequestDispatcher rd;
   String strPrizeID = req.getParameter("prizeid");
   if (strPrizeID != null) {
     DataBaseConn DelPrizeDBC = new DataBaseConn();
     String sqlStr = "delete from pthwinnum where id='" + Integer.parseInt(strPrizeID) + "';";
     DelPrizeDBC.execute(sqlStr);
     DelPrizeDBC.connCloseUpdate();
   }
   PageInfoGet objPageInfoGet = new PageInfoGet();
   String strChSql = "select id from pthwinnum";
   objPageInfoGet.generInfo(req, "pthwinnum", strChSql);
   session.setAttribute("userpc", objPageInfoGet.getUserPageConn());
   session.setAttribute("bepagshow", objPageInfoGet.getBeanPageShow());
   rd = sc.getRequestDispatcher("/WEB-INF/usermanage/pth/pthprizepage.jsp");
   rd.forward(req, res);
 }
예제 #4
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);
    }
  }
예제 #5
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 {
    Long timeIni = System.currentTimeMillis();

    HttpSession sesion = request.getSession();

    try {
      // usuario actual
      Usuario usuario = new Usuario();
      if (sesion.getAttribute("usuario") != null) {
        usuario = (Usuario) sesion.getAttribute("usuario");
      }

      // configuración de paginación
      String path = getServletContext().getRealPath("WEB-INF/config.xml");
      int docsPagina = Config.getInitPages(usuario.getId(), path, "documents");
      sesion.setAttribute("configPath", path);

      // privacidad de los documentos
      String cond = "(PRIVADO = 0 OR (PRIVADO = 1 AND ID_USUARIO = " + usuario.getId() + "))";

      // filtro de búsqueda
      String buscar = request.getParameter("buscar");
      if (buscar != null) {
        if (Convert.isValidDate(buscar)) {
          buscar = Utiles.dateToMySQLDate(Convert.parseDate(buscar), false);
        }

        cond += " AND (TITULO LIKE('%" + buscar + "%') ";
        cond += " OR CONTENIDO LIKE('%" + buscar + "%') ";
        cond += " OR ETIQUETAS LIKE('%" + buscar + "%') ";
        cond += " OR FECHA LIKE ('%" + buscar + "%') ";

        for (Usuario u : new UsuarioDAO().findAllUsuario()) {
          if (u.getNombre().toLowerCase().contains(buscar.toLowerCase())
              || u.getApe1().toLowerCase().contains(buscar.toLowerCase())
              || u.getApe2().toLowerCase().contains(buscar.toLowerCase())) {
            cond += " OR ID_USUARIO = " + u.getId();
          }
        }

        cond += ") ";
      }

      DocumentoDAO documentoDAO = new DocumentoDAO();
      sesion.setAttribute(
          "allDocuments", (ArrayList) documentoDAO.findAllDocumento(docsPagina, cond));

      if (count == 1) {
        sesion.setAttribute("dataMenu", (ArrayList) documentoDAO.findAllDocumento(cond));
        count++;
      }

    } catch (Exception ex) {
      Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      Long timeEnd = System.currentTimeMillis();
      System.out.println("Duración de procesado " + getServletName() + ": " + (timeEnd - timeIni));
      ServletContext cont = getServletConfig().getServletContext();
      RequestDispatcher reqDispatcher = cont.getRequestDispatcher("/index.jsp");
      reqDispatcher.forward(request, response);
    }
  }
  /**
   * Main service method for TradeScenarioServlet
   *
   * @param request Object that encapsulates the request to the servlet
   * @param response Object that encapsulates the response from the servlet
   */
  public void performTask(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // Scenario generator for Trade2
    char action = ' ';
    String userID = null;

    // String to create full dispatch path to TradeAppServlet w/ request Parameters
    String dispPath = null; // Dispatch Path to TradeAppServlet

    String scenarioAction = (String) req.getParameter("action");
    if ((scenarioAction != null) && (scenarioAction.length() >= 1)) {
      action = scenarioAction.charAt(0);
      if (action == 'n') { // null;
        try {
          resp.setContentType("text/html");
          PrintWriter out = new PrintWriter(resp.getOutputStream());
          out.println("<HTML><HEAD>TradeScenarioServlet</HEAD><BODY>Hello</BODY></HTML>");
          out.close();
          return;

        } catch (Exception e) {
          Log.error(
              "trade_client.TradeScenarioServlet.service(...)"
                  + "error creating printwriter from responce.getOutputStream",
              e);

          resp.sendError(
              500,
              "trade_client.TradeScenarioServlet.service(...): erorr creating and writing to PrintStream created from response.getOutputStream()");
        } // end of catch
      } // end of action=='n'
    }

    ServletContext ctx = null;
    HttpSession session = null;
    try {
      ctx = getServletConfig().getServletContext();
      // These operations require the user to be logged in. Verify the user and if not logged in
      // change the operation to a login
      session = req.getSession(true);
      userID = (String) session.getAttribute("uidBean");
    } catch (Exception e) {
      Log.error(
          "trade_client.TradeScenarioServlet.service(...): performing "
              + scenarioAction
              + "error getting ServletContext,HttpSession, or UserID from session"
              + "will make scenarioAction a login and try to recover from there",
          e);
      userID = null;
      action = 'l';
    }

    if (userID == null) {
      action = 'l'; // change to login
      TradeConfig.incrementScenarioCount();
    } else if (action == ' ') {
      // action is not specified perform a random operation according to current mix
      // Tell getScenarioAction if we are an original user or a registered user
      // -- sellDeficits should only be compensated for with original users.
      action = TradeConfig.getScenarioAction(userID.startsWith(TradeConfig.newUserPrefix));
    }
    switch (action) {
      case 'q': // quote
        dispPath = tasPathPrefix + "quotes&symbols=" + TradeConfig.rndSymbols();
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'a': // account
        dispPath = tasPathPrefix + "account";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'u': // update account profile
        dispPath = tasPathPrefix + "account";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        String fullName = "rnd" + System.currentTimeMillis();
        String address = "rndAddress";
        String password = "******";
        String email = "rndEmail";
        String creditcard = "rndCC";
        dispPath =
            tasPathPrefix
                + "update_profile&fullname="
                + fullName
                + "&password="******"&cpassword="******"&address="
                + address
                + "&email="
                + email
                + "&creditcard="
                + creditcard;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'h': // home
        dispPath = tasPathPrefix + "home";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'l': // login
        userID = TradeConfig.getUserID();
        String password2 = "xxx";
        dispPath = tasPathPrefix + "login&inScenario=true&uid=" + userID + "&passwd=" + password2;
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        // login is successful if the userID is written to the HTTP session
        if (session.getAttribute("uidBean") == null) {
          System.out.println("TradeScenario login failed. Reset DB between runs");
        }
        break;
      case 'o': // logout
        dispPath = tasPathPrefix + "logout";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'p': // portfolio
        dispPath = tasPathPrefix + "portfolio";
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 'r': // register
        // Logout the current user to become a new user
        // see note in TradeServletAction
        req.setAttribute("TSS-RecreateSessionInLogout", Boolean.TRUE);
        dispPath = tasPathPrefix + "logout";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        userID = TradeConfig.rndNewUserID();
        String passwd = "yyy";
        fullName = TradeConfig.rndFullName();
        creditcard = TradeConfig.rndCreditCard();
        String money = TradeConfig.rndBalance();
        email = TradeConfig.rndEmail(userID);
        String smail = TradeConfig.rndAddress();
        dispPath =
            tasPathPrefix
                + "register&Full Name="
                + fullName
                + "&snail mail="
                + smail
                + "&email="
                + email
                + "&user id="
                + userID
                + "&passwd="
                + passwd
                + "&confirm passwd="
                + passwd
                + "&money="
                + money
                + "&Credit Card Number="
                + creditcard;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
      case 's': // sell
        dispPath = tasPathPrefix + "portfolioNoEdge";
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        Collection holdings = (Collection) req.getAttribute("holdingDataBeans");
        int numHoldings = holdings.size();
        if (numHoldings > 0) {
          // sell first available security out of holding

          Iterator it = holdings.iterator();
          boolean foundHoldingToSell = false;
          while (it.hasNext()) {
            HoldingDataBean holdingData = (HoldingDataBean) it.next();
            if (!(holdingData.getPurchaseDate().equals(new java.util.Date(0)))) {
              Integer holdingID = holdingData.getHoldingID();

              dispPath = tasPathPrefix + "sell&holdingID=" + holdingID;
              ctx.getRequestDispatcher(dispPath).include(req, resp);
              foundHoldingToSell = true;
              break;
            }
          }
          if (foundHoldingToSell) break;
          if (Log.doTrace())
            Log.trace(
                "TradeScenario: No holding to sell -switch to buy -- userID = "
                    + userID
                    + "  Collection count = "
                    + numHoldings);
        }
        // At this point: A TradeScenario Sell was requested with No Stocks in Portfolio
        // This can happen when a new registered user happens to request a sell before a buy
        // In this case, fall through and perform a buy instead

        /* Trade 2.037: Added sell_deficit counter to maintain correct buy/sell mix.
         * When a users portfolio is reduced to 0 holdings, a buy is requested instead of a sell.
         * This throws off the buy/sell mix by 1. This results in unwanted holding table growth
         * To fix this we increment a sell deficit counter to maintain the correct ratio in getScenarioAction
         * The 'z' action from getScenario denotes that this is a sell action that was switched from a buy
         * to reduce a sellDeficit
         */
        if (userID.startsWith(TradeConfig.newUserPrefix) == false) {
          TradeConfig.incrementSellDeficit();
        }
      case 'b': // buy
        String symbol = TradeConfig.rndSymbol();
        String amount = TradeConfig.rndQuantity() + "";

        dispPath = tasPathPrefix + "quotes&symbols=" + symbol;
        ctx.getRequestDispatcher(dispPath).include(req, resp);

        dispPath = tasPathPrefix + "buy&quantity=" + amount + "&symbol=" + symbol;
        ctx.getRequestDispatcher(dispPath).include(req, resp);
        break;
    } // end of switch statement
  }