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:fr.gael.dhus.server.http.valve.processings.ProcessingValve.java

/**
 * Logs information into temporary cache. According to the Valve
 * configuration, log will also display into the logger.
 *
 * @param request  the input user request to log.
 * @param response the response to the user to be incremented.
 *                 return the log entry.
 * @throws IOException//ww w.  j  a v  a 2 s .c  om
 * @throws ServletException
 */
private ProcessingInformation createProcessing(Request request, Response response)
        throws IOException, ServletException {
    String request_string = null;
    if (request.getQueryString() != null) {
        request_string = request.getRequestURL().append('?').append(request.getQueryString()).toString();
    } else {
        request_string = request.getRequestURL().toString();
    }

    ProcessingInformation pi = new ProcessingInformation(request_string);

    // Retrieve cookie to obtains existing context if any.
    Cookie integrityCookie = CookieKey.getIntegrityCookie(request.getCookies());

    SecurityContext ctx = null;
    if (integrityCookie != null) {
        String integrity = integrityCookie.getValue();
        if (integrity != null && !integrity.isEmpty()) {
            ctx = SEC_CTX_PROVIDER.getSecurityContext(integrity);
        }
    }
    if ((ctx != null) && (ctx.getAuthentication() != null)) {
        pi.setUsername(ctx.getAuthentication().getName());
    } else {
        String[] basicAuth = extractAndDecodeHeader(request.getHeader("Authorization"));
        if (basicAuth != null) {
            pi.setUsername(basicAuth[0]);
        }
    }
    pi.setRemoteAddress(ProxyWebAuthenticationDetails.getRemoteIp(request));
    pi.setRemoteHost(ProxyWebAuthenticationDetails.getRemoteHost(request));
    return pi;
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current theme from the cookie.
 * //from ww  w.j av  a 2s  . co  m
 * @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 value = this.getSettings().getParam(SysParam.CORE_DEFAULT_THEME_EXTJS.name());
        c = this.createCookie(Constants.COOKIE_NAME_THEME, value, 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;
}

From source file:com.portfolio.data.attachment.FileServlet.java

String[] processCookie(Cookie[] cookies) {
    String login = null;//from ww  w. ja  v  a2s . com
    String[] ret = { login };
    if (cookies == null)
        return ret;

    for (int i = 0; i < cookies.length; ++i) {
        Cookie cookie = cookies[i];
        String name = cookie.getName();
        if ("user".equals(name) || "useridentifier".equals(name))
            login = cookie.getValue();
    }

    ret[0] = login;
    return ret;
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <p>Lookup a client conference number stored in a cookie. If no phone number is provided by the client a random SIP URI phone number is automatically generated.</p>
 * <p>A conference definition template file is used to create the conference definition for the phone number.</p>
 * <p>The auto-assigned phone number is then stored in a cookie and returned to the client.</p>
 * @param out standard output Output writer
 * @param request The HTTP request object
 * @param response The HTTP response object
 *///from  w  ww.  j av  a  2s.c  om
private boolean doCreateNumber(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String strOutputNumber = null;

    Cookie[] arrCookies = request.getCookies();
    if (null != arrCookies) {
        for (Cookie cookie : arrCookies) {
            //logger.debug("cookie name: " + cookie.getName() + ", path: " + cookie.getPath() + ", domain: " + cookie.getDomain() + ", maxAge: " + cookie.getMaxAge() + ", value: " + cookie.getValue());
            if (COOKIE_NUMBER_KEY.equals(cookie.getName())) {
                if (null != (strOutputNumber = cookie.getValue()) && strOutputNumber.length() == 0) {
                    strOutputNumber = null;
                }
                logger.debug("Using cookie stored conference output number: '" + strOutputNumber + "'.");
                break;
            }
        }
    }

    strOutputNumber = createConferenceDefinition(strOutputNumber);

    if (null != strOutputNumber) {

        int cookieAgeDays = 7;
        Cookie cookie = new Cookie(COOKIE_NUMBER_KEY, strOutputNumber);
        cookie.setMaxAge(cookieAgeDays * SECONDS_IN_DAY);
        cookie.setPath("/" + getUriDirSegment(request.getRequestURI(), 0) + "/");
        logger.debug("Setting cookie " + COOKIE_NUMBER_KEY + "=" + strOutputNumber);
        response.addCookie(cookie);
        out.println("number=" + strOutputNumber);
    }

    return true;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//www.jav a2 s.  c o m
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

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. j a va2 s . c o 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:org.kite9.diagram.server.AbstractKite9Controller.java

/**
 * Retrieves user info from cookie//from   w  ww.ja  v a  2 s .c  o m
 */
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.netflix.genie.web.controllers.JobRestController.java

private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) {
    // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header.
    final HttpHeaders headers = forwardRequest.getHeaders();
    final Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            if (!NAME_HEADER_COOKIE.equals(headerName)) {
                final String headerValue = request.getHeader(headerName);
                log.debug("Request Header: name = {} value = {}", headerName, headerValue);
                headers.add(headerName, headerValue);
            }// w ww.j a  va2  s . c  om
        }
    }
    // Lets add the cookie as an header
    final Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        StringBuilder builder = null;
        for (final Cookie cookie : request.getCookies()) {
            if (builder == null) {
                builder = new StringBuilder();
            } else {
                builder.append(",");
            }
            builder.append(cookie.getName()).append("=").append(cookie.getValue());
        }
        if (builder != null) {
            final String cookieValue = builder.toString();
            headers.add(NAME_HEADER_COOKIE, cookieValue);
            log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue);
        }
    }
    // This method only called when need to forward so add the forwarded from header
    headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString());
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

private void assertSingleSessionCookie(String expected) {
    com.gargoylesoftware.htmlunit.util.Cookie jsessionidCookie = cookieManager.getCookie("JSESSIONID");
    if (expected == null || expected.contains("Expires=Thu, 01-Jan-1970 00:00:01 GMT")) {
        assertThat(jsessionidCookie).isNull();
        return;/*from   w ww . ja v a 2  s . c o m*/
    }
    String actual = jsessionidCookie.getValue();
    assertThat("JSESSIONID=" + actual + "; Path=/test; Domain=example.com").isEqualTo(expected);
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override/*from ww w  .j a v  a2s.co m*/
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(new Random().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity)
                            throws Exception {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        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 = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), isHttps);
                        }
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug("Authentication exception: " + ex.getMessage(), ex);
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}