private void processReturn(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    // System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
      // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
      resp.sendRedirect(returnURL);
    } else {
      HttpSession session = req.getSession(true);

      // ((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

      Subject subject = new Subject();

      // TODO: hardcoded to jetty - rewrite
      // *******************************************************
      DefaultIdentityService _identityService = new DefaultIdentityService();
      UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

      Authentication cached = new HttpSessionAuthentication(session, user);
      session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
      // *******************************************************

      resp.sendRedirect(returnURL);
    }
  }
Exemple #2
1
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {

      String target = ((HttpServletRequest) request).getRequestURI();

      HttpSession session = ((HttpServletRequest) request).getSession();

      if (session == null) {
        /* まだ認証されていない */
        session = ((HttpServletRequest) request).getSession(true);
        session.setAttribute("target", target);
        ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
      } else {
        Object loginCheck = session.getAttribute("login");
        if (loginCheck == null) {
          /* まだ認証されていない */
          session.setAttribute("target", target);
          ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
        }
      }

      chain.doFilter(request, response);

    } catch (ServletException se) {
    } catch (IOException e) {
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>Page2</title></head><body>");
    Users tmpUser = null;
    HttpSession session;

    tmpUser = usersService.findByLogin(request.getParameter("login"));
    if (tmpUser != null) {
      if ((tmpUser.getPassword()).equals(request.getParameter("password"))) {
        session = request.getSession(true);
        session.setAttribute("users", tmpUser);
        response.sendRedirect("http://localhost:8080/orders");
      } else {
        out.print("Access denied :(");
      }

    } else {
      String login = request.getParameter("login");
      String pass = request.getParameter("password");
      tmpUser = new Users(login, pass);
      usersService.saveUsers(tmpUser);
      session = request.getSession(true);
      session.setAttribute("users", tmpUser);
      response.sendRedirect("http://localhost:8080/orders");
    }
    out.print("</body></html>");
  }
Exemple #4
1
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    PrintWriter out = response.getWriter();
    StringBuilder sb = new StringBuilder();

    HashMap<String, String> userInfo = (HashMap<String, String>) session.getAttribute("userInfo");
    String ticket = request.getParameter("ticket");

    if (userInfo == null) {
      response.sendRedirect(response.encodeRedirectUrl(request.getContextPath() + "/SignIn"));
    } else {
      if (userInfo.get("role").equals("technician")) {
        sb.append(LayoutProvider.getInstance().getLoggedInHeader(userInfo.get("name")));
        sb.append("<div id=\"body\">");
        sb.append(
            "<h3>Schedule Confirmation</h3><p>You have scheduled <strong>ticket # "
                + ticket
                + "</strong></p>");
        if (ticket != null) {
          List<String> tickets;
          try {
            if (userInfo.get("tickets").equals("")) {
              tickets = null;
            } else {
              tickets = Arrays.asList(userInfo.get("tickets").split("\\,"));
            }
          } catch (Exception ex) {
            System.out.println("PayBill: error splitting tickets");
            tickets = null;
          }
          String remaining = "";
          if (tickets != null && tickets.size() > 0) {
            for (String t : tickets) {
              if (!t.equals(ticket)) {
                remaining += t + ",";
              }
            }
            if (remaining.length() > 0) remaining = remaining.substring(0, remaining.length() - 1);
          } else {
            remaining = "";
          }
          userInfo.put("tickets", remaining);
        }
        sb.append("</div>");
      } else {
        sb.append("<h2>Error</h2>");
        sb.append("<p>You do not have access to this page.</p>");
        sb.append("</div>");
      }
    }
    out.println(sb.toString());
    out.close();
  }
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    log.info("########## START EDIT EVENT POST ###########");

    // Check for valid user session
    lpo.User user = UserManager.GetUser();

    if (user == null) resp.sendRedirect("WelcomePage.jsp");

    // get event from datastore
    String eventKey = req.getParameter("k");

    // pull the event object out
    lpo.Event event = EventManager.GetEvent(eventKey);

    String eventName = req.getParameter("eventName").trim();
    String description = req.getParameter("description").trim();

    boolean formIsComplete = true;

    int minParticipants = 0;
    try {
      minParticipants = Integer.parseInt(req.getParameter("minParticipants"));
    } catch (Exception e) {
      log.info("ERROR PARSING MIN PARTICIPANTS: " + e.toString());
      formIsComplete = false;
    }

    log.info("FORM VARS : " + eventName + " " + description + " " + minParticipants);

    if (eventName == null
        || eventName.isEmpty()
        || description == null
        || description.isEmpty()
        || minParticipants < 1) {

      formIsComplete = false;
    }

    if (formIsComplete) {

      // create event and populate available attributes
      event.setName(eventName);
      event.setDescription(description);
      event.setMinParticipants(minParticipants);

      // persist to database
      DataAccessManager.UpdateEvent(event);

      resp.sendRedirect("/Menu");
    } else {
      // reshow the same jsp page with error message :
      req.getRequestDispatcher("/WEB-INF/EditEvent.jsp").forward(req, resp);
    }

    return;
  }
  /* goodG2B() - use goodsource and badsink by moving BadSource and BadSink to after return */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";

      if (data != null) {
        /* This prevents \r\n (and other chars) and should prevent incidentals such
         * as HTTP Response Splitting and HTTP Header Injection.
         */
        URI u;
        try {
          u = new URI(data);
        } catch (URISyntaxException e) {
          response.getWriter().write("Invalid redirect URL");
          return;
        }
        /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */
        response.sendRedirect(data);
        return;
      }
    }

    if (true) return; /* INCIDENTAL: CWE 571 Expression is Always True.
		  We need the "if(true)" because the Java Language Spec requires that
		  unreachable code generate a compiler error */

    /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
    {
      Logger log_bad = Logger.getLogger("local-logger");

      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }

      if (data != null) {
        /* This prevents \r\n (and other chars) and should prevent incidentals such
         * as HTTP Response Splitting and HTTP Header Injection.
         */
        URI u;
        try {
          u = new URI(data);
        } catch (URISyntaxException e) {
          response.getWriter().write("Invalid redirect URL");
          return;
        }
        /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */
        response.sendRedirect(data);
        return;
      }
    }
  }
 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   Owner owner = DatastoreManager.getCurrentOwner();
   if (owner == null) {
     UserService userService = UserServiceFactory.getUserService();
     resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
     return;
   }
   resp.sendRedirect("/driverselection.jsp");
 }
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    /*String us = req.getParameter("usuario");
    String pw = req.getParameter("passw");

    Cuenta profSeverus = new Cuenta("severus","1234");
    Cuenta profAlbus = new Cuenta("albus","6789");
    Cuenta secreYayita = new Cuenta("yayita","condorito123");

    PersistenceManager pm = PMF.get().getPersistenceManager();
    try{


    }catch(Exception e){

    	System.out.println(e);
    	PrintWriter out = resp.getWriter();
    	resp.setContentType("text/html");
    	resp.getWriter().println("Ocurrio un error, <a href='inicio.jsp'>vuelva a intentarlo</a>");
    }finally{
    	pm.close();
    }
    */
    resp.setContentType("text/plain");
    String us = req.getParameter("usuario");
    String pw = req.getParameter("passw");

    final PersistenceManager pm = PMF.get().getPersistenceManager();
    if (us.equals("severus") && pw.equals("1234")) {
      resp.getWriter().println("bienevenido profesor Severus Snape");
      resp.sendRedirect("/bienvenidoP.jsp");
    }
    if (us.equals("albus") && pw.equals("6789")) {
      resp.getWriter().println("bienevenido profesor Albus");
      resp.sendRedirect("/bienvenidoP.jsp");
    }
    if (us.equals("yayita") && pw.equals("condorito123")) {
      resp.getWriter().println("bienevenido secretaria yayita");
      resp.sendRedirect("/bienvenidoS.jsp");
    }

    try {

      /*if(us==cuenta.getUsuario()&&pw==cuenta.getContrasea()){
      	resp.getWriter().println("bienevenido alumno"+cuenta.getUsuario());
      	resp.sendRedirect("/bienvenidoA.jsp");
      }*/

    } catch (Exception e) {
      System.out.println(e);
      resp.getWriter().println("Ocurriñ un error, vuelva a intentarlo.");
      resp.sendRedirect("/index.jsp");
    } finally {
      pm.close();
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    String exitParam = req.getParameter("exit");
    String deleteParam = req.getParameter("delete");
    String settingsParam = req.getParameter("settings");

    if ("settings".equals(settingsParam)) {
      resp.sendRedirect("/profileSettings");
      return;
    }

    if ("exit".equals(exitParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/login");
    }

    if ("delete".equals(deleteParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      try {
        UserRepository.deleteUser((User) session.getAttribute("user_a"));
      } catch (SQLException e) {
        req.setAttribute("message", "Some problems with server");
        resp.sendRedirect("/profile");

        e.printStackTrace();
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/welcome");
    }
  }
  /* goodG2B() - use goodsource and badsink by moving BadSource and BadSink to after return */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";

      /* POTENTIAL FLAW: Input not verified before inclusion in redirect */
      response.sendRedirect("/author.jsp?lang=" + data);
    }

    if (true) return; /* INCIDENTAL: CWE 571 Expression is Always True.
		  We need the "if(true)" because the Java Language Spec requires that
		  unreachable code generate a compiler error */

    /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
    {
      Logger log_bad = Logger.getLogger("local-logger");

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }

      /* POTENTIAL FLAW: Input not verified before inclusion in redirect */
      response.sendRedirect("/author.jsp?lang=" + data);
    }
  }
  private void handleRemoveFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("removing feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String feedId = request.getParameter(PARAM_FEED_ID);

      LOG.info(String.format("Removing feed %s for user %s", feedId, user));

      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (feedId == null || feedId.equals("")) {
        LOG.error("feed not specified");
        // ttt1 show some error
        return;
      }

      if (user.feedIds.remove(
          feedId)) { // ttt2 clean up the global feed table; that's probably better done if nobody
                     // accesses a feed for 3 months or so
        userDb.updateFeeds(user);
        LOG.info(String.format("Removed feed %s for user %s", feedId, user));
      } else {
        LOG.info(String.format("No feed found with ID %s for user %s", feedId, user));
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
Exemple #12
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   ArrayList<String> ar = new ArrayList<String>();
   boolean flag = false;
   Cookie[] cArr = req.getCookies();
   if (cArr != null) {
     for (int i = 0; i < cArr.length; i++) {
       Cookie c0 = cArr[i];
       if (c0.getName().equals("Name") && !c0.getValue().equals("Logout")) {
         res.sendRedirect("index.html");
         flag = true;
       }
     }
   }
   if (flag == false) res.sendRedirect("Login.html");
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

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

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
 public void service(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession sess = req.getSession(false);
   sess.invalidate();
   System.out.println("Session Closed");
   res.sendRedirect("index.html");
 }
  /* good1() reverses the GoodSinkBody and the BadSinkBody so that the BadSinkBody never runs */
  private void good1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    {
      response.sendRedirect("/test");
      /* FIX: no code after the redirect */

    }
    if (true)
      return; /* INCIDENTAL: CWE 571 Expression is Always True.  We need the "if(true)" because the Java Language Spec requires that unreachable code generate a compiler error */
    /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
    {
      response.sendRedirect("/test");

      /* FLAW: code after the redirect is undefined */
      IO.writeLine("doing some more things here after the redirect");
    }
  }
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
Exemple #18
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.STATIC_FINAL_TRUE) {
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (data != null) {
      /* This prevents \r\n (and other chars) and should prevent incidentals such
       * as HTTP Response Splitting and HTTP Header Injection.
       */
      URI uri;
      try {
        uri = new URI(data);
      } catch (URISyntaxException exceptURISyntax) {
        response.getWriter().write("Invalid redirect URL");
        return;
      }
      /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */
      response.sendRedirect(data);
      return;
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   ProfesorRepository profesores = (ProfesorRepository) context.getBean("profesorRepository");
   try {
     String id = request.getParameter("id");
     int idProf = Integer.parseInt(id);
     String cedula = request.getParameter("cedula");
     String nombre = request.getParameter("nombre");
     String titulo = request.getParameter("titulo");
     String area = request.getParameter("area");
     String telefono = request.getParameter("telefono");
     Profesor prof = profesores.findProfesor(idProf);
     try {
       if (cedula != null) prof.setCedula(cedula);
       if (nombre != null) prof.setNombre(nombre);
       if (titulo != null) prof.setTitulo(titulo);
       if (area != null) prof.setArea(area);
       if (telefono != null) prof.setTelefono(telefono);
       profesores.updateProfesor(prof);
     } catch (Exception e) {
     }
     response.sendRedirect("listaProfesores");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
  /* goodG2B() - use goodsource and badsink by changing the "if" so that
   * both branches use the GoodSource */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (data != null) {
      /* This prevents \r\n (and other chars) and should prevent incidentals such
       * as HTTP Response Splitting and HTTP Header Injection.
       */
      URI uri;
      try {
        uri = new URI(data);
      } catch (URISyntaxException exceptURISyntax) {
        response.getWriter().write("Invalid redirect URL");
        return;
      }
      /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */
      response.sendRedirect(data);
      return;
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   EstacionBombeoModule module = (EstacionBombeoModule) context.getBean("estacionBombeoModule");
   try {
     String presionSalida = request.getParameter("presionSalida");
     int presionSalidaObj = Integer.parseInt(presionSalida);
     String presionEntrada = request.getParameter("presionEntrada");
     int presionEntradaObj = Integer.parseInt(presionEntrada);
     String cantidadBombas = request.getParameter("cantidadBombas");
     int cantidadBombasObj = Integer.parseInt(cantidadBombas);
     String capacidadMaxima = request.getParameter("capacidadMaxima");
     int capacidadMaximaObj = Integer.parseInt(cantidadBombas);
     String idAcueducto = request.getParameter("idAcueducto");
     int idAcueductoObj = Integer.parseInt(idAcueducto);
     String encargado = request.getParameter("encargado");
     String tipo = request.getParameter("tipo");
     String telefono = request.getParameter("telefono");
     String nombreEstacion = request.getParameter("nombreEstacion");
     module.insertar(
         presionSalidaObj,
         tipo,
         capacidadMaximaObj,
         cantidadBombasObj,
         encargado,
         telefono,
         presionEntradaObj,
         idAcueductoObj,
         nombreEstacion);
     response.sendRedirect("listaEstacionBombeos");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward(e.getMessage(), request, response);
   }
 }
 private void handleOpenArticle(
     Request request, HttpServletResponse httpServletResponse, String target) throws Exception {
   try {
     int k1 = target.indexOf('/', 1);
     int k2 = target.indexOf('/', k1 + 1);
     String feedId = target.substring(k1 + 1, k2);
     String strSeq = target.substring(k2 + 1);
     int seq = Integer.parseInt(strSeq);
     Article article = articleDb.get(feedId, seq);
     LoginInfo loginInfo = userHelpers.getLoginInfo(request);
     // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something
     // better, e.g. sign up
     ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId);
     if (readArticlesColl == null) {
       readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId);
     }
     if (!readArticlesColl.isRead(seq)) {
       readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles);
       readArticlesCollDb.add(readArticlesColl);
     }
     String s =
         URIUtil.encodePath(article.url)
             .replace("%3F", "?")
             .replace("%23", "#"); // ttt2 see how to do this right
     httpServletResponse.sendRedirect(s);
   } catch (Exception e) {
     WebUtils.showResult(
         String.format("Failed to get article for path %s. %s", target, e),
         "/",
         request,
         httpServletResponse);
   }
 }
  /* uses badsource and badsink - see how tools report flaws that don't always occur */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      data = ""; /* Initialize data */
      /* read input from URLConnection */
      {
        URLConnection urlConnection = (new URL("http://www.example.org/")).openConnection();
        BufferedReader readerBuffered = null;
        InputStreamReader readerInputStream = null;
        try {
          readerInputStream = new InputStreamReader(urlConnection.getInputStream(), "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data from a web server with URLConnection */
          /* This will be reading the first "line" of the response body,
           * which could be very long if there are no newlines in the HTML */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* clean up stream reading objects */
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }
        }
      }
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (data != null) {
      /* This prevents \r\n (and other chars) and should prevent incidentals such
       * as HTTP Response Splitting and HTTP Header Injection.
       */
      URI uri;
      try {
        uri = new URI(data);
      } catch (URISyntaxException exceptURISyntax) {
        response.getWriter().write("Invalid redirect URL");
        return;
      }
      /* POTENTIAL FLAW: redirect is sent verbatim; escape the string to prevent ancillary issues like XSS, Response splitting etc */
      response.sendRedirect(data);
      return;
    }
  }
 @Override
 public void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws IOException, ServletException {
   if (CookieUtils.getCookie(req, "name") == null) {
     req.getRequestDispatcher("/login.jsp").forward(req, resp);
   } else {
     resp.sendRedirect("/analyze");
   }
 }
Exemple #26
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.setCharacterEncoding("gb2312");
   String delete = request.getParameter("delete");
   Login loginBean = null;
   HttpSession session = request.getSession(true);
   try {
     loginBean = (Login) session.getAttribute("loginBean");
     boolean b = loginBean.getLogname() == null || loginBean.getLogname().length() == 0;
     if (b) response.sendRedirect("login.jsp"); // 重定向到登录页面
     LinkedList<String> car = loginBean.getCar();
     car.remove(delete);
   } catch (Exception exp) {
     response.sendRedirect("login.jsp"); // 重定向到登录页面
   }
   RequestDispatcher dispatcher = request.getRequestDispatcher("lookShoppingCar.jsp");
   dispatcher.forward(request, response); // 转发
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    LookupService lookupService = new LookupService();
    coshms.ejb.pathalogy.PathalogyRemote pthRemoteSB = lookupService.lookupPathalogyBean();

    java.util.ArrayList pthTestDomainList = new java.util.ArrayList();
    int tStatus = 0;

    if (request.getParameter("status") != null) {
      tStatus = 1;
    }
    String[] cid = request.getParameterValues("contentId");
    String[] cname = request.getParameterValues("cname");
    String[] unit = request.getParameterValues("unit");
    String[] minvalue = request.getParameterValues("minvalue");
    String[] maxvalue = request.getParameterValues("maxvalue");

    for (int i = 0; i < cname.length; i++) {
      PthTestContentsInfo pthTestCon =
          new PthTestContentsInfo(
              "",
              Integer.parseInt(cid[i]),
              cname[i],
              Double.parseDouble(minvalue[i]),
              Double.parseDouble(maxvalue[i]),
              unit[i]);
      pthTestDomainList.add(pthTestCon);
    }
    int empId = 1;

    if (pthRemoteSB.pthTestDomainEdit(
        pthTestDomainList,
        request.getParameter("tname"),
        tStatus,
        Integer.parseInt(request.getParameter("tcost")),
        empId,
        Integer.parseInt(request.getParameter("testId"))))
      response.sendRedirect("pthMessage.jsp?message=Pathalogy Test Edit Successfully");
    else response.sendRedirect("pthMessage.jsp?message=Try Again");
    out.close();
  }
Exemple #28
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   final String button = request.getParameter("button");
   if (button.equals("create")) {
     Cookie cookie = new Cookie("carlos-cookie-test", "");
     refreshCookie(cookie, response);
     response.sendRedirect("cookie");
   } else if (button.equals("no-pass")) {
     response.sendRedirect("cookie");
   } else if (button.equals("delete")) {
     Cookie cookie = getCookie("carlos-cookie-test", request);
     if (cookie != null) {
       cookie.setMaxAge(0);
       response.addCookie(cookie);
     }
     response.sendRedirect("cookie");
   } else {
     throw new RuntimeException("unknown action: " + button);
   }
 }
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Identity identity = facade.login(username, password);
    // if login successfully, mark in the session:
    request.getSession().setAttribute(Identity.IDENTITY, identity);
    response.sendRedirect("manageCategory.c");

    return null;
  }
  // required doFilter method
  // redirects users trying to access restricted part of site when not logged in
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws java.io.IOException, javax.servlet.ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession();

    String loggedIn = (String) session.getAttribute("loggedIn");

    if (loggedIn == null) res.sendRedirect("../pleaselogin.html");
    else if (loggedIn == "yes") chain.doFilter(request, response);
  }