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.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java

@Override
public void preAuthenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateTLSClientAuthenticationFilter.preAuthenticate is called");

    Validate.notNull(t);// ww  w . j ava2  s.  c o m
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);

    // then check if required auth header is present
    if (request.getParameter(Shared.REQUEST_AUTH_PARAM) == null) {
        // authentication not possible
        log.debug(Shared.REQUEST_AUTH_PARAM + " is missing, requesting " + Shared.TLSCLIENT_AUTH_PREFIX);
        t.setWwwAuthenticate(Shared.TLSCLIENT_AUTH_PREFIX);
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.BAD_REQUEST,
                null);
        t.setValidationResult(vr);
        throw new SamlServiceException();
    }

    // check if logout cookie is present
    Cookie[] cookies = request.getCookies();
    String logoutCookieName = Shared.getLogoutCookieName(accessor.getTenant());
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(logoutCookieName)) {
                ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST,
                        WebSSOError.UNAUTHORIZED, WebSSOError.LOGGED_OUT_TLS_SESSION);
                t.setValidationResult(vr);
                throw new SamlServiceException();
            }
        }
    }
}

From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java

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

        @Override//from  ww  w .  ja  v a2  s  .c o  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(ThreadLocalRandom.current().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) {

                    }

                    @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 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, name, 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());
                            tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps);
                            request.setAttribute(SIGNED_TOKEN_ATTRIBUTE,
                                    tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(),
                                            token.getExpires(), !token.isExpired() && token.getExpires() > 0,
                                            isHttps));
                        }
                        // Since this request is validated also set DRUID_AUTHENTICATION_RESULT
                        request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                                new AuthenticationResult(token.getName(), authorizerName, name, null));
                        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(ex, "Authentication exception: " + ex.getMessage());
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, 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());
                    }
                }
            }
        }
    };
}

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

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

        @Override/*from  www  .  j  ava  2 s  . c om*/
        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());
                    }
                }
            }
        }
    };
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected boolean prepareForwardingCookies(HttpRequestBase method, HttpServletRequest request,
        DefaultHttpClient httpClient) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    Cookie[] cookies = request.getCookies();
    BasicCookieStore cs = new BasicCookieStore();
    httpClient.setCookieStore(cs);/*from w ww. ja va 2  s .c  o m*/
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookiename = cookie.getName();
                if (StringUtil.isNotEmpty(cookiename)) {
                    String cookieval = cookie.getValue();
                    if (cookiename.startsWith(PASSTHRUID)) {
                        cookiename = cookiename.substring(PASSTHRUID.length());
                        if (isCookieAllowed(cookiename)) {
                            String[] parts = decodeCookieNameAndPath(cookiename);
                            if (parts != null && parts.length == 3) {
                                cookiename = parts[0];
                                String path = parts[1];
                                String domain = parts[2];

                                // Got stored domain now see if it matches destination
                                BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                                methodcookie.setDomain(domain);
                                methodcookie.setPath(path);
                                cs.addCookie(methodcookie);
                                if (getDebugHook() != null) {
                                    getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                            methodcookie.toString());
                                }
                            }
                        }
                    } else if (isCookieAllowed(cookiename)) {
                        BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                        String domain = cookie.getDomain();
                        if (domain == null) {
                            try {
                                domain = method.getURI().getHost();
                                domain = domain.substring(domain.indexOf('.'));
                            } catch (Exception e) {
                                domain = "";
                            }
                        }
                        methodcookie.setDomain(domain);
                        String path = cookie.getPath();
                        if (path == null) {
                            path = "/";
                        }
                        methodcookie.setPath(path);
                        cs.addCookie(methodcookie);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                    methodcookie.toString());
                        }
                    }
                }
            }
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "perpareForwardingCookie");
    return true;
}

From source file:org.bpmscript.web.BpmScriptCookieController.java

@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    response.setContentType(contentType);

    String requestUri = request.getRequestURI();
    String definitionName = null;
    String methodName = null;//w w w .  j  a v a 2  s.  c o m
    String split[] = request.getRequestURI().split("/");
    if (requestUri.endsWith("/")) {
        definitionName = split[split.length - 1];
        methodName = defaultIndexName;
    } else {
        definitionName = split[split.length - 2];
        methodName = split[split.length - 1].split("\\.")[0];
    }

    String correlationIdParam = null;

    String cookieName = cookiePrefix + StringUtils.capitalize(definitionName)
            + StringUtils.capitalize(methodName);

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        String name = cookie.getName();
        if (cookieName.equals(name)) {
            correlationIdParam = cookie.getValue();
        }
    }

    String timeoutParam = request.getParameter("timeout");
    long timeout = defaultTimeout;
    if (timeoutParam != null) {
        try {
            timeout = Integer.parseInt(timeoutParam);
        } catch (NumberFormatException e) {
            log.debug(e);
        }
    }
    try {
        SerializableHttpServletRequest serializableHttpServletRequest = new SerializableHttpServletRequest(
                request);
        if (correlationIdParam == null) {
            Object result = null;
            String conversationId = null;
            Object message = bpmScriptFacade.call(definitionName, methodName, timeout,
                    serializableHttpServletRequest);
            if (message instanceof IInvocationMessage) {
                IInvocationMessage conversationMessage = (IInvocationMessage) message;
                result = conversationMessage.getArgs()[0];
                conversationId = conversationMessage.getCorrelationId();
            } else {
                result = message;
            }
            if (result instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) result;
                if (conversationId != null) {
                    map.put("conversationId", conversationId);
                    response.addCookie(new Cookie(cookieName, conversationId));
                }
                ModelAndView modelAndView = new ModelAndView((String) map.get("view"), map);
                return modelAndView;
            } else {
                throw new Exception("result must be a map or a conversation");
            }
        } else {

            IInvocationMessage conversationMessage = null;

            conversationMessage = (IInvocationMessage) conversationCorrelator.call(correlationIdParam, timeout,
                    serializableHttpServletRequest);

            if (conversationMessage != null) {
                Map<String, Object> result = (Map<String, Object>) conversationMessage.getArgs()[0];
                String conversationId = conversationMessage.getCorrelationId();
                result.put("conversationId", conversationId);
                String replyTo = conversationMessage.getReplyTo();
                Cookie cookie = new Cookie(cookieName, conversationId);
                if (replyTo == null) {
                    cookie.setMaxAge(0);
                }
                response.addCookie(cookie);
                ModelAndView modelAndView = new ModelAndView((String) result.get("view"), result);
                return modelAndView;
            } else {
                Cookie cookie = new Cookie(cookieName, "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                throw new Exception("Did not get a response for message " + correlationIdParam);
            }
        }
    } catch (Throwable e) {
        if (e instanceof Exception) {
            throw (Exception) e;
        } else {
            throw new Exception(e);
        }
    }
}

From source file:ips1ap101.lib.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 ava2s  . co m
     * 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 = new String[2];
    switch (option) {
    case 1:
        clave[0] = qualifiedKey;
        clave[1] = null;
        break;
    case 2:
        clave[0] = key;
        clave[1] = null;
        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.shenit.commons.utils.HttpUtils.java

/**
 * Dump out things from HttpServletRequest object
 * //from  w w w  .  j a v a2  s .  c om
 * @param req
 * @return
 */
public static String dumpRequest(HttpServletRequest req) {
    if (req == null)
        return null;
    char column = ':', rtn = '\n', space = ' ';
    StringBuilder builder = new StringBuilder(req.getMethod());
    builder.append(space).append(req.getRequestURL().toString()).append(space).append(req.getProtocol())
            .append(rtn);
    Enumeration<String> headers = req.getHeaderNames();
    builder.append("HEADERS:\n");
    String header;
    for (; headers.hasMoreElements();) {
        header = headers.nextElement();
        builder.append(header).append(column).append(req.getHeader(header)).append(rtn);
    }
    builder.append("COOKIES:\n");
    Cookie cookie;
    Cookie[] cookies = req.getCookies();
    if (!ValidationUtils.isEmpty(cookies)) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            builder.append(cookie.getName()).append(column).append(GsonUtils.format(cookie)).append(rtn);
        }
    }
    builder.append("BODY:\n");
    Map<String, String[]> params = req.getParameterMap();
    for (String name : params.keySet()) {
        builder.append(name).append(ShenStrings.DELIMITER_DOT);
        builder.append(name.matches(PASS_PATTERN) ? params.get(SECRET_STRING) : params.get(name));
    }
    return builder.toString();

}

From source file:com.ssbusy.controller.catalog.CategoryController.java

@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView model = new ModelAndView();
    MyCustomer customer = (MyCustomer) CustomerState.getCustomer();

    HttpSession session = request.getSession();
    MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode");
    Boolean w_flag = Boolean.FALSE;
    // cookies/*from ww w. jav a2 s .  c  o  m*/
    String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    int count = 0;// ??
    Cookie cookies[] = request.getCookies();
    Boolean uiv2 = null;
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (dateTime.equals(c.getName())) {
                count = Integer.valueOf(c.getValue());
                break;
                // } else if ("uiv2".equals(c.getName())) {
                // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie
            }
        }
    }
    if (cookies != null) {
        for (Cookie c : cookies) {
            if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) {
                model.addObject("rember", c.getValue());
                break;
            }
        }
    }
    // String uiParam = request.getParameter("uiv2");
    // if (StringUtils.isNotEmpty(uiParam)) { // 1 param
    // uiv2 = Boolean.valueOf(uiParam);
    // Cookie c = new Cookie("uiv2", uiv2.toString());
    // c.setPath("/");
    // c.setMaxAge(60 * 60 * 24 * 360);
    // response.addCookie(c);
    // } else if (uiv2 == null) {
    uiv2 = Boolean.TRUE; // 3 default. 
    // }
    session.setAttribute("uiv2", uiv2);
    // LOG.warn("uiv2=" + uiv2);

    if (myOfferCode != null) {
        if (customer.isRegistered())
            giftService.updateOwnerCustomer(customer, myOfferCode);
        else
            myOfferCode = null;
    } else if (count < maxoffercodeCount) {
        myOfferCode = giftService.getgift(customer);
        if (myOfferCode != null) {
            if (customer.isAnonymous()) {
                session.setAttribute("bonusOfferCode", myOfferCode);
                model.addObject("bonusOfferCode", myOfferCode);
                myOfferCode = null;
            }
        }
    }
    if (myOfferCode != null) {
        session.removeAttribute("bonusOfferCode");
        model.addObject("bonusOfferCode", myOfferCode);
        Cookie c = new Cookie(dateTime, String.valueOf(count + 1));
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24);
        response.addCookie(c);
        LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr());
    }

    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the
        // field to the
        // product search criteria expected format. This is used in
        // multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical
        // URLs

        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }

        parameters.remove(ProductSearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");

        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        model.setViewName("redirect:" + newUrl);
    } else {
        // Else, if we received a GET to the category URL (either the user
        // clicked this link or we redirected
        // from the POST method, we can actually process the results

        Category category = (Category) request
                .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME);
        assert (category != null);

        List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category);
        ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets);

        String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING);
        ProductSearchResult result;

        List<FulfillmentLocation> locations = null;
        try {
            // 
            if (customer != null && customer.getRegion() != null) {
                InventorySolrSearchServiceExtensionHandler.customerLocation
                        .set(locations = customer.getRegion().getFulfillmentLocations());
            }
            if (StringUtils.isNotBlank(searchTerm)) {
                result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria);
            } else {
                result = searchService.findProductsByCategory(category, searchCriteria);
            }
        } finally {
            InventorySolrSearchServiceExtensionHandler.customerLocation.remove();
        }

        facetService.setActiveFacetResults(result.getFacets(), request);
        List<Product> products = result.getProducts();

        if (products != null && products.size() > 0) {
            List<String> prodIds = new ArrayList<String>(products.size());
            for (Product product : products) {
                prodIds.add(String.valueOf(product.getId()));
            }
            model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT));

            // ?productinventories
            if (locations != null) {
                Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations);
                model.addObject("inventories", invs);
            }
        }

        model.addObject(PRODUCTS_ATTRIBUTE_NAME, products);
        model.addObject(CATEGORY_ATTRIBUTE_NAME, category);
        // facets
        List<SearchFacetDTO> facets = result.getFacets();
        if (facets != null) {
            _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) {
                SearchFacetDTO dto = itr.next();
                if (dto != null && dto.getFacetValues() != null) {
                    for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) {
                        if (searchFacetDTO != null)
                            if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0)
                                continue _nextFact;
                    }
                }
                itr.remove();
            }
            model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets());
        }
        model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);

        // TODO temp
        String view = category.getDisplayTemplate();
        if (StringUtils.isEmpty(view))
            view = getDefaultCategoryView();
        if (request.getRequestURI().startsWith("/weixin/")) {
            view = "weixin/catalog/w_category_item";
            w_flag = Boolean.TRUE;
        }
        if (uiv2) {
            if ("layout/home".equals(view))
                view = "v2/home";
            else {
                if (!view.startsWith("activity") && !view.startsWith("weixin/")) {
                    view = "v2/" + view;
                }

            }
        }
        session.setAttribute("w_flag", w_flag);
        model.setViewName(view);
    }
    // if (isAjaxRequest(request)) {
    // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM);
    // model.addObject("ajax", Boolean.TRUE);
    // }
    return model;
}

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

@RequestMapping(value = "{tenantId}/showTenantProfilePage.htm", method = RequestMethod.POST)
public ModelAndView showProfilePage(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie,
        @ModelAttribute("logoFileDTO") LogoFileDTO logoFileDTO, BindingResult result) {
    // validate the file uploaded for logo
    logoFileDTOValidator.validate(logoFileDTO, result);
    // if no errors in validation then only process the request
    if (!result.hasErrors()) {
        if (cookie == null) {
            cookie = request.getAttribute("cookieNameAttr").toString();
        }//www .  ja  v  a  2s  .co m
        String tenantId = AuthFilterUtils
                .getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX, cookie);

        String logoFileName = fileUploadService.fileUploadService(logoFileDTO.getFile(), tenantId);

        String logoCookieName = "CLOUDNINJALOGO";

        // update the logo cookie with the new logo file
        Cookie cookies[] = request.getCookies();
        Cookie logoCookie = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(logoCookieName)) {
                    logoCookie = cookies[i];
                    logoCookie.setValue(logoFileName);
                    logoCookie.setMaxAge(-1);
                    logoCookie.setPath("/");
                    response.addCookie(logoCookie);
                    break;
                }
            }
        }
    }

    return new ModelAndView("tenantProfilePage", "logoFileDTO", logoFileDTO);
}