Example usage for javax.servlet.http Cookie clone

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

Introduction

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

Prototype

public Object clone() 

Source Link

Document

Overrides the standard java.lang.Object.clone method to return a copy of this Cookie.

Usage

From source file:com.adobe.acs.commons.util.CookieUtil.java

/**
 * Internal method used for dropping cookies
 *
 * @param response// ww  w. j  a v  a  2s  .  c o m
 * @param cookies
 * @param cookiePath
 * @return
 */
private static int dropCookies(final HttpServletResponse response, final Cookie[] cookies,
        final String cookiePath) {
    int count = 0;

    for (final Cookie cookie : cookies) {
        if (cookie == null) {
            continue;
        }

        final Cookie responseCookie = (Cookie) cookie.clone();
        responseCookie.setMaxAge(0);
        responseCookie.setPath(cookiePath);
        responseCookie.setValue("");

        addCookie(responseCookie, response);
        count++;
    }

    return count;
}

From source file:com.adobe.acs.commons.util.CookieUtil.java

/**
 * <p>/*w w w.ja  v a 2  s .c om*/
 * Extend the cookie life.
 * <p></p>
 * This can be used when a cookie should be valid for X minutes from the last point of activity.
 * <p></p>
 * This method will leave expired or deleted cookies alone.
 * </p>
 *
 * @param request    Request to get the Cookie from
 * @param response   Response to write the extended Cookie to
 * @param cookieName Name of Cookie to extend the life of
 * @param expiry     New Cookie expiry
 */
public static boolean extendCookieLife(final HttpServletRequest request, final HttpServletResponse response,
        final String cookieName, final String cookiePath, final int expiry) {
    final Cookie cookie = getCookie(request, cookieName);
    if (cookie == null) {
        return false;
    }

    if (cookie.getMaxAge() <= 0) {
        return false;
    }

    final Cookie responseCookie = (Cookie) cookie.clone();
    responseCookie.setMaxAge(expiry);
    responseCookie.setPath(cookiePath);

    addCookie(responseCookie, response);

    return true;
}

From source file:m.c.m.proxyma.resource.ProxymaResponseDataBean.java

/**
 * This method clone the current response data into a new separated object.
 *
 * @return a new and separate instance of the object.
 * @throws CloneNotSupportedException if the clone operation is not supported
 *//*from   ww w  . j a va2  s . co m*/
@Override
public Object clone() throws CloneNotSupportedException {
    //clone self
    ProxymaResponseDataBean clone = (ProxymaResponseDataBean) super.clone();

    //Clone headers
    clone.headers = (HashMap<String, Object>) new HashMap();
    Iterator<String> stringIterarot = this.getHeaderNames().iterator();
    String headerName = null;
    ProxymaHttpHeader header = null;
    Collection<ProxymaHttpHeader> multiHeader = null;
    while (stringIterarot.hasNext()) {
        headerName = stringIterarot.next();
        if (this.isMultipleHeader(headerName)) {
            //Process multiple values header.
            multiHeader = this.getMultivalueHeader(headerName);
            Iterator<ProxymaHttpHeader> instanceHeaders = multiHeader.iterator();
            while (instanceHeaders.hasNext()) {
                header = instanceHeaders.next();
                clone.addHeader(header.getName(), header.getValue());
            }
        } else {
            //Process Sungle value header
            header = this.getHeader(headerName);
            clone.addHeader(header.getName(), header.getValue());
        }
    }

    //clone cookies
    clone.cookies = (HashMap<String, Cookie>) new HashMap();
    Iterator<Cookie> cookieIterator = this.getCookies().iterator();
    while (cookieIterator.hasNext()) {
        Cookie original = cookieIterator.next();
        clone.addCookie((Cookie) original.clone());
    }

    //Clone data
    if (data != null)
        clone.data = (ByteBuffer) data.clone();
    return clone;
}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }/*from ww w. j a v  a 2  s  .  c o  m*/
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:uk.ac.ed.epcc.webapp.servlet.DefaultServletService.java

/**invalidate the servlet session and optionally remove the session cookie.
 *
 * /*  w ww  .  j  ava 2  s  .  com*/
 * 
 * @param remove_cookie should cookie be removed
 * 
 */
public void logout(boolean remove_cookie) {
    HttpSession sess = getSession();
    if (sess != null) {
        sess.invalidate();
    }
    if (remove_cookie) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie c : cookies) {
                    if (c.getName().equalsIgnoreCase("JSESSIONID") || getContext()
                            .getBooleanParameter(LOGOUT_REMOVE_COOKIE_PREFIX + c.getName(), false)) {
                        Cookie c2 = (Cookie) c.clone();
                        c2.setMaxAge(0); // This should request a delete
                        if (c2.getPath() == null) {
                            String contextPath = request.getContextPath();
                            c2.setPath(contextPath + "/"); // browser did not include path. This will only work if path matched exactly
                        }
                        c2.setValue("");
                        ((HttpServletResponse) res).addCookie(c2);
                    }
                }
            }
        }
    }
}