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.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write session cookie.//w w w  . j a va 2  s . c o  m
 *
 * @return
 */
private void writeSessionCookie(HttpServletResponse response, HttpSession session, boolean secured) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(-1);
    cookie.setPath(session.getServletContext().getContextPath());
    cookie.setHttpOnly(true);
    if (secured) {
        cookie.setSecure(secured);
    }
    response.addCookie(cookie);
}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write connections cookie.//from www .jav a  2s.c om
 *
 * @param name
 * @param value
 * @param duration
 * @return
 */
private void writeCookie(HttpServletResponse response, String name, String value, int duration,
        boolean secure) {
    String cookieValue;
    try {
        cookieValue = URLEncoder.encode(value, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException ex) {
        cookieValue = value;
    }
    Cookie cookie = new Cookie(name, cookieValue);
    cookie.setMaxAge(duration);
    cookie.setPath("/");
    if (secure) {
        cookie.setSecure(true);
    }
    response.addCookie(cookie);
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    try {/* w  w  w  .ja va  2 s.c om*/
        String remoteAddress = request.getRemoteAddr();

        this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress);
        String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response,
                data, spep);
        PrintStream out = new PrintStream(response.getOutputStream());

        /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */
        Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled");
        autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT
        autoSubmit.setPath("/");
        response.addCookie(autoSubmit);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "text/html");

        out.print(document);

        out.close();

        this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress);
    } catch (IOException e) {
        throw new AuthenticationException("Unable to send response due to an I/O error.", e);
    }
}

From source file:com.mockey.model.ResponseFromService.java

private void setCookiesFromHeader(Header[] headers) {
    for (Header header : headers) {

        if (header.getName().equals("Set-Cookie")) {
            String headerValue = header.getValue();
            // Parse cookie
            String[] fields = headerValue.split(";\\s*");

            //String cookieValue = fields[0];
            //String expires = null;
            String path = null;//from   w  ww .ja va2  s  . c o m
            String domain = null;
            boolean secure = false;

            // Parse each field
            for (int j = 1; j < fields.length; j++) {
                if ("secure".equalsIgnoreCase(fields[j])) {
                    secure = true;
                } else if (fields[j].indexOf('=') > 0) {
                    String[] f = fields[j].split("=");
                    if ("expires".equalsIgnoreCase(f[0])) {
                        //expires = f[1];
                    } else if ("domain".equalsIgnoreCase(f[0])) {
                        domain = f[1];
                    } else if ("path".equalsIgnoreCase(f[0])) {
                        path = f[1];
                    }
                }
            }
            String[] cookieParts = headerValue.split("=", 2);
            String cookieBody = cookieParts[1];
            String[] cookieBodyParts = cookieBody.split("; ");
            Cookie cookie = new Cookie(cookieParts[0], cookieBodyParts[0]);
            cookie.setDomain(domain);
            cookie.setPath(path);
            cookie.setSecure(secure);
            //            if(expires!=null){
            //            Date expiresTime = null;
            //            try {
            //               expiresTime = HttpCookieDateUtil.parseDate(expires);
            //               Date nowTime = new Date();
            //               long maxAge = nowTime.getTime() - expiresTime.getTime();
            //               cookie.setMaxAge((int) maxAge/1000);
            //            }catch(Exception e){
            //               log.error("Unable to calculate maxAge with expiration date "+expiresTime, e);
            //            }
            //            }
            this.cookieList.add(cookie);
        }

    }
}

From source file:net.ymate.platform.mvc.web.support.CookieHelper.java

/**
 * @param key /*from  ww  w. jav  a 2 s .  c  o  m*/
 * @param value 
 * @param maxAge 
 * @return ?Cookie
 */
public CookieHelper setCookie(String key, String value, int maxAge) {
    Cookie _cookie = new Cookie(WebMVC.getConfig().getCookiePrefix() + key,
            StringUtils.isBlank(value) ? "" : encodeValue(value));
    _cookie.setMaxAge(maxAge);
    _cookie.setPath(WebMVC.getConfig().getCookiePath());
    if (StringUtils.isNotBlank(WebMVC.getConfig().getCookieDomain())) {
        _cookie.setDomain(WebMVC.getConfig().getCookieDomain());
    }
    _cookie.setSecure(__request.getServerPort() == 443 ? true : false);
    WebContext.getResponse().addCookie(_cookie);
    return this;
}

From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java

/**
 * @param response//from  w ww . j av  a2  s  .  c  o  m
 * @param config
 * @param value
 * 
 * @throws Exception
 */
private void removeCookie(HttpServletResponse response, SessionAttributeConfig config) throws Exception {
    String cookieName = config.getNickName();

    Cookie cookie = new Cookie(cookieName, null);
    ;
    // COOKIE
    String cookiePath = COOKIE_PATH;

    if (config.getCookiePath() != null) {
        cookiePath = config.getCookiePath();
    }

    cookie.setPath(cookiePath);

    log.debug("remove cookie name: " + cookieName);

    cookie.setMaxAge(0);
    String domain = config.getDomain();

    if ((domain != null) && (domain.length() > 0)) {
        cookie.setDomain(domain);
    }

    response.addCookie(cookie);
}

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

private void removeCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String authCookieName) {//from  ww w .j a  v  a2s  . co  m

    //   Cookie cookieToBeRemoved = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, authCookieName);
    Cookie cookie = new Cookie(authCookieName, null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    httpServletResponse.addCookie(cookie);
}

From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java

@Override
public void destroySessions(final HttpServletRequest request, final HttpServletResponse response) {
    final String portalSessionId = this.getPortalSessionId(request);
    if (portalSessionId != null) {
        final SessionBucket sessionBucket = this.sessionBucketCache.remove(portalSessionId);
        sessionBucket.destroy();//from ww  w.j a  va2  s . co  m
        final Cookie portalSessionCookie = new Cookie(IPortal.PORTAL_SESSION_ID_COOKIE_NAME,
                "SESSION_DESTROYED");
        portalSessionCookie.setPath("/");
        response.addCookie(portalSessionCookie);

        this.generatedSessionIds.remove(portalSessionId);
    }
}

From source file:org.kuali.mobility.shared.interceptors.NativeCookieInterceptor.java

/**
 * Attempts to detect REMOTE_USER and sets currentNetworkId cookie with the value
 *
 * @param request//w  w  w .j  av  a2  s . c  o  m
 * @param response
 * @return
 * @deprecated This could should be placed in an other interceptor, this interceptor is only meant to detect platform specifics
 */
@Deprecated
private void checkAuthenticatedUser(HttpServletRequest request, HttpServletResponse response) {
    String loggedInUser = request.getRemoteUser();
    User user;
    if (StringUtils.isEmpty(loggedInUser)
            && ((user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY)) != null)) {
        loggedInUser = user.getLoginName();
    }

    LOG.debug("REMOTE_USER: " + loggedInUser);
    if (loggedInUser != null && !loggedInUser.trim().isEmpty()) {
        boolean useSecureCookies = Boolean
                .parseBoolean(getKmeProperties().getProperty("kme.secure.cookie", "false"));
        Cookie userCookie = new Cookie("currentNetworkId", loggedInUser);
        userCookie.setMaxAge(60 * 60); //1hr
        userCookie.setPath(request.getContextPath());
        userCookie.setSecure(useSecureCookies);
        response.addCookie(userCookie);
        LOG.debug("Setting currentNetworkId cookie : " + loggedInUser);
    }
}

From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map requestMap = HttpServletHelper.getInstance().createRequestMap(request);
    Map session = HttpServletHelper.getInstance().createSessionMap(request);
    Map application = HttpServletHelper.getInstance().createApplicationMap(request);

    ModelAndView returnedMv;/*from   ww w.  ja va  2  s  . c om*/

    if (controller instanceof CancelableController
            && ((CancelableController) controller).isCancel(requestMap)) {
        returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application,
                command, errors);
    } else {
        returnedMv = controller.handleRequest(command, requestMap, session, application, errors);
    }

    boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false);

    if (errors.hasErrors()) {
        logger.debug("Form submission errors: " + errors.getErrorCount());
        HttpServletHelper.getInstance().reloadApplicationMap(request, application);
        HttpServletHelper.getInstance().reloadSessionMap(request, session);
        HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);
        if (saveCookies) {
            Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes");
            cookie.setMaxAge(30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return showForm(request, response, errors);
    }

    if (returnedMv.getViewName() != null) {
        // should get from mappings
        String mappedView = (String) screenMappings.get(returnedMv.getViewName());

        if (mappedView == null) {
            mappedView = returnedMv.getViewName();
        }

        //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView);

        returnedMv = new ModelAndView(mappedView, returnedMv.getModel());
    }

    //We have a successful save coming back, so we set/append to a cookie
    String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS);
    if (savedForm != null && saveCookies) {
        Cookie cookie = null;
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) {
                    String[] forms = c.getValue().split(",");
                    StringBuilder value = new StringBuilder();
                    boolean alreadyIncluded = false;
                    for (String form : forms) {
                        if (form.equals(savedForm)) {
                            alreadyIncluded = true;
                        }
                        value.append(",").append(form);
                    }
                    if (!alreadyIncluded) {
                        value.append(",").append(savedForm);
                    }
                    cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1));
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm);
        }
        cookie.setMaxAge(2000000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    HttpServletHelper.getInstance().reloadApplicationMap(request, application);
    HttpServletHelper.getInstance().reloadSessionMap(request, session);
    HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);

    return returnedMv;
}