Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *///from  w ww.  ja  v  a2s . c  o m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.liferay.portal.action.LogoutAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {

    try {/*from w w w  .j a  va2s . c  om*/
        HttpSession ses = req.getSession();
        try {
            // Logger.info(this, "User " +
            // PortalUtil.getUser(req).getFullName() + " (" +
            // PortalUtil.getUser(req).getUserId() +
            // ") has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User " + PortalUtil.getUser(req).getFullName() + " ("
                    + PortalUtil.getUser(req).getUserId() + ") has logged out from IP: " + req.getRemoteAddr());
        } catch (Exception e) {
            //Logger.info(this, "User has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User has logged out from IP: " + req.getRemoteAddr());
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_PRE), req, res);

        ArrayList<Cookie> al = new ArrayList<Cookie>();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                al.add(cookie);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                res.addCookie(cookie);
            }
        }

        Map sessions = PortletSessionPool.remove(ses.getId());

        if (sessions != null) {
            Iterator itr = sessions.entrySet().iterator();

            while (itr.hasNext()) {
                Map.Entry entry = (Map.Entry) itr.next();

                HttpSession portletSession = (HttpSession) entry.getValue();

                portletSession.invalidate();
            }
        }

        try {
            ses.invalidate();
        } catch (Exception e) {
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_POST), req, res);

        // ActionForward af = mapping.findForward("referer");
        // return af;
        return mapping.findForward(Constants.COMMON_REFERER);
    } catch (Exception e) {
        req.setAttribute(PageContext.EXCEPTION, e);
        return mapping.findForward(Constants.COMMON_REFERER);
    }
}

From source file:com.sjc.cc.login.action.LoginAction.java

/**
 * /*  w w w  .j  a v  a  2 s .c  om*/
 * 
 * @return
 * @exception Exception can be thrown by subclasses.
 */
public String logout() throws Exception {
    LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
    if (loginUserInfo != null && loginUserInfo.getEmpName() != null) {
        logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + ""
                + BusinessEnvironment.OPER_RESULT_SUCCESS, loginUserInfo, 3);
    }
    sessionUserAccessor.logoutUser(ServletActionContext.getRequest().getSession());
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Cookiecookies[" + i + "].getName()==========[" + cookies[i].getName() + "]");
            }
            if (LoginAction.COOKIE_CC_USER_ID.equals(cookies[i].getName())) {
                cookies[i].setMaxAge(0);
                response.addCookie(cookies[i]);// cookie
                break;
            }
        }
    }
    TccSkin tCcSkin = loginService.getSkindflt();
    if (null != tCcSkin) {
        String dirString = tCcSkin.getSkinDir();
        if (null == dirString || dirString.equals("")) {
            dirString = "";
        }
        request.getSession().setAttribute("changeskin", dirString);
    } else {
        request.getSession().setAttribute("changeskin", "");
    }
    TCcBasicCfg basicCfg = loginService.getBasicCfg();
    request.getSession().setAttribute("basicCfg", basicCfg);
    return "logout";
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }//  w  ww.  j  a v  a2  s .  c  o m
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}

From source file:cn.tiup.httpproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *//*  w  w w.j a  va 2  s . c om*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(cookie.getPath()); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

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();
        }// w ww  .  j a  v a2  s .c  om
        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);
}

From source file:nl.strohalm.cyclos.controls.access.ExternalLoginAction.java

@Override
public void prepareForm(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) {

    // Resolve the translation messages for each status
    final Map<String, String> statusMessages = new HashMap<String, String>();
    for (final Status status : Status.values()) {
        final String key = status.getKey();
        if (key != null) {
            String argument = status.getArgument();
            if (argument != null) {
                // The argument is actually a key to another message
                argument = messageHelper.message(argument);
            }//from  w w  w . j  a  va  2 s.c o  m
            statusMessages.put(status.name(), messageHelper.message(key, argument));
        }
    }
    request.setAttribute("statusMessages", statusMessages);

    // Store a cookie in order to know where to go after logout
    String afterLogout = request.getParameter("afterLogout");
    afterLogout = StringUtils.trimToEmpty(afterLogout);
    try {
        final LocalSettings settings = settingsService.getLocalSettings();
        afterLogout = URLEncoder.encode(StringUtils.trimToEmpty(afterLogout), settings.getCharset());
    } catch (final UnsupportedEncodingException e) {
    }
    final Cookie cookie = new Cookie("afterLogout", afterLogout);
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
}

From source file:com.salesmanager.catalog.CatalogInterceptor.java

@Override
protected String doIntercept(ActionInvocation invoke, HttpServletRequest req, HttpServletResponse resp)
        throws Exception {

    /** remove profile url **/
    req.getSession().removeAttribute("profileUrl");

    /** synchronize mini shopping cart**/

    //get http session shopping cart
    ShoppingCart cart = SessionUtil.getMiniShoppingCart(req);
    MerchantStore mStore = SessionUtil.getMerchantStore(req);

    if (cart == null) {//synch only when the cart is null or empty

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(CatalogConstants.SKU_COOKIE + mStore.getMerchantId())) {

                    Locale locale = LocaleUtil.getLocale(req);

                    String cookieValue = StringUtil.unescape(cookie.getValue());

                    ShoppingCart sc = MiniShoppingCartSerializationUtil.deserializeJSON(cookieValue, mStore,
                            locale);/*w ww  .java2 s  . co  m*/
                    if (sc != null) {

                        MiniShoppingCartUtil.calculateTotal(sc, mStore);
                        SessionUtil.setMiniShoppingCart(sc, req);

                    } else {//expire cookie
                        cookie.setValue(null);
                        cookie.setMaxAge(0);
                        resp.addCookie(cookie);
                    }
                }
            }
        }

    }

    return null;

}

From source file:com.haulmont.idp.controllers.IdpController.java

@GetMapping(value = "/logout")
public String logout(@RequestParam(value = "sp", defaultValue = "") String serviceProviderUrl,
        @RequestParam(value = "response_type", defaultValue = "server-ticket") String responseType,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;/*from  ww w .  j av  a 2 s.c om*/
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    // remove auth cookie
    Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);

    if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
        return "redirect:login.html" + "?response_type=" + ResponseType.CLIENT_TICKET.getCode() + "&sp="
                + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
    }

    return "redirect:login.html?sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 *  Check if the session cookie is set and valid for this request.
 *  If not, create a new one.//from   w w w . j  ava2 s  . co m
 */
private void checkSessionCookie(HttpServletRequest request, HttpServletResponse response, RequestTrans reqtrans,
        String domain) {
    // check if we need to create a session id.
    if (protectedSessionCookie) {
        // If protected session cookies are enabled we also force a new session
        // if the existing session id doesn't match the client's ip address
        StringBuffer b = new StringBuffer();
        if (reqtrans.getSession() == null || !reqtrans.getSession().startsWith(b.toString())) {
            response.addCookie(createSessionCookie(b, reqtrans, domain));
        }
    } else if (reqtrans.getSession() == null) {
        response.addCookie(createSessionCookie(new StringBuffer(), reqtrans, domain));
    }
}