Example usage for javax.servlet.http Cookie getValue

List of usage examples for javax.servlet.http Cookie getValue

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getValue.

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:m.c.m.proxyma.rewrite.CookieRewriteEngineTest.java

public void testMasquerade_Unmasquerade_Cookie() throws NullArgumentException, IllegalArgumentException, UnsupportedEncodingException {
    System.out.println("masquerade/unmasqueradeCookie");
    ProxymaFacade proxyma = new ProxymaFacade();
    ProxymaContext context = proxyma.getContextByName("default");
    ProxyFolderBean folder1 = proxyma.createNewProxyFolder("host1", "http://www.google.com/it", context);
    ProxyFolderBean folder2 = proxyma.createNewProxyFolder("host2", "https://www.apple.com/en", context);
    ProxymaResource aResource = proxyma.createNewResource(request, response, context);
    aResource.setProxymaRootURI("http://localhost:8080/proxyma");
    aResource.setProxyFolder(folder1);/*w  w  w .  j  a v  a  2 s . c  o m*/
    CookieRewriteEngine instance = new CookieRewriteEngine(context);

    Cookie theCookie = new Cookie("cookie1", "Value1");
    theCookie.setDomain("google.com");
    theCookie.setPath("/it/pippo");
    instance.masqueradeCookie(theCookie, aResource);

    String expected = "localhost";
    assertEquals(expected, theCookie.getDomain());

    expected = "/proxyma/host1/pippo";
    assertEquals(expected, theCookie.getPath());

    expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER  + "Value1";
    assertEquals(expected, theCookie.getValue());

    instance.unmasqueradeCookie(theCookie);

    expected = "Value1";
    assertEquals(expected, theCookie.getValue());

    theCookie = new Cookie("cookie2", "Value2");
    instance.masqueradeCookie(theCookie, aResource);

    expected = "localhost";
    assertEquals(expected, theCookie.getDomain());

    expected = "/proxyma/host1";
    assertEquals(expected, theCookie.getPath());

    expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER  + "Value2";
    assertEquals(expected, theCookie.getValue());

    instance.unmasqueradeCookie(theCookie);

    expected = "Value2";
    assertEquals(expected, theCookie.getValue());

    proxyma.removeProxyFolder(folder2, context);
    proxyma.removeProxyFolder(folder1, context);
}

From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java

/**
 * This method filters every incoming request.
 * If request contains cookie, it checks whether the cookie is valid.
 *    A. If request cookie is present and is valid, forwards the request 
 *          to next page.//from w w w .  j  ava2  s  .c  o m
 *    B. If cookie is not valid and request is not coming from ACS, this
 *          method redirects the request to ACS login page.
 * If request does not contain a cookie, but contains an ACS token,
 * this method, creates or updates cookie and 
 * forwards the request to landing page.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // capture ACS response
    String acsToken = httpServletRequest.getParameter("wresult");
    if (null != acsToken && acsToken.trim().length() == 0) {
        acsToken = null;
    }
    String isEncodedWresult = httpServletRequest.getParameter("isEncodedWresult");
    String decodedTokenString = null;
    if (null != acsToken && null != isEncodedWresult && isEncodedWresult.trim().equalsIgnoreCase("true")) {
        decodedTokenString = new String(URLDecoder.decode(acsToken, "UTF-8"));
        acsToken = decodedTokenString;
    }

    // by pass the url access validation validateInvitationCode
    if (httpServletRequest.getRequestURI().contains("/validateInvitationCode")) {
        request.getRequestDispatcher("/validateInvitationCode.htm").forward(httpServletRequest,
                httpServletResponse);
    } else {

        CloudNinjaUser cloudNinjaUser = null;

        boolean isValidCookiePresent = false;
        String cookieName = CloudNinjaConstants.AUTH_COOKIE_NAME;

        Cookie preExistentCookie = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);

        if (preExistentCookie != null && StringUtils.isNotBlank(preExistentCookie.getValue())) {
            isValidCookiePresent = AuthFilterUtils.checkValidityOfCookie(preExistentCookie);
        }

        if (isValidCookiePresent) {
            Cookie cookieToUse = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);

            // Add cookie userNames, etc to request attributes
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToNextPage(httpServletRequest, httpServletResponse, chain);
        } else if (!isValidCookiePresent && (acsToken == null)) {
            redirectToACSPage(httpServletRequest, httpServletResponse);
            return;
        } else if (acsToken != null) {

            acsToken = new String(acsToken.getBytes(), CloudNinjaConstants.UTF_8_FORMAT);
            boolean isValidCertificate = AuthFilterUtils.checkCertificateValidity(acsToken);
            if (!isValidCertificate) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            try {
                cloudNinjaUser = parseSAMLResponseAndCreateCNUser(acsToken);
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            String liveGuid = null;

            //  GUID is present and user is null it means that user is from windowsLiveId
            // and is login-in in for the first time so we need to ask for verification code
            if (cloudNinjaUser != null && cloudNinjaUser.getUser() == null) {
                liveGuid = cloudNinjaUser.getLiveGUID();
                cloudNinjaUser = null;
                forwardToVerificationPage(httpServletRequest, httpServletResponse, liveGuid, acsToken);
                return;
            }
            // if user is null and no GUID is present
            // redirect to ACS page

            if (null == cloudNinjaUser) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            Cookie cookieToUse;
            if (preExistentCookie == null) {
                cookieToUse = AuthFilterUtils.createNewCookieForACSAuthenticatedUser(cloudNinjaUser,
                        cookieName);
            } else {
                cookieToUse = AuthFilterUtils.updateExistingCookie(preExistentCookie, cloudNinjaUser);
            }
            cookieToUse.setMaxAge(getCookieMaxAge());
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToLandingPage(httpServletRequest, httpServletResponse, chain, cloudNinjaUser);
        }
    }
}

From source file:custom.application.login.java

public Object validate() {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST");
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE");

    Cookie cookie = StringUtilities.getCookieByName(request.getCookies(), "username");
    if (cookie != null) {
        this.setVariable("username", cookie.getValue());
        String user_field = cookie.getValue()
                + "<input class=\"text\" id=\"username\" name=\"username\" type=\"hidden\" value=\""
                + cookie.getValue()//from  ww  w . j a  va 2 s . co m
                + "\"/>  <a href=\"javascript:void(0)\" onclick=\"restoreField()\">[%login.user.change%]</a>";

        this.setVariable("user_field", user_field);
    } else {
        this.setVariable("username", "");
        this.setVariable("user_field",
                "<input class=\"text\" id=\"username\" name=\"username\" type=\"text\" value=\"\"/>");
    }

    this.setText("login.tips.text", this.getLink("bible"));

    try {
        Reforward reforward = new Reforward(request, response);

        if (request.getMethod().equalsIgnoreCase("post")) {
            this.passport = new passport(request, response, "waslogined");
            if (this.passport.login()) {
                reforward.forward();
            }
        }

        this.setVariable("from", reforward.getFromURL());
    } catch (ApplicationException e) {
        this.setVariable("error", "<div class=\"error\">" + e.getRootCause().getMessage() + "</div>");
    }

    this.setVariable("action",
            this.config.get("default.base_url") + this.context.getAttribute("REQUEST_ACTION").toString());

    HttpSession session = request.getSession();
    if (session.getAttribute("usr") != null) {
        this.usr = (User) session.getAttribute("usr");

        this.setVariable("user.status", "");
        this.setVariable("user.profile",
                "<a href=\"javascript:void(0)\" onmousedown=\"profileMenu.show(event,'1')\">"
                        + this.usr.getEmail() + "</a>");
    } else {
        this.setVariable("user.status", "<a href=\"" + this.getLink("user/login") + "\">"
                + this.getProperty("page.login.caption") + "</a>");
        this.setVariable("user.profile", "");
    }

    return this;
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*from  w  ww . ja v  a2s.c  om*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:com.adobe.acs.commons.httpcache.config.impl.RequestCookieHttpCacheConfigExtension.java

@Override
public boolean accepts(SlingHttpServletRequest request, HttpCacheConfig cacheConfig,
        Map<String, String[]> allowedKeyValues) {
    for (final Map.Entry<String, String[]> entry : allowedKeyValues.entrySet()) {
        final Cookie cookie = CookieUtil.getCookie(request, entry.getKey());

        if (cookie != null) {
            if (ArrayUtils.isEmpty(entry.getValue())) {
                // If no values were specified, then assume ANY and ALL values are acceptable, and were are merely looking for the existence of the cookie
                log.debug("Accepting as cacheable due to existence of Cookie [ {} ]", entry.getKey());
                return true;
            } else if (ArrayUtils.contains(entry.getValue(), cookie.getValue())) {
                // The cookies value matched one of the allowed values
                log.debug("Accepting as cacheable due to existence of Cookie [ {} ] with value [ {} ]",
                        entry.getKey(), cookie.getValue());
                return true;
            }/*from w  w w. j a  v  a2s  . c o m*/
            // No matches found for this row; continue looking through the allowed list
        }
    }

    // No valid cookies could be found.
    log.debug("Could not find any valid Cookie matches for HTTP Cache");
    return false;
}

From source file:com.appeligo.search.actions.BaseAction.java

public String getLineup() {
    String lineup = null;//from www. j a  v  a2 s. c  o m
    //Get if from the user if there is one
    User user = getUser();
    if (user != null) {
        lineup = user.getLineupId();
        getServletRequest().getSession().setAttribute(LINEUP_ID, lineup);
    } else {
        lineup = (String) getServletRequest().getSession().getAttribute(LINEUP_ID);
        if (lineup == null) {
            // No user, and its not stored in the session, so check for a cookie. If there is no cookie, default them to pacific
            //Right now the lineup is not getting stored in the session when it is loaded by the cookie.
            //The reason is that the cookie gets set before they login and it would not get set with
            //The lineup from the user.
            Cookie[] cookies = getServletRequest().getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(LINEUP_ID)) {
                        cookie.setMaxAge(Integer.MAX_VALUE);
                        lineup = cookie.getValue();
                        break;
                    }
                }
            }
            if (lineup == null) {
                lineup = DEFAULT_LINEUP;
                Cookie cookie = new Cookie(LINEUP_ID, lineup);
                cookie.setMaxAge(Integer.MAX_VALUE);
                response.addCookie(cookie);
                getServletRequest().getSession().setAttribute(LINEUP_ID, lineup);
            }
        }
    }
    return lineup;
}

From source file:com.example.web.Create_story.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    int count = 1;
    String storyid, storystep;/*from   www .  ja  va2  s.  c o  m*/
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

    String latitude = request.getParameter("lat");
    String longitude = request.getParameter("lng");
    storyid = (request.getParameter("storyid"));
    storystep = (request.getParameter("storystep"));
    String message = "";
    int valid = 1;
    String query;
    ResultSet rs;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "tworld";
    String driver = "com.mysql.jdbc.Driver";

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String[] spliting = fileName.split("\\.");
                    // Write the file
                    System.out.println(sizeInBytes + " " + maxFileSize);
                    System.out.println(spliting[spliting.length - 1]);
                    if (!fileName.equals("")) {
                        if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                || spliting[spliting.length - 1].equals("png")
                                || spliting[spliting.length - 1].equals("jpeg"))) {

                            if (fileName.lastIndexOf("\\") >= 0) {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                            } else {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                            }
                            fi.write(file);
                            System.out.println("Uploaded Filename: " + fileName + "<br>");
                        } else {
                            valid = 0;
                            message = "not a valid image";
                        }
                    }
                }
                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {
                    br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (f == 0)
                    action = sb.toString();
                else if (f == 1)
                    storyid = sb.toString();
                else if (f == 2)
                    storystep = sb.toString();
                else if (f == 3)
                    title = sb.toString();
                else if (f == 4)
                    header = sb.toString();
                else if (f == 5)
                    text_field = sb.toString();
                else if (f == 6)
                    latitude = sb.toString();
                else if (f == 7)
                    longitude = sb.toString();
                else if (f == 8)
                    first = sb.toString();
                f++;

            }
        } catch (Exception ex) {
            System.out.println("hi");
            System.out.println(ex);

        }
    }
    if (latitude == null)
        latitude = "";
    if (latitude.equals("") && first == null) {

        request.setAttribute("message", "please enter a marker");
        request.setAttribute("storyid", storyid);
        request.setAttribute("s_page", "3");
        request.setAttribute("storystep", storystep);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (valid == 1) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (first != null) {
                if (first.equals("first_step")) {
                    do {
                        query = "select * from story_database where story_id='" + count + "' ";
                        Statement st = conn.createStatement();
                        rs = st.executeQuery(query);
                        count++;
                    } while (rs.next());

                    int a = count - 1;
                    request.setAttribute("storyid", a);
                    storyid = Integer.toString(a);
                    request.setAttribute("storystep", 2);

                }
            }
            query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='"
                    + storystep + "' ";
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);

            if (!rs.next()) {

                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)");

                pst.setInt(1, Integer.parseInt(storyid));
                pst.setInt(2, Integer.parseInt(storystep));
                pst.setString(3, text_field);
                pst.setString(4, latitude);
                pst.setString(5, longitude);
                pst.setString(6, title);
                pst.setString(7, header);
                pst.setInt(8, Integer.parseInt(storystep));
                pst.setString(9, user);
                if (fileName.equals(""))
                    pst.setString(10, "");
                else
                    pst.setString(10, fileName);
                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            } else {
                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?");

                pst.setString(1, text_field);
                pst.setString(2, latitude);
                pst.setString(3, longitude);
                pst.setString(4, title);
                pst.setString(5, header);

                pst.setInt(6, Integer.parseInt(storystep));
                pst.setString(7, user);
                pst.setInt(8, Integer.parseInt(storyid));
                pst.setInt(9, Integer.parseInt(storystep));

                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            }
            request.setAttribute("storyid", storyid);
            storystep = Integer.toString(Integer.parseInt(storystep) + 1);
            request.setAttribute("storystep", storystep);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {

            //            Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex);  
        }
        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {
        request.setAttribute("storyid", storyid);
        request.setAttribute("message", message);
        request.setAttribute("storystep", storystep);

        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.google.identitytoolkit.GitkitClient.java

/**
 * Verifies Gitkit token in http request.
 *
 * @param request http request/*from w w  w  . j  a  va  2  s .c  o  m*/
 * @return Gitkit user if valid token is found in the request.
 * @throws GitkitClientException if there is token but signature is invalid
 */
public GitkitUser validateTokenInRequest(HttpServletRequest request) throws GitkitClientException {
    Cookie[] cookies = request.getCookies();
    if (cookieName == null || cookies == null) {
        return null;
    }

    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return validateToken(cookie.getValue());
        }
    }
    return null;
}

From source file:com.appeligo.search.actions.BaseAction.java

public TimeZone getTimeZone() {
    User user = getUser();/*from  w w  w . ja v a 2s . co m*/
    if (user != null) {
        getServletRequest().getSession().setAttribute(TIMEZONE_ID, user.getTimeZone());
        return user.getTimeZone();
    } else {
        TimeZone zone = (TimeZone) getServletRequest().getSession().getAttribute(TIMEZONE_ID);
        if (zone == null) {
            String timeZoneId = null;
            Cookie[] cookies = getServletRequest().getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(TIMEZONE_ID)) {
                        cookie.setMaxAge(Integer.MAX_VALUE);
                        timeZoneId = cookie.getValue();
                        break;
                    }
                }
            }
            if (timeZoneId == null) {
                timeZoneId = DEFAULT_TIMEZONE_ID;
                Cookie cookie = new Cookie(TIMEZONE_ID, timeZoneId);
                cookie.setMaxAge(Integer.MAX_VALUE);
                response.addCookie(cookie);
            }
            zone = TimeZone.getTimeZone(timeZoneId);
            getServletRequest().getSession().setAttribute(TIMEZONE_ID, zone);
            return zone;
        } else {
            return zone;
        }
    }
}

From source file:cn.vlabs.umt.ui.servlet.login.LoginMethod.java

private boolean loginByCookie(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ApplicationNotFound {
    Cookie cookie = getCookieByName(request, Attributes.COOKIE_NAME);
    if (cookie == null) {
        return false;
    }//from   w w  w . java  2s.c  om
    if (StringUtils.isNotEmpty(cookie.getValue())) {
        String cookieValue = getSsoCookieValue(request);
        if (cookieValue != null) {
            LoginInfo info = ServiceFactory.getLoginService(request).loginAndReturnPasswordType(
                    new CookieCredential(cookieValue, RequestUtil.getRemoteIP(request)));
            User userPrincipal = (info != null) ? info.getUser() : null;
            if (userPrincipal != null) {

                saveThirdPartyCredential(request, userPrincipal.getType(), cookieValue, "");
                HttpSession session = request.getSession();
                session.setAttribute(Attributes.LOGIN_INFO, info);
                // Roles
                RoleService rs = (RoleService) factory.getBean("RoleService");
                UMTRole[] roles = rs.getUserRoles(cookieValue);
                UMTContext.saveRoles(session, roles);
                generateSsoCookie(response, request, info);
                generateAutoFill(response, request, info);
                String appname = request.getParameter(Attributes.APP_NAME);
                if (appname == null) {
                    appname = (String) request.getAttribute(Attributes.APP_NAME);
                }

                if (appname != null) {
                    sendTicket(userPrincipal, SessionUtils.getSiteInfo(request), request, response);
                } else {
                    response.sendRedirect(RequestUtil.getContextPath(request) + "/index.jsp");
                }
                return true;
            }
            request.setAttribute("cookieError", "true");
        }
    }
    return false;
}