Ejemplo n.º 1
1
  @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>");
  }
  /**
   * Creates a Discussion Post
   *
   * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter
   * for the POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createPostAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Post) {
      DiscussionManager dm = new DiscussionManager();

      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");

      // Create the discussion post
      DiscussionPost post = new DiscussionPost();
      post.setUserId(userSession.getUserId());
      post.setMessage(req.getParameter("comment"));
      post.setThreadId(Integer.parseInt(req.getParameter("threadId")));

      dm.createPost(post);

      redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId"));
    } else {
      httpNotFound(req, res);
    }
  }
  /**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
  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);
    }
  }
Ejemplo n.º 5
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
  /* good2() reverses the bodies in the if statement */
  private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    if (IO.static_returns_t()) {
      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }
      String username = request.getParameter("username");
      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FIX: logged message does not contain session id */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }

      String username = request.getParameter("username");

      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FLAW: leak session ID to debug log */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    }
  }
Ejemplo n.º 7
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();
    }
  }
Ejemplo n.º 8
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("[Servlet3.doPost]");

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

    out.println("FILTER-REQUEST:" + request.getSession().getAttribute("FILTER-REQUEST"));
    out.println("FILTER-FORWARD:" + request.getSession().getAttribute("FILTER-FORWARD"));
    out.println("FILTER-INCLUDE:" + request.getSession().getAttribute("FILTER"));
  }
  /**
   * This method will open the sample report pdf.
   *
   * @param reportFilePath - full path of the sample report to be shown.
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  private static void showSampleReport(
      String reportFilePath, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (null != request.getSession().getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
        && request
            .getSession()
            .getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
            .toString()
            .equalsIgnoreCase("Y")) {
      ServletOutputStream output = null;
      try {

        FileInputStream fis = new FileInputStream(reportFilePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        try {
          for (int readNum; (readNum = fis.read(buf)) != -1; ) {
            baos.write(buf, 0, readNum); // no doubt here is 0
            // Writes len bytes from the specified byte array starting at offset off to this byte
            // array output stream.
          }

        } catch (IOException ex) {
          ex.printStackTrace();
        }

        if (null != baos) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(baos.size());
          response.setHeader("Content-disposition", "inline; filename=\"" + reportFilePath);
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(baos.toByteArray(), 0, baos.size());

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
Ejemplo n.º 10
0
 private Connection getConnection(HttpServletRequest req) {
   Connection result = (Connection) req.getSession().getAttribute("connection");
   if (result == null) {
     try {
       result =
           DriverManager.getConnection(
               "jdbc:postgresql://localhost:5432/kickstarter", "postgres", "1234");
     } catch (SQLException e) {
       throw new RuntimeException(e);
     }
     req.getSession().setAttribute("connection", result);
   }
   return result;
 }
 private void setDefaultSchema(HttpServletRequest request) {
   String hibernateDefaultSchemaTab =
       (String) request.getSession().getAttribute("xava_hibernateDefaultSchemaTab");
   if (hibernateDefaultSchemaTab != null) {
     request.getSession().removeAttribute("xava_hibernateDefaultSchemaTab");
     XHibernate.setDefaultSchema(hibernateDefaultSchemaTab);
   }
   String jpaDefaultSchemaTab =
       (String) request.getSession().getAttribute("xava_jpaDefaultSchemaTab");
   if (jpaDefaultSchemaTab != null) {
     request.getSession().removeAttribute("xava_jpaDefaultSchemaTab");
     XPersistence.setDefaultSchema(jpaDefaultSchemaTab);
   }
 }
Ejemplo n.º 12
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Utilisateur user = null;

    if (request.getSession(false) != null
        && request.getSession(false).getAttribute("user") != null
        && request.getSession(false).getAttribute("user") instanceof Utilisateur) {
      user = (Utilisateur) request.getSession(false).getAttribute("user");

    } else {

      request.getRequestDispatcher("/login.jsp").forward(request, response);
      return;
    }

    if (!user.getType().equals(TypeUtilisateur.FORMATEUR)) {
      request.getRequestDispatcher("/login.jsp").forward(request, response);
      return;
    }
    // TODO Load logiciel
    int idLogiciel = Integer.parseInt(request.getParameter("idLogiciel"));
    int noOrdreLogiciel = Integer.parseInt(request.getParameter("noOrdreLogiciel"));
    String nomLogiciel = request.getParameter("nomLogiciel");
    String descriptionLogiciel = request.getParameter("descriptionLogiciel");
    String versionLogiciel = request.getParameter("versionLogiciel");
    String editeurLogiciel = request.getParameter("editeurLogiciel");
    int categorieLogiciel = Integer.parseInt(request.getParameter("categorieLogiciel"));
    Profil p = new Profil();

    Profil.Logiciels l = p.new Logiciels();
    l.setIdLogiciel(idLogiciel);
    l.setNoOrdreLogiciel(noOrdreLogiciel);
    l.setNomLogiciel(nomLogiciel);
    l.setDescriptionLogiciel(descriptionLogiciel);
    l.setEditeurLogiciel(editeurLogiciel);
    l.setCategorieLogiciel(categorieLogiciel);
    l.setVersion(versionLogiciel);
    TableLogiciels tl = new TableLogiciels();
    try {
      tl.save(l);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      request.getRequestDispatcher("/error.jsp").forward(request, response);
    }
    request.getRequestDispatcher("/success.jsp").forward(request, response);
  }
  public Event perform(HttpServletRequest request) throws HTMLActionException {

    HttpSession session = request.getSession();
    // look up the adventure transportation
    AdventureComponentManager acm =
        (AdventureComponentManager) session.getAttribute(AdventureKeys.COMPONENT_MANAGER);
    Cart cart = acm.getCart(session);
    String origin = request.getParameter("origin");
    // if we are doing a search for a different flight from the cart page
    if (origin == null) {
      origin = cart.getOrigin();
    } else {
      cart.setOrigin(origin);
    }

    String noTransport = request.getParameter("no_transport");
    String showTransport = request.getParameter("show_flights");
    Locale locale = new Locale("en", "us");
    String destination = cart.getDestination();
    // access catalog component and retrieve data from the database
    List transpDepartureBeans = searchTransportation(origin, destination, locale);
    List transpReturnBeans = searchTransportation(destination, origin, locale);

    // places result bean data in the request
    request.setAttribute("departure_result", transpDepartureBeans);
    request.setAttribute("return_result", transpReturnBeans);
    request.setAttribute("search_target", "transportation");
    return null;
  }
Ejemplo n.º 14
0
  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;
  }
Ejemplo n.º 15
0
  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);
  }
Ejemplo n.º 16
0
  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));
  }
Ejemplo n.º 17
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
Ejemplo n.º 18
0
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
Ejemplo n.º 19
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
Ejemplo n.º 20
0
  /**
   * Parse the case id from the url and then delete it. Finally redirects the response and the
   * request to admCase.jsp
   *
   * @see DatabaseMethods#caseDelete(int)
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    DatabaseMethods dbPoint = new DatabaseMethods();
    HttpSession userSession = request.getSession();

    if (Integer.parseInt(userSession.getAttribute("isadmin").toString()) == 1) {
      int caseId = Integer.parseInt(request.getParameter("caseId"));

      int success = dbPoint.caseDelete(caseId);

      if (success != 0) {
        userSession.setAttribute("caseDelete", "1");
      } else {
        userSession.setAttribute("caseDelete", "0");
      }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/admCase.jsp");
    if (rd != null) {
      rd.forward(request, response);
    }
  }
Ejemplo n.º 21
0
  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;
  }
  public void testRecordsReleaseGet() throws Exception {
    RecordsReleaseDAO rrDAO = new RecordsReleaseDAO(factory);
    List<RecordsReleaseBean> list = rrDAO.getAllRecordsReleasesByPid(102L);
    ViewRecordsReleaseAction viewAction = new ViewRecordsReleaseAction(factory, 9000000000L);

    when(request.getSession()).thenReturn(session);
    //		when(response.getContentType()).thenReturn("text/xml");
    when(response.getWriter()).thenReturn(out);

    when(request.getParameter("index")).thenReturn(String.valueOf("0"));
    when(request.getSession().getAttribute("recRequests")).thenReturn(list);
    when(request.getSession().getAttribute("viewAction")).thenReturn(viewAction);

    servlet.doGet(request, response);
    //		assertTrue(response.getContentType().equals("text/xml"));
  }
Ejemplo n.º 23
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Method execute
   *
   * @param ActionMapping mapping
   * @param ActionForm form
   * @param HttpServletRequest request
   * @param HttpServletResponse response
   * @return ActionForward
   * @throws Exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession();
    // clientXML = (XMLClient) session.getAttribute("client");
    clientXML = XMLClient.getInstance();
    sessionLogin = (String) session.getAttribute("login");

    ajoutsuppressionForm ajoutForm = (ajoutsuppressionForm) form;

    String idperm = ajoutForm.getId1();
    String idrole = ajoutForm.getId2();

    response.setContentType("text/html");

    boolean ajout = clientXML.ajouterPermissionRole(sessionLogin, idperm, idrole);

    if (ajout) {
      String result = "INFO: Permission ajoutée au role";

      session.setAttribute("Resultat", result);
      return mapping.findForward("ok");
    } else {
      String erreur = "ERREUR: Permission non ajoutée au role";

      session.setAttribute("Resultat", erreur);
      return mapping.findForward("failed");
    }
  }
 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");
 }
Ejemplo n.º 26
0
  public void updateTokens(HttpServletRequest request) {
    /** cannot create sessions if response already committed * */
    HttpSession session = request.getSession(false);

    if (session != null) {
      /** create master token if it does not exist * */
      updateToken(session);

      /** create page specific token * */
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        /** first time initialization * */
        if (pageTokens == null) {
          pageTokens = new HashMap<String, String>();
          session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens);
        }

        /** create token if it does not exist * */
        if (isProtectedPageAndMethod(request)) {
          createPageToken(pageTokens, request.getRequestURI());
        }
      }
    }
  }
  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);
    }
  }
Ejemplo n.º 28
0
  public ActionForward execute(
      ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      GpsImportForm gpsForm = (GpsImportForm) form;
      User user = (User) req.getSession().getAttribute("user");
      int entryId = gpsForm.getEntryId();
      String fileName = gpsForm.getFileName();
      String title = gpsForm.getTitle();
      String activityId = gpsForm.getActivityId();
      String xml = gpsForm.getXml();
      log.debug(xml);

      List<GpsTrack> tracks = new TcxParser().parse(xml.getBytes());
      GpsTrack track = tracks.get(0); // Horrible hack.
      createAttachment(user, entryId, fileName, title, activityId, track);
      createGeotag(fileName, track);

      req.setAttribute("status", "success");
      req.setAttribute("message", "");
      log.debug("Returning status: success.");
      return mapping.findForward("results");
    } catch (Exception e) {
      log.fatal("Error processing incoming Garmin XML", e);
      req.setAttribute("status", "failure");
      req.setAttribute("message", e.toString());
      return mapping.findForward("results");
    }
  }
Ejemplo n.º 29
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse reponse)
      throws Exception {
    BeanEcrireCommentaire bean = (BeanEcrireCommentaire) actionForm;
    String contenu = bean.getContenu();
    BeanCommentaire beanCommentaire = new BeanCommentaire();
    beanCommentaire.setContenu(contenu);
    Abonne abonne =
        (Abonne)
            bdutil.getUtilisateur(((Integer) request.getSession().getAttribute("id")).intValue());
    beanCommentaire.setIdRedacteur(abonne.getId());

    Article article = bdart.getArticle(Integer.parseInt(request.getParameter("idArticle")));
    beanCommentaire.setIdArticle(article.getId());

    // beanCommentaire.setId(bdart.getIdLibre());

    if (contenu.equals("")) return mapping.findForward("echec");
    else {

      bdcom.addCommentaire(beanCommentaire.getCommentaire());

      //        bdart.addArticle(beanArticle.getArticle());

      //	beanCommentaire.setIdRedacteur(request.getSession(true));
      //	beanCommentaire.setIdArticle(((Article)request.getAttribute("article")).getId());
      //	bean.setId(BDArticles.getIdLibre())
      /// bdart.addArticle(beanCommentaire.getCommentaire());     // /!\ omg!!!

      return mapping.findForward("succes");
    }
  }