Exemplo n.º 1
0
  @Test
  public void testCookies_whenCookiesArePresent() {

    Collection<Cookie> cookies = new ArrayList<>();
    cookies.add(new Cookie("cookie1", "cookie1value"));
    cookies.add(new Cookie("cookie2", "cookie2value"));

    Map<String, String> expected = new HashMap<>();
    for (Cookie cookie : cookies) {
      expected.put(cookie.getName(), cookie.getValue());
    }

    Cookie[] cookieArray = cookies.toArray(new Cookie[cookies.size()]);

    when(servletRequest.getCookies()).thenReturn(cookieArray);

    assertTrue(
        "The count of cookies returned should be the same as those in the request",
        request.cookies().size() == 2);

    assertEquals(
        "A Map of Cookies should have been returned because they exist",
        expected,
        request.cookies());
  }
Exemplo n.º 2
0
  /**
   * Gets user email address, first and last name, puts them into a User object, puts the Object
   * user into session scope, adds a Cookie called emailCookie with the email address as its value,
   * stores the away into a EmailList.txt file that is store in openshift in OPENSHIFT_DATA_DIR
   * folder and locally under WEB-INF.
   *
   * @param request provides parameters for user information
   * @param response add the cookie to the response
   * @return String representing URL to go to next
   */
  private String registerUser(HttpServletRequest request, HttpServletResponse response) {

    // get the user data
    String email = request.getParameter("email");
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    // store the data in a User object
    User user = new User();
    user.setEmail(email);
    user.setFirstName(firstName);
    user.setLastName(lastName);

    // write the User object to a file
    // ServletContext sc = getServletContext();
    // String path = sc.getRealPath("/WEB-INF/EmailList.txt");
    String path = this.getActualFile();
    System.out.println("Path: " + path);
    UserIO.add(user, path);

    // store the User object as a session attribute
    HttpSession session = request.getSession();
    session.setAttribute("user", user);

    // add a cookie that stores the user's email to browser
    Cookie c = new Cookie("emailCookie", email);
    c.setMaxAge(60 * 60 * 24 * 365 * 2); // set age to 2 years
    c.setPath("/"); // allow entire app to access it
    response.addCookie(c);

    // create and return a URL for the appropriate Download page
    String productCode = (String) session.getAttribute("productCode");
    String url = "/" + productCode + "_download.jsp";
    return url;
  }
Exemplo n.º 3
0
  private void addCookie(ExternalContext extContext, Flash flash) {
    // Do not update the cookie if redirect after post
    if (flash.isRedirect()) {
      return;
    }

    String thisRequestSequenceString = null;
    HttpServletResponse servletResponse = null;
    // PortletRequest portletRequest = null;
    Object thisRequestSequenceStringObj, response = extContext.getResponse();

    thisRequestSequenceStringObj =
        extContext.getRequestMap().get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME);
    if (null == thisRequestSequenceStringObj) {
      return;
    }
    thisRequestSequenceString = thisRequestSequenceStringObj.toString();

    if (response instanceof HttpServletResponse) {
      servletResponse = (HttpServletResponse) response;
      Cookie cookie =
          new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString);
      cookie.setMaxAge(-1);
      servletResponse.addCookie(cookie);
    } else {
      /**
       * *** portletRequest = (PortletRequest) request; // You can't add a cookie in portlet. //
       * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
       * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
       * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *******
       */
    }
  }
Exemplo n.º 4
0
 /**
  * 设置cookie
  *
  * @param response
  * @param key = asuraSessionId
  * @param value = sessionId
  */
 public void saveCookie(final HttpServletResponse response, final String key, final String value) {
   final Cookie cookie = new Cookie(key, value);
   cookie.setDomain(DOMAIN);
   cookie.setMaxAge(604800);
   cookie.setPath("/");
   response.addCookie(cookie);
 }
Exemplo n.º 5
0
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Cookie[] cookies = request.getCookies();

    int userID = -1;
    boolean newUser = false;

    // determine whether we've seen this user before
    if (cookies != null) {
      for (Cookie c : cookies) {
        if (c.getName().equals("userID")) {
          userID = Integer.parseInt(c.getValue());
          logger.log(Level.INFO, "Existing user: "******"userID", String.valueOf(userID));
      response.addCookie(c);
      logger.log(Level.INFO, "New user: "******"text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();

    String title = "Cookie Servlet";
    String bootstrapHeader =
        "<!DOCTYPE html>"
            + "<html lang=\"en\">\n"
            + "	<head>\n"
            + "		<title>"
            + title
            + "</title>\n"
            + "		<meta charset=\"utf-8\">\n"
            + "		<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
            + "		<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n"
            + "		<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n"
            + "		<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n"
            + "	</head>\n";

    String body =
        "	<body>\n"
            + "		<div class=\"container\">\n"
            + "			<p>Hello, "
            + (newUser ? "new" : "existing")
            + " user!</p>\n"
            + "		</div>\n"
            + "	</body>\n";

    String footer = "</html>";

    String page = bootstrapHeader + body + footer;
    out.println(page);
  }
Exemplo n.º 6
0
 private void processSessionCookie(HttpSession session) {
   if (null == response || null == session) {
     // No response or session object attached, skip the pre processing
     return;
   }
   // cookieOverWritten - Flag to filter multiple "Set-Cookie" headers
   Object cookieOverWritten = getAttribute("COOKIE_OVERWRITTEN_FLAG");
   if (null == cookieOverWritten && isSecure() && isRequestedSessionIdFromCookie()) {
     // Might have created the cookie in SSL protocol and tomcat will
     // loose the session
     // if there is change in protocol from HTTPS to HTTP. To avoid this,
     // trick the browser
     // using the HTTP and HTTPS session cookie.
     Cookie cookie =
         new Cookie("JSESSIONID", RequestUtil.getSessionWithoutSuffix(session.getId()));
     cookie.setMaxAge(-1); // Life of the browser or timeout
     String contextPath = getContextPath();
     if ((contextPath != null) && (contextPath.length() > 0)) {
       cookie.setPath(contextPath);
     } else {
       cookie.setPath("/");
     }
     response.addCookie(cookie); // Adding an "Set-Cookie" header to the
     // response
     setAttribute("COOKIE_OVERWRITTEN_FLAG", "true"); // To avoid multiple
     // "Set-Cookie"
     // header
   }
 }
 public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) {
   for (int i = 0; i < cookies.length; i++) {
     Cookie cookie = cookies[i];
     if (cookieName.equals(cookie.getName())) return (cookie.getValue());
   }
   return (defaultValue);
 }
Exemplo n.º 8
0
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   Cookie[] cookies = request.getCookies();
   boolean localeAlreadySetupInCookie = false;
   if (null != cookies) {
     Cookie cookie = null;
     for (int i = 0; i < cookies.length; i++) {
       cookie = cookies[i];
       if ((null != cookie) && COOKIENAME_LOCALE.equals(cookie.getName())) {
         localeAlreadySetupInCookie = true;
         break;
       }
     }
   }
   if (!localeAlreadySetupInCookie) {
     // if locale not setup in cookie,means first-time to request.
     String acceptLanuage = request.getHeader("Accept-Language");
     if (null != acceptLanuage) {
       if (acceptLanuage.toLowerCase().indexOf("zh") >= 0) {
         localeResolver.setLocale(request, response, Locale.SIMPLIFIED_CHINESE);
       }
     }
   }
   return true;
 }
 /** @param response */
 void clearCookie(HttpServletResponse response) {
   Cookie c = new HttpOnlyCookie(trustedAuthCookieName, "");
   c.setMaxAge(0);
   c.setPath("/");
   c.setSecure(secureCookie);
   response.addCookie(c);
 }
  /**
   * Create a new {@link TimestampFormatter}.
   *
   * @param systemTimeFormat the system clock time format
   * @param elapsedTimeFormat the elapsed time format
   * @param request the current HTTP request
   * @param timeZoneId the currently configured time zone
   */
  TimestampFormatter(
      String systemTimeFormat,
      String elapsedTimeFormat,
      Optional<? extends HttpServletRequest> request,
      Optional<String> timeZoneId) {

    String cookieValue = null;
    if (request.isPresent()) {
      Cookie[] cookies = request.get().getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if ("jenkins-timestamper".equals(cookie.getName())) {
            cookieValue = cookie.getValue();
            break;
          }
        }
      }
    }

    if ("elapsed".equalsIgnoreCase(cookieValue)) {
      formatTimestamp = new ElapsedTimeFormatFunction(elapsedTimeFormat);
    } else if ("none".equalsIgnoreCase(cookieValue)) {
      formatTimestamp = new EmptyFormatFunction();
    } else {
      // "system", no cookie, or unrecognised cookie
      formatTimestamp = new SystemTimeFormatFunction(systemTimeFormat, timeZoneId);
    }
  }
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public void login(
     @ModelAttribute("user") User user,
     HttpSession session,
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam(value = "userId", required = true) String userId,
     @RequestParam(value = "passwd", required = true) String passwd)
     throws Exception {
   user = this.userService.getUser(userId, passwd);
   PrintWriter pw = response.getWriter();
   if (user != null) {
     Cookie cookie = new Cookie(Constants.BRUSERID, user.getId());
     cookie.setPath("/");
     cookie.setMaxAge(10 * 365 * 24 * 3600);
     response.addCookie(cookie);
     WebContextThreadLocal.setCurrentUser(user);
     LoggerUtil.info(this.getClass(), "当前登录用户为:" + user.getUserName());
     AuthenticateRole.authenticate(request, user, (String) request.getAttribute("userIdRuleReg"));
     request.setAttribute("user", user);
     session.setAttribute("user", user);
     this.userService.flush();
     pw.write(
         "{\"login\" : true ,\"user\":\""
             + user.getUserName()
             + "\",\"isTeacher\":\""
             + request.getAttribute("isTeacher")
             + "\"}");
   } else {
     LoggerUtil.debug(this.getClass(), "用户名或密码错误!");
     pw.write("{\"login\":false}");
   }
   pw.close();
 }
Exemplo n.º 12
0
 public static void removeCookie(
     HttpServletRequest request, HttpServletResponse response, Cookie cookie) {
   if (cookie == null) return;
   cookie.setPath(request.getContextPath());
   cookie.setMaxAge(0);
   response.addCookie(cookie);
 }
Exemplo n.º 13
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = new Test().doSomething(param);

    String sql = "UPDATE USERS SET PASSWORD='******' WHERE USERNAME='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      int count = statement.executeUpdate(sql, new int[] {1, 2});
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
Exemplo n.º 14
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 {
   String url = request.getParameter("url_req");
   String user = request.getParameter("username");
   String password = request.getParameter("password");
   String[] remember = request.getParameterValues("cookie");
   try {
     User u = RegistrationManager.verifyUser(user, password);
     if (u != null) {
       if (!u.getProfile().equals(RegistrationManager.NO_PROFILES)) {
         request.getSession().setAttribute("user", u);
         if (remember != null) {
           Cookie cookie = new Cookie("user", user);
           cookie.setMaxAge(30 * 24 * 60 * 60); // 1 month.
           cookie.setPath("/");
           response.addCookie(cookie);
         }
         u.updateLastAccess(user);
         if (url.equals("null")) response.sendRedirect("index.jsp");
         else response.sendRedirect(url);
       } else {
         request.setAttribute(
             StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_DOMAIN_ERROR);
         request.getRequestDispatcher("login.jsp").forward(request, response);
       }
     } else {
       request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR);
       request.getRequestDispatcher("login.jsp").forward(request, response);
     }
   } catch (IOException | ServletException e) {
     request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR_SERVER);
     request.getRequestDispatcher("login.jsp").forward(request, response);
   }
 }
Exemplo n.º 15
0
  // greetMe will use session to return last called name
  public String greetMe(String me) {
    LOG.info("Executing operation greetMe");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
    Cookie cookies[] = req.getCookies();
    String val = "";
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        val += ";" + cookie.getName() + "=" + cookie.getValue();
      }
    }

    HttpSession session = req.getSession();
    // Get a session property "counter" from context
    if (session == null) {
      throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String) session.getAttribute("name");
    if (name == null) {
      name = me;
      LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

    return "Hello " + name + val;
  }
Exemplo n.º 16
0
  public String authenticateUser(RequestContext request) {
    Cookie cookie = ControllerUtils.getCookie("JForumSSO");
    logger.info("DEBUG - CustomSSO - authenticatUser - Getting JForumSSO Cookie!");

    String username = null;
    if (cookie == null) {
      logger.info("DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is NULL!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));

      return null;
    } else {
      username = (String) cookie.getValue();
      logger.info(
          "DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is contains username: "******"!");
      if (username.equals("")) {
        logger.info("DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is empty!");
        JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      }
    }
    logger.info(
        "DEBUG - CustomSSO - authenticatUser - JForumSSO is returning username: "******"!");
    return username;
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Map<String, Object> session = invocation.getInvocationContext().getSession();
    User user = (User) session.get("user");

    HttpServletRequest request =
        (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);

    if (user != null) {
      return invocation.invoke();
    } else {
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember-me")) {
            Map<String, String> loginParameters =
                Splitter.on('&').withKeyValueSeparator('=').split(cookie.getValue());
            UserDao userDao = new UserDaoImpl();
            user = userDao.loginUser(loginParameters.get("email"), loginParameters.get("password"));
            if (!loginParameters.get("password").equals(user.getPassword())) {
              return "login";
            } else {
              session.put("user", user);
              request.setAttribute("rememberMe", "true");
              return invocation.invoke();
            }
          }
        }
      }
      return "login";
    }
  }
Exemplo n.º 18
0
  public boolean isSessionValid(UserSession userSession, RequestContext request) {
    String remoteUser = null;

    Cookie SSOCookie = ControllerUtils.getCookie("JforumSSO"); // my app login cookie
    logger.info("DEBUG - CustomSSO - isSessionValid - Getting JForumSSO Cookie!");

    if (SSOCookie != null) remoteUser = SSOCookie.getValue(); //  jforum username

    if (remoteUser == null) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is NULL!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;

    } else if (remoteUser.equals("")) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is empty!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;
      // user has since logged in
    } else if (remoteUser != null
        && userSession.getUserId() == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is Anonymous!");
      return false;
      // user has changed user
    } else if (remoteUser != null && !remoteUser.equals(userSession.getUsername())) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie User Mismatch");
      return false;
    }
    logger.info("DEBUG - CustomSSO - isSessionValid - Returning True");
    return true; // sso pool apps user and forum user the same
  }
Exemplo n.º 19
0
 public boolean checkForUserCookie(HttpServletRequest request, HttpServletResponse response) {
   // TODO just grab cookieValue from ThreadLocal because HttpSessionServletFilter already got it
   // for us
   Cookie[] cookies = request.getCookies();
   String cookieValue = null;
   if (cookies != null) {
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals(LoginController.USER_COOKIE_NAME)) {
         cookieValue = cookie.getValue();
         if (cookieValue != null && !cookieValue.equals("")) {
           logger.debug("Attempting login with cookie value = " + cookieValue);
           UserData userData = securityService.loginWithCookie(cookieValue);
           if (userData != null) {
             LoginController.saveUserInHttpSession(request, userData);
             logger.debug("Logged in using cookie, returning true");
             return true;
           } else {
             LogoutController.clearCookie(response);
           }
         }
         break;
       }
     }
   }
   return false;
 }
  /**
   * Resolve the user's current theme from the cookie.
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  private String resolveTheme(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME);
    if (c == null) {
      String defaultValue =
          this.getSystemConfig()
              .getSysParamValue(
                  SysParams.CORE_DEFAULT_THEME_EXTJS, SysParams.CORE_DEFAULT_THEME_EXTJS_DEFVAL);
      if (defaultValue == null || defaultValue.equals("")) {
        defaultValue = Constants.DEFAULT_THEME_EXTJS;
      }
      c = this.createCookie(Constants.COOKIE_NAME_THEME, defaultValue, 60 * 60 * 24 * 365);
      response.addCookie(c);
    }

    String theme = request.getParameter(Constants.REQUEST_PARAM_THEME);
    if (theme == null || theme.equals("")) {
      theme = c.getValue();
    } else {
      c.setMaxAge(0);
      c = this.createCookie(Constants.COOKIE_NAME_THEME, theme, 60 * 60 * 24 * 365);
      response.addCookie(c);
    }
    return theme;
  }
Exemplo n.º 21
0
 /**
  * Returns the {@link AuthenticationToken} for the request.
  *
  * <p>It looks at the received HTTP cookies and extracts the value of the {@link
  * AuthenticatedURL#AUTH_COOKIE} if present. It verifies the signature and if correct it creates
  * the {@link AuthenticationToken} and returns it.
  *
  * <p>If this method returns <code>null</code> the filter will invoke the configured {@link
  * AuthenticationHandler} to perform user authentication.
  *
  * @param request request object.
  * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
  * @throws IOException thrown if an IO error occurred.
  * @throws AuthenticationException thrown if the token is invalid or if it has expired.
  */
 protected AuthenticationToken getToken(HttpServletRequest request)
     throws IOException, AuthenticationException {
   AuthenticationToken token = null;
   String tokenStr = null;
   Cookie[] cookies = request.getCookies();
   if (cookies != null) {
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
         tokenStr = cookie.getValue();
         try {
           tokenStr = signer.verifyAndExtract(tokenStr);
         } catch (SignerException ex) {
           throw new AuthenticationException(ex);
         }
         break;
       }
     }
   }
   if (tokenStr != null) {
     token = AuthenticationToken.parse(tokenStr);
     if (!token.getType().equals(authHandler.getType())) {
       throw new AuthenticationException("Invalid AuthenticationToken type");
     }
     if (token.isExpired()) {
       throw new AuthenticationException("AuthenticationToken expired");
     }
   }
   return token;
 }
  /**
   * Resolve the user's current language from the cookie.
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  private String resolveLang(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG);
    if (c == null) {
      String defaultValue =
          this.getSystemConfig()
              .getSysParamValue(
                  SysParams.CORE_DEFAULT_LANGUAGE, SysParams.CORE_DEFAULT_LANGUAGE_DEFVAL);
      if (defaultValue == null || defaultValue.equals("")) {
        defaultValue = Constants.DEFAULT_LANGUAGE;
      }
      c = this.createCookie(Constants.COOKIE_NAME_LANG, defaultValue, 60 * 60 * 24 * 365);
      response.addCookie(c);
    }

    String lang = request.getParameter(Constants.REQUEST_PARAM_LANG);
    if (lang == null || lang.equals("")) {
      lang = c.getValue();
    } else {
      c.setMaxAge(0);
      c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365);
      response.addCookie(c);
    }
    return lang;
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Cookie[] cookies = request.getCookies();
    Cookie requestCountCookie = null;
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if ("requestCount".equals(cookies[i].getName())) {
          requestCountCookie = cookies[i];
          break;
        }
      }
    }
    int count = 1;
    if (requestCountCookie == null) {
      requestCountCookie = new Cookie("requestCount", count + "");
    } else {
      count = Integer.parseInt(requestCountCookie.getValue());
      count++;
    }
    requestCountCookie.setValue(count + "");
    requestCountCookie.setMaxAge(9999999);
    response.addCookie(requestCountCookie);

    PrintWriter out = response.getWriter();
    out.println("<h1>Request Count : " + count + "</h1>");
  }
  /**
   * Render page contents.
   *
   * @param writer
   * @param cookies
   */
  private void renderPage(PrintWriter writer, Cookie[] cookies) {
    List<String[]> events = parseEvents();
    List<String> cities = parseCities(events), categories = parseCategories(events);
    String city = null, category = null;

    // Write header.
    appendHeader(writer);

    // If cookies are List, show monthly events.
    if (cookies != null) {
      // Check if city and category cookie existed and update values.
      for (Cookie cookie : cookies) {
        // If city cookie existed, modify city value.
        String name = cookie.getName();
        if (name.equalsIgnoreCase(CITY_PARAMETER_COOKIE_NAME)) {
          city = cookie.getValue();
        } else if (name.equalsIgnoreCase(CATEGORY_PARAMETER_COOKIE_NAME)) {
          category = cookie.getValue();
        }
      }
    }

    // Show input form.
    showInputForm(writer, cities, categories, city, category);

    // Show event table.
    showEventTable(writer, events, city, category);

    // Write footer.
    appendFooter(writer);
  }
Exemplo n.º 25
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = new Test().doSomething(param);

    new java.io.File(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), bar);
  } // end doPost
  /**
   * Handle POST request.
   *
   * @param req
   * @param resp
   * @throws javax.servlet.ServletException
   * @throws java.io.IOException
   */
  @Override
  protected void doPost(
      javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp)
      throws javax.servlet.ServletException, java.io.IOException {
    // Get parameters.
    String city = req.getParameter(CITY_PARAMETER_COOKIE_NAME),
        category = req.getParameter(CATEGORY_PARAMETER_COOKIE_NAME);

    // Create response cookies.
    Cookie cookies[] = new Cookie[2];
    Cookie cookie = new Cookie(CITY_PARAMETER_COOKIE_NAME, city);
    cookie.setMaxAge(COOKIE_MAX_AGE);
    resp.addCookie(cookie);
    cookies[0] = cookie;
    cookie = new Cookie(CATEGORY_PARAMETER_COOKIE_NAME, category);
    cookie.setMaxAge(COOKIE_MAX_AGE);
    resp.addCookie(cookie);
    cookies[1] = cookie;

    // Get print writer.
    PrintWriter writer = resp.getWriter();

    // Render page.
    renderPage(writer, cookies);

    // Close print writer.
    writer.close();
  }
Exemplo n.º 27
0
 private void addCookie(String cookieContent, HttpServletResponse response) {
   Cookie cookie = new Cookie(CookieSessionHandler.session, cookieContent);
   cookie.setSecure(SparkBase.isSecure());
   cookie.setHttpOnly(true);
   cookie.setMaxAge(-1);
   response.addCookie(cookie);
 }
Exemplo n.º 28
0
 @Override
 public String execute() throws Exception {
   // TODO Auto-generated method stub
   System.out.println(callback);
   System.out.println(username);
   UsersService usersService = new UsersService();
   usersService.login(username, password);
   users = usersService.getCurrentUser();
   if (users == null) {
     loginResult = new LoginResult(new Users());
     loginResult.setLoginStatus(0);
   } else {
     loginResult = new LoginResult(usersService.getCurrentUser());
     loginResult.setLoginStatus(1);
     loginResult.setImagePath(new ImageService().getImage(users));
     Cookie cookie = new Cookie("hashCode", users.getHashCode());
     cookie.setMaxAge(60 * 60 * 24 * 365 * 5);
     cookie.setPath("/");
     ServletActionContext.getResponse().addCookie(cookie);
   }
   setLoginResult(loginResult);
   if (callback == null || callback.equals("")) {
     return SUCCESS;
   } else {
     JSONObject jsonObj = JSONObject.fromObject(loginResult);
     System.out.println(jsonObj.toString());
     String str = new String(callback + "(" + jsonObj + ")");
     inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
     return "callback";
   }
 }
Exemplo n.º 29
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = param;
    if (param.length() > 1) {
      bar = param.substring(0, param.length() - 1);
    }

    response.getWriter().write(bar);
  }
Exemplo n.º 30
0
  @RequestMapping(value = "/auth/login", method = RequestMethod.POST)
  public String login(
      String email,
      String password,
      String saveEmail,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      Model model)
      throws Exception {

    Cookie cookie = null;
    if (saveEmail != null) {
      cookie = new Cookie("email", email);
      cookie.setMaxAge(60 * 60 * 24 * 3);
    } else {
      cookie = new Cookie("email", null);
      cookie.setMaxAge(0);
    }
    response.addCookie(cookie);

    HashMap<String, String> sqlparamMap = new HashMap<String, String>();
    sqlparamMap.put("email", email);
    sqlparamMap.put("password", password);

    Member member = memberDao.selectByEmailPassword(sqlparamMap);

    if (member != null) {
      session.setAttribute("loginUser", member);
      return "redirect:../main.do";
    } else {
      return "auth/loginFail";
    }
  }