Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.egt.core.jsf.JSF.java

private static String getCookie(String key, int option) {
    Bitacora.trace(JSF.class, "getCookie", "key=" + key, "option=" + option);
    /*/*from ww  w.j a  va  2s  .  c om*/
     * 1 = busca con clave privada (cualificada)
     * 2 = busca con clave publica (no cualificada)
     * 3 = busca primero con clave privada y luego con clave publica
     * 4 = busca primero con clave publica y luego con clave privada
     */
    FacesContext facesContext = FacesContext.getCurrentInstance();
    String qualifiedKey = key + getRequestQualifier();
    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    Cookie[] cookie = request.getCookies();
    String[] clave = { null, null };
    switch (option) {
    case 1:
        clave[0] = qualifiedKey;
        break;
    case 2:
        clave[0] = key;
        break;
    case 3:
        clave[0] = qualifiedKey;
        clave[1] = key;
        break;
    case 4:
        clave[0] = key;
        clave[1] = qualifiedKey;
        break;
    default:
        return null;
    }
    for (int i = 0; i < cookie.length; i++) {
        for (int j = 0; j < clave.length; j++) {
            if ((clave[j] != null && cookie[i].getName().equals(clave[j]))) {
                return cookie[i].getValue();
            }
        }
    }
    return null;
}

From source file:com.hypersocket.session.json.SessionUtils.java

public Session getActiveSession(HttpServletRequest request) {

    Session session = null;/*from   w  w  w  . j av  a2  s  .c o m*/

    if (request.getAttribute(AUTHENTICATED_SESSION) != null) {
        session = (Session) request.getAttribute(AUTHENTICATED_SESSION);
        if (sessionService.isLoggedOn(session, true)) {
            return session;
        }
    }
    if (request.getSession().getAttribute(AUTHENTICATED_SESSION) != null) {
        session = (Session) request.getSession().getAttribute(AUTHENTICATED_SESSION);
        if (sessionService.isLoggedOn(session, true)) {
            return session;
        }
    }
    for (Cookie c : request.getCookies()) {
        if (c.getName().equals(HYPERSOCKET_API_SESSION)) {
            session = sessionService.getSession(c.getValue());
            if (session != null && sessionService.isLoggedOn(session, true)) {
                return session;
            }
        }
    }

    if (request.getParameterMap().containsKey(HYPERSOCKET_API_KEY)) {
        session = sessionService.getSession(request.getParameter(HYPERSOCKET_API_KEY));
    } else if (request.getHeader(HYPERSOCKET_API_SESSION) != null) {
        session = sessionService.getSession((String) request.getHeader(HYPERSOCKET_API_SESSION));
    }

    if (session != null && sessionService.isLoggedOn(session, true)) {
        return session;
    }

    return null;
}

From source file:com.squid.kraken.v4.api.core.ServiceUtils.java

public String getLocale(HttpServletRequest request) {
    // try to find from a request param
    String locale = (String) request.getParameter(LOCALE_PARAM);
    if (locale == null) {
        // try to find from a cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(SQUIDAPILOCALE)) {
                    locale = cookies[i].getValue();
                }/*ww  w.j a v a  2 s  .  co m*/
            }
        }
    }
    // check string validity
    if ((locale != null) && (locale.length() != 5)) {
        throw new APIException("Invalid " + LOCALE_PARAM + " : " + locale, isNoErrorEnabled(request));
    }
    return locale;
}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

/**
 * Retrieves user info from cookie// w  ww  .j  av a  2  s  .c om
 */
public User getUser(HttpServletRequest req) {
    if (isLocal()) {
        return LOCAL_USER;
    }

    Cookie[] cookies = req.getCookies();
    String wpCookieName = null;
    String wpCookieValue = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith("wordpress_logged_in")) {
                wpCookieName = cookie.getName();
                wpCookieValue = cookie.getValue();
            }
        }
    }

    final String ip = req.getRemoteAddr();
    final String host = req.getRemoteHost();

    System.out.println("Session : " + wpCookieName + " " + wpCookieValue);

    if (wpCookieName == null) {
        return NO_USER;
    }

    try {
        URL u = new URL(URL_ROOT + "/kite9_user_info");
        URLConnection conn = u.openConnection();
        conn.setRequestProperty("Cookie", wpCookieName + "=" + wpCookieValue);
        conn.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = br.readLine();
        br.close();
        if (line.contains("<none>")) {
            return NO_USER;
        } else {
            String parts[] = line.split(",");
            int id = Integer.parseInt(parts[1]);
            return new User(id, parts[0], false, ip, host);
        }
    } catch (IOException e) {
        throw new Kite9ProcessingException("Couldn't handle user log-in", e);
    }
}

From source file:com.exxonmobile.ace.hybris.storefront.interceptors.beforecontroller.RequireHardLoginBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
        final HandlerMethod handler) throws Exception {
    // We only care if the request is secure
    if (request.isSecure()) {
        // Check if the handler has our annotation
        final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class);
        if (annotation != null) {
            boolean redirect = true;
            final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
            final boolean anonymousUser = getUserService().isAnonymousUser(getUserService().getCurrentUser());
            if (!anonymousUser && guid != null && request.getCookies() != null) {
                final String guidCookieName = getCookieGenerator().getCookieName();
                if (guidCookieName != null) {
                    for (final Cookie cookie : request.getCookies()) {
                        if (guidCookieName.equals(cookie.getName())) {
                            if (guid.equals(cookie.getValue())) {
                                redirect = false;
                                break;
                            } else {
                                LOG.info("Found secure cookie with invalid value. expected [" + guid
                                        + "] actual [" + cookie.getValue() + "]. removing.");
                                getCookieGenerator().removeCookie(response);
                            }//from w ww.j  a  v a  2s  . com
                        }
                    }
                }
            }

            if (redirect) {
                LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie")
                        + ", redirecting");
                getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request));
                return false;
            }
        }
    }

    return true;
}

From source file:com.squid.kraken.v4.api.core.ServiceUtils.java

/**
 * Retrieve a {@link AccessToken}./*from  w w  w .  j a  v a2 s.co  m*/
 * 
 * @param request
 *            an HttpServletRequest containing an 'access_token' param.
 * @return the AccessToken associated to this token or
 *         <tt>null</null> if none found.
 * @throws TokenExpiredException
 *             if the token has expired.
 */
public AccessToken getToken(HttpServletRequest request) {
    // try to find from a request param
    String tokenId = (String) request.getParameter(TOKEN_PARAM);
    if (tokenId == null) {
        // try to find from a cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(SQUIDAPITOKEN)) {
                    tokenId = cookies[i].getValue();
                }
            }
        }
    }
    if (tokenId == null) {
        // try with Bearer header
        Enumeration<String> headers = request.getHeaders(AUTHORIZATION);
        while (headers.hasMoreElements()) {
            String auth = headers.nextElement();
            int idx = auth.indexOf(BEARER_HEADER);
            if (idx > -1) {
                tokenId = auth.substring(BEARER_HEADER.length());
            }
        }
    }
    try {
        AccessToken token = getToken(tokenId);
        if (token != null) {
            return token;
        } else {
            // no token id found
            throw new InvalidTokenAPIException("Auth failed : invalid " + TOKEN_PARAM,
                    isNoErrorEnabled(request));
        }
    } catch (TokenExpiredException e) {
        throw new InvalidTokenAPIException("Auth failed : expired " + TOKEN_PARAM, isNoErrorEnabled(request));
    }
}

From source file:com.traffitruck.web.HtmlController.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        chain.doFilter(request, response);
    } else {/*w  w w .ja v  a 2s.co  m*/
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(HtmlController.DEVICE_REGISTRATION_COOKIE_NAME)
                    && cookie.getValue() != null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication != null) {
                    String username = authentication.getName();
                    LoadsUser user = dao.getUser(username);
                    if (user != null && user.getRoles() != null) {
                        boolean isTruckOwner = false;
                        for (Role role : user.getRoles()) {
                            if (Role.TRUCK_OWNER.equals(role)) {
                                isTruckOwner = true;
                            }
                        }
                        if (isTruckOwner) {
                            dao.addDevice(username, cookie.getValue());
                        }
                        setSessionCookie((HttpServletResponse) response, "", DELETE_COOKIE);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}

From source file:com.mitre.storefront.interceptors.beforecontroller.RequireHardLoginBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
        final HandlerMethod handler) throws Exception {
    // We only care if the request is secure
    if (request.isSecure()) {
        // Check if the handler has our annotation
        final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class);
        if (annotation != null) {
            boolean redirect = true;
            final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
            final boolean anonymousUser = getUserService().isAnonymousUser(getUserService().getCurrentUser());
            if (!anonymousUser && guid != null && request.getCookies() != null) {
                final String guidCookieName = getCookieGenerator().getCookieName();
                if (guidCookieName != null) {
                    for (final Cookie cookie : request.getCookies()) {
                        if (guidCookieName.equals(cookie.getName())) {
                            if (guid.equals(cookie.getValue())) {
                                redirect = false;
                                break;
                            } else {
                                LOG.info("Found secure cookie with invalid value. expected [" + guid
                                        + "] actual [" + cookie.getValue() + "]. removing.");
                                getCookieGenerator().removeCookie(response);
                            }/*from w ww . j  a  v  a 2  s .c  o m*/
                        }
                    }
                }
            }

            if (redirect) {
                final String ajaxHeader = request.getHeader(ajaxRequestHeaderKey);
                LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie")
                        + ", redirecting");
                if (ajaxRequestHeaderValue.equals(ajaxHeader)) {
                    response.addHeader("redirectUrl", request.getContextPath() + getRedirectUrl(request));
                    response.sendError(Integer.parseInt(ajaxRedirectErrorCode));
                } else {
                    getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request));
                }
                return false;
            }
        }
    }

    return true;
}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w  .j a  va 2 s .  c o m*/
 *
 * @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, FileUploadException, IOException_Exception {
    // Check that we have a file upload request
    PrintWriter writer = response.getWriter();
    String productName = "";
    String description = "";
    String price = "";
    String pictureName = "";
    String productId = "";

    Cookie cookie = null;
    Cookie[] cookies = null;
    String selectedCookie = "";
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (cookie.getName().equals("JuraganDiskon")) {
                selectedCookie = cookie.getValue();
            }
        }
    } else {
        writer.println("<h2>No cookies founds</h2>");
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here

        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent()
            + "/web/" + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            int k = 0;
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    k++;
                    writer.println("if = " + k);

                    String fileName = new File(item.getName()).getName();
                    pictureName = fileName;
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("message", "Upload has been done successfully!");
                    writer.println("pictureName = " + pictureName);
                } else {
                    k++;
                    writer.println("else = " + k);

                    // Get the field name
                    String fieldName = item.getName();
                    // Get the field value
                    String value = item.getString();
                    if (k == 0) {

                    } else if (k == 1) {
                        productId = value.trim();
                        writer.println("productId = " + productId);
                    } else if (k == 2) {
                        productName = value;
                        writer.println("productName = " + productName);
                    } else if (k == 3) {
                        description = value;
                        writer.println("description = " + description);
                    } else if (k == 4) {
                        price = value;
                        writer.println("price = " + price);
                    }

                }

            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName,
            selectedCookie);
    writer.println(update);

    //redirects client to message page
    getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response);

}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>// w w  w .  java 2s.  c  o m
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}