Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

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

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

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

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

        CloudNinjaUser cloudNinjaUser = null;

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.netspective.sparx.security.HttpLoginManager.java

public void logout(HttpServletValueContext vc) {
    vc.getProject().getScrollStates().removeActiveState(vc);

    if (isAllowRememberUserId()) {
        Cookie cookie = new Cookie(getRememberUserIdCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);//from  w  ww.  j  a va 2  s  .  c om
        vc.getHttpResponse().addCookie(cookie);
        cookie = new Cookie(getRememberPasswordCookieName(), "");
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(-1);
        vc.getHttpResponse().addCookie(cookie);
    }

    final HttpServletRequest req = vc.getHttpRequest();
    final MutableAuthenticatedUser user = (MutableAuthenticatedUser) getAuthenticatedUser(req);
    final HttpSession session = req.getSession();
    if (user != null) {
        registerLogout(vc, user);
        session.removeAttribute(getAuthenticatedUserSessionAttrName());
    }
    session.invalidate();
}

From source file:org.jahia.bin.Export.java

/**
 * Process the request and return a ModelAndView object which the DispatcherServlet
 * will render. A <code>null</code> return value is not an error: It indicates that
 * this object completed request processing itself, thus there is no ModelAndView
 * to render.//from   ww w .j a  v a2s . co  m
 *
 * @param request  current HTTP request
 * @param response current HTTP response
 * @return a ModelAndView to render, or <code>null</code> if handled directly
 * @throws Exception in case of errors
 */
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {

        checkUserLoggedIn();

        Matcher m = StringUtils.isNotEmpty(request.getPathInfo()) ? URI_PATTERN.matcher(request.getPathInfo())
                : null;
        if (m == null || !m.matches()) {
            throw new JahiaBadRequestException("Requested URI '" + request.getRequestURI() + "' is malformed");
        }
        String workspace = m.group(1);
        String nodePath = "/" + m.group(2);
        String exportFormat = m.group(3);
        String serverDirectory = null;
        if (StringUtils.isNotEmpty(request.getParameter("exportformat"))) {
            exportFormat = request.getParameter("exportformat");
        }

        Map<String, Object> params = getParams(request);

        JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession(workspace);
        JCRNodeWrapper exportRoot = null;

        if (request.getParameter("root") != null) {
            exportRoot = session.getNode(request.getParameter("root"));
        }

        if (StringUtils.isNotBlank(request.getParameter("exportPath"))) {
            serverDirectory = request.getParameter("exportPath");
            params.put(ImportExportService.SERVER_DIRECTORY, serverDirectory);
        }

        if ("all".equals(exportFormat)) {

            if (!session.getUser().isRoot()) {
                throw JahiaUserManagerService.isGuest(session.getUser())
                        ? new JahiaUnauthorizedException("Only root user can perform export of all content")
                        : new JahiaForbiddenAccessException("Only root user can perform export of all content");
            }

            response.setContentType("application/zip");
            //make sure this file is not cached by the client (or a proxy middleman)
            WebUtils.setNoCacheHeaders(response);

            params.put(ImportExportService.INCLUDE_ALL_FILES, Boolean.TRUE);
            params.put(ImportExportService.INCLUDE_TEMPLATES, Boolean.TRUE);
            params.put(ImportExportService.INCLUDE_SITE_INFOS, Boolean.TRUE);
            params.put(ImportExportService.INCLUDE_DEFINITIONS, Boolean.TRUE);
            params.put(ImportExportService.VIEW_WORKFLOW, Boolean.TRUE);
            params.put(ImportExportService.XSL_PATH, cleanupXsl);

            OutputStream outputStream = response.getOutputStream();
            importExportService.exportAll(outputStream, params);
            outputStream.close();

        } else if ("site".equals(exportFormat)) {

            if (!session.getUser().isRoot()) {
                throw JahiaUserManagerService.isGuest(session.getUser())
                        ? new JahiaUnauthorizedException("Only root user can perform export of a site")
                        : new JahiaForbiddenAccessException("Only root user can perform export of a site");
            }

            List<JCRSiteNode> sites = new ArrayList<JCRSiteNode>();
            String[] sitekeys = request.getParameterValues("sitebox");
            if (sitekeys != null) {
                for (String sitekey : sitekeys) {
                    JahiaSite site = ServicesRegistry.getInstance().getJahiaSitesService()
                            .getSiteByKey(sitekey);
                    sites.add((JCRSiteNode) site);
                }
            }

            if (sites.isEmpty()) {
                // Todo redirect to new administration
            } else {
                response.setContentType("application/zip");
                //make sure this file is not cached by the client (or a proxy middleman)
                WebUtils.setNoCacheHeaders(response);

                params.put(ImportExportService.INCLUDE_ALL_FILES, Boolean.TRUE);
                params.put(ImportExportService.INCLUDE_TEMPLATES, Boolean.TRUE);
                params.put(ImportExportService.INCLUDE_SITE_INFOS, Boolean.TRUE);
                params.put(ImportExportService.INCLUDE_DEFINITIONS, Boolean.TRUE);
                if (request.getParameter("live") == null || Boolean.valueOf(request.getParameter("live"))) {
                    params.put(ImportExportService.INCLUDE_LIVE_EXPORT, Boolean.TRUE);
                }
                if (request.getParameter("users") == null && SettingsBean.getInstance().getPropertiesFile()
                        .getProperty("siteExportUsersDefaultValue") != null) {
                    Boolean siteExportUsersDefaultValue = Boolean.valueOf(SettingsBean.getInstance()
                            .getPropertiesFile().getProperty("siteExportUsersDefaultValue"));
                    if (siteExportUsersDefaultValue.booleanValue()) {
                        params.put(ImportExportService.INCLUDE_USERS, Boolean.TRUE);
                    } else {
                        params.remove(ImportExportService.INCLUDE_USERS);
                    }
                } else if (request.getParameter("users") != null) {
                    if (Boolean.valueOf(request.getParameter("users"))) {
                        params.put(ImportExportService.INCLUDE_USERS, Boolean.TRUE);
                    } else {
                        params.remove(ImportExportService.INCLUDE_USERS);
                    }
                } else {
                    params.put(ImportExportService.INCLUDE_USERS, Boolean.TRUE);
                }
                params.put(ImportExportService.INCLUDE_ROLES, Boolean.TRUE);
                params.put(ImportExportService.INCLUDE_MOUNTS, Boolean.TRUE);
                params.put(ImportExportService.VIEW_WORKFLOW, Boolean.TRUE);
                params.put(ImportExportService.XSL_PATH, cleanupXsl);

                OutputStream outputStream = response.getOutputStream();
                importExportService.exportSites(outputStream, params, sites);
                outputStream.close();
            }

        } else if ("xml".equals(exportFormat)) {

            JCRNodeWrapper node = session.getNode(nodePath);
            response.setContentType("text/xml");
            //make sure this file is not cached by the client (or a proxy middleman)
            WebUtils.setNoCacheHeaders(response);

            if ("template".equals(request.getParameter(CLEANUP))) {
                params.put(ImportExportService.XSL_PATH, templatesCleanupXsl);
            } else if ("simple".equals(request.getParameter(CLEANUP))) {
                params.put(ImportExportService.XSL_PATH, cleanupXsl);
            }
            OutputStream outputStream = response.getOutputStream();
            Cookie exportedNode = new Cookie("exportedNode", node.getIdentifier());
            exportedNode.setMaxAge(60);
            exportedNode.setPath("/");
            response.addCookie(exportedNode);
            //No export log for the node export
            importExportService.exportNode(node, exportRoot, outputStream, params);

        } else if ("zip".equals(exportFormat)) {

            JCRNodeWrapper node = session.getNode(nodePath);
            response.setContentType("application/zip");
            //make sure this file is not cached by the client (or a proxy middleman)
            WebUtils.setNoCacheHeaders(response);

            if ("template".equals(request.getParameter(CLEANUP))) {
                params.put(ImportExportService.XSL_PATH, templatesCleanupXsl);
            } else if ("simple".equals(request.getParameter(CLEANUP))) {
                params.put(ImportExportService.XSL_PATH, cleanupXsl);
            }
            if (request.getParameter("live") == null || Boolean.valueOf(request.getParameter("live"))) {
                params.put(ImportExportService.INCLUDE_LIVE_EXPORT, Boolean.TRUE);
            }
            OutputStream outputStream = response.getOutputStream();
            Cookie exportedNode = new Cookie("exportedNode", node.getIdentifier());
            exportedNode.setMaxAge(60);
            exportedNode.setPath("/");
            response.addCookie(exportedNode);
            importExportService.exportZip(node, exportRoot, outputStream, params);
            outputStream.close();
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        if (logger.isDebugEnabled())
            logger.debug("Cannot export due to some IO exception", e);
        else
            logger.warn("Cannot export due to some IO exception :" + e.getMessage());
        DefaultErrorHandler.getInstance().handle(e, request, response);
    } catch (Exception e) {
        logger.error("Cannot export", e);
        DefaultErrorHandler.getInstance().handle(e, request, response);
    }

    return null;
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

/** 
* Invalida la cookie AUTENTICADO//from ww w .j a  va  2s .c  o m
* @param response
* @param request
*/
private void invalidateCookieAutenticado(HttpServletResponse response) throws IOException {

    Cookie cookieAutenticado = new Cookie("AUTENTICADO", "");
    cookieAutenticado.setPath("/");
    cookieAutenticado.setMaxAge(0);
    response.addCookie(cookieAutenticado);

}

From source file:org.mule.transport.http.servlet.MuleHttpServletResponse.java

private org.apache.commons.httpclient.Cookie toHttpClientCookie(Cookie cookie) {
    org.apache.commons.httpclient.Cookie internal = new org.apache.commons.httpclient.Cookie();

    internal.setName(cookie.getName());/*from w w w .  j  av  a2 s  . c om*/
    internal.setValue(cookie.getValue());
    internal.setComment(cookie.getComment());
    internal.setDomain(cookie.getDomain());
    //        internal.setExpiryDate(toExpiry(cookie.getMaxAge()));
    internal.setPath(cookie.getPath());
    internal.setVersion(cookie.getVersion());

    return internal;
}

From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java

/**
 * Setup the Alfresco auth cookie value.
 * // w  w w  . j a v  a  2 s .com
 * @param httpRequest
 * @param httpResponse
 * @param username
 */
public static void setUsernameCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String username) {
    if (logger.isDebugEnabled())
        logger.debug("Setting up the Alfresco auth cookie for " + username);
    Cookie authCookie = getAuthCookie(httpRequest);
    // Let's Base 64 encode the username so it is a legal cookie value
    String encodedUsername;
    try {
        encodedUsername = Base64.encodeBytes(username.getBytes("UTF-8"));
        if (logger.isDebugEnabled())
            logger.debug("Base 64 encode the username: " + encodedUsername);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    if (authCookie == null) {
        if (logger.isDebugEnabled())
            logger.debug("No Alfresco auth cookie wa found, creating new one.");
        authCookie = new Cookie(COOKIE_ALFUSER, encodedUsername);
    } else {
        if (logger.isDebugEnabled())
            logger.debug("Updating the previous Alfresco auth cookie value.");
        authCookie.setValue(encodedUsername);
    }
    authCookie.setPath(httpRequest.getContextPath());
    // TODO: make this configurable - currently 7 days (value in seconds)
    authCookie.setMaxAge(60 * 60 * 24 * 7);
    httpResponse.addCookie(authCookie);
}

From source file:com.netspective.sparx.security.HttpLoginManager.java

public void login(HttpServletValueContext vc, MutableAuthenticatedUser user, boolean rememberUserId) {
    vc.getHttpRequest().getSession().setAttribute(getAuthenticatedUserSessionAttrName(), user);

    if (isAllowRememberUserId() && rememberUserId) {
        Cookie cookie = new Cookie(getRememberUserIdCookieName(), user.getUserId().toString());
        cookie.setPath(getRememberPasswordCookiePath(vc));
        cookie.setMaxAge(getRememberUserIdCookieMaxAge());
        vc.getHttpResponse().addCookie(cookie);
        cookie = new Cookie(getRememberPasswordCookieName(), user.getEncryptedPassword());
        cookie.setMaxAge(getRememberUserIdCookieMaxAge());
        cookie.setPath(getRememberPasswordCookiePath(vc));
        vc.getHttpResponse().addCookie(cookie);
    }/*from w  w w  .  j  a v a 2 s. com*/

    registerLogin(vc, user);
}

From source file:org.apache.hadoop.security.authentication.server.AuthenticationFilter.java

/**
 * Creates the Hadoop authentiation HTTP cookie.
 * <p/>/*from  w w  w . j a  va2  s. co  m*/
 * It sets the domain and path specified in the configuration.
 *
 * @param token authentication token for the cookie.
 *
 * @return the HTTP cookie.
 */
protected Cookie createCookie(String token) {
    Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, token);
    if (getCookieDomain() != null) {
        cookie.setDomain(getCookieDomain());
    }
    if (getCookiePath() != null) {
        cookie.setPath(getCookiePath());
    }
    return cookie;
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

private void setCookieAutenticado(HttpServletResponse response, String claimedIdentity) throws IOException {

    Cookie cookieOpenId = new Cookie(nombreCookieOpenId, claimedIdentity);
    cookieOpenId.setPath("/");
    //El tiempo de expiracin de la cookie se recoger del Agrega.properties

    int caducidadCookie = new Long(((System.currentTimeMillis()) * 1000)).intValue()
            + (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID))).intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookieOpenId.setMaxAge(caducidadCookie);
    //cookieOpenId.setMaxAge(-1);
    response.addCookie(cookieOpenId);/*from  w w  w  . ja  va 2  s  .c  o m*/

}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * cookie//from  ww  w .  jav a 2s. co  m
 * 
 * @param name
 *            Cookie??
 * @param val
 *            
 * @param expiry
 *            
 * @param domain
 *            
 * @param path
 *            
 * @param httpOnly
 *            ??HTTPcooie
 * @param secure
 *            ?SSL
 * @return
 */
public static Cookie cookie(String name, Object val, Integer expiry, String domain, String path,
        boolean httpOnly, boolean secure) {
    Cookie cookie = new Cookie(name, val == null ? null : val.toString());
    if (expiry != null)
        cookie.setMaxAge(expiry);
    if (!StringUtils.isEmpty(domain))
        cookie.setDomain(domain);
    cookie.setSecure(secure);
    if (!StringUtils.isEmpty(path))
        cookie.setPath(path);
    cookie.setHttpOnly(httpOnly);
    return cookie;
}