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:org.apache.hadoop.test.mock.MockResponseProvider.java

public void apply(HttpServletResponse response) throws IOException {
    if (statusCode != null) {
        response.setStatus(statusCode);/*from  w  ww  .j  av a2  s  .  c o  m*/
    }
    if (errorCode != null) {
        if (errorMsg != null) {
            response.sendError(errorCode, errorMsg);
        } else {
            response.sendError(errorCode);
        }
    }
    if (redirectUrl != null) {
        response.sendRedirect(redirectUrl);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            response.addHeader(name, headers.get(name));
        }
    }
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            response.addCookie(cookie);
        }
    }
    if (locale != null) {
        response.setLocale(locale);
    }
    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (characterEncoding != null) {
        response.setCharacterEncoding(characterEncoding);
    }
    if (contentLength != null) {
        response.setContentLength(contentLength);
    }
    if (entity != null) {
        response.getOutputStream().write(entity);
        response.getOutputStream().close();
    }
}

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

/**
 * @param response/*from w  ww.  ja v  a 2 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:net.prasenjit.auth.config.CustomAjaxAwareHandler.java

/** {@inheritDoc} */
@Override/*  w  w  w  .jav  a  2  s  .c  om*/
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    request.setAttribute("javax.servlet.error.status_code", HttpServletResponse.SC_FORBIDDEN);
    request.setAttribute("org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.ERROR",
            accessDeniedException);
    if (accessDeniedException instanceof CsrfException && !response.isCommitted()) {
        // Remove the session cookie so that client knows it's time to obtain a new CSRF token
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, "");
        cookie.setMaxAge(0);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    delegatedAccessDeniedHandler.handle(request, response, accessDeniedException);
}

From source file:com.netpace.vzdn.webapp.vzdninterceptors.SecurityInterceptor.java

public String getUserNameFromCookie(HttpServletRequest request, HttpServletResponse response) {

    try {/*from  ww w.  j a v  a  2  s . c  om*/
        SSOTokenManager stm = SSOTokenManager.getInstance();
        Cookie[] requestCookies = request.getCookies();
        String userName = "";
        for (int i = 0; i < requestCookies.length; i++) {
            Cookie cookie = requestCookies[i];
            if (cookie.getName().equals(VzdnConstants.OPENSSO_COOKIE)) {
                SSOToken st = stm.createSSOToken(request);
                userName = st.getPrincipal().getName();
                userName = userName.substring(userName.indexOf("=") + 1, userName.indexOf(",")).toLowerCase();
                System.out.println("got the cookie user name : " + userName);
                Cookie ssoCookie = new Cookie("loggedInUserInfo", userName);
                response.addCookie(ssoCookie);
                break;
            }
        }
        return userName;
    } catch (Exception ex) {
        log.error("Some issue in SecurityInterceptor while reading user info from cookie" + ex.getMessage());
        ex.printStackTrace();
        return null;
    }
}

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

/**
 * List Tenant Tasks.// www .j a va  2s. co  m
 * @param cookie used to retrieve Tenant ID
 * @return MadelAndView mapped to tenantHomePage view
 * @throws CloudNinjaException
 */

@RequestMapping(value = "{tenantId}/showTenantHomePage.htm")
public ModelAndView showTenantHomePage(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) throws CloudNinjaException {

    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }
    String tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
            cookie);
    if (null == rsBundle) {
        rsBundle = ResourceBundle.getBundle("storageAcc");
    }
    response.addCookie(getTenantLogoCookieInResponse(tenantId, cookie));

    ModelAndView model = new ModelAndView(
            new RedirectView("/" + tenantId + "/showTenantHomePageList.htm", true));
    return model;
}

From source file:com.qut.middleware.esoe.sso.plugins.post.handler.impl.PostLogicImpl.java

private void sendPostResponseDocument(SSOProcessorData data) throws PostBindingException {
    String remoteAddress = data.getHttpRequest().getRemoteAddr();
    try {/*from   w w w  .jav  a2  s . c om*/
        HttpServletResponse response = data.getHttpResponse();
        PrintWriter writer = response.getWriter();

        response.setContentType("text/html");

        /* Set cookie to allow javascript enabled browsers to auto submit, ensures navigation with the back button is not broken
         * because auto submit is active only when this cookie exists, and the submit javascript removes it */
        Cookie autoSubmit = new Cookie("esoeAutoSubmit", "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);

        this.logger.debug("[SSO for {}] Cookie added. About to check for response document.", remoteAddress); //$NON-NLS-1$

        if (data.getResponseDocument() == null) {
            this.logger.error(
                    "[SSO for {}] No response document was generated. Unable to respond to HTTP-POST binding request.", //$NON-NLS-1$
                    remoteAddress);
            throw new PostBindingException(
                    "No response document was generated. Unable to respond to HTTP-POST binding request.");
        }

        // TODO relaystate
        String responseRelayState = "";// = data.getRelayState();
        if (responseRelayState == null)
            responseRelayState = new String("");

        /* Encode SAML Response in base64 */
        byte[] samlResponseEncoded = Base64.encodeBase64(data.getResponseDocument()); //$NON-NLS-1$
        Object[] responseArgs = new Object[] { data.getResponseEndpoint(), new String(samlResponseEncoded),
                responseRelayState };
        String htmlOutput = this.samlMessageFormat.format(responseArgs);

        this.logger.debug(
                "[SSO for {}] Writing HTML document, response for HTTP-POST request. Length: {} bytes",
                remoteAddress, htmlOutput.length());

        this.logger.trace("[SSO for {}] Writing HTML document. Content:\n{}", remoteAddress, htmlOutput);

        writer.print(htmlOutput);
        writer.flush();
    } catch (IOException e) {
        this.logger.error(
                "[SSO for {}] I/O exception occurred trying to write the HTTP response. Unable to respond with HTTP-POST binding. Error was: {}",
                remoteAddress, e.getMessage());
        throw new PostBindingException(
                "I/O exception occurred trying to write the HTTP response. Unable to respond with HTTP-POST binding.",
                e);
    }
}

From source file:com.pureinfo.tgirls.sns.servlet.SNSEntryServlet.java

private void addCookie(User _loginUser, HttpServletRequest _request, HttpServletResponse _response)
        throws UnsupportedEncodingException {
    Cookie name = new Cookie(CookieUtils.NAME, URLEncoder.encode(_loginUser.getName(), "utf-8"));
    Cookie nickName = new Cookie(CookieUtils.NICK_NAME, URLEncoder.encode(_loginUser.getNickname(), "utf-8"));
    Cookie taobaoId = new Cookie(CookieUtils.TAOBAO_ID, URLEncoder.encode(_loginUser.getTaobaoID(), "utf-8"));
    Cookie img = new Cookie(CookieUtils.HEAD_IMG, URLEncoder.encode(_loginUser.getHeadImg(), "utf-8"));
    Cookie topsession = new Cookie(CookieUtils.TOP_SESSION_ID,
            _request.getParameter(APPConstants.REQ_PARAMETER_SESSION));

    _response.addCookie(name);
    _response.addCookie(nickName);/* w w  w.  ja  va  2s.co m*/
    _response.addCookie(taobaoId);
    _response.addCookie(img);
    _response.addCookie(topsession);

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.OAuthAction.java

/** ACTIONS **/
// http://localhost:8080/ciapl/external/oauth/userdialog&client_id=123123&redirect_uri=http://www.google.com

public ActionForward getUserPermission(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String clientId = request.getParameter("client_id");
    String redirectUrl = request.getParameter("redirect_uri");
    Person person = getLoggedPerson(request);

    if (!StringUtils.isEmpty(clientId) && !StringUtils.isEmpty(redirectUrl)) {
        if (person == null) {
            //redirect person to this action with client id in session

            final String cookieValue = clientId + "|" + redirectUrl;
            response.addCookie(
                    new Cookie(OAUTH_SESSION_KEY, Base64.getEncoder().encodeToString(cookieValue.getBytes())));
            if (CoreConfiguration.casConfig().isCasEnabled()) {
                response.sendRedirect(CoreConfiguration.casConfig().getCasLoginUrl(
                        CoreConfiguration.getConfiguration().applicationUrl() + "/oauth/userdialog"));
            } else {
                response.sendRedirect(request.getContextPath() + "/oauth/userdialog");
            }//from   w  w  w.java2  s  .  c  o  m
            return null;
        } else {
            return redirectToRedirectUrl(mapping, request, response, person, clientId, redirectUrl);
        }
    } else {
        if (person != null) {
            // this is the request that will recover client id from session
            final Cookie cookie = CookieReaderUtils.getCookieForName(OAUTH_SESSION_KEY, request);
            if (cookie == null) {
                logger.debug("Cookie can't be null because this a direct request from this action with cookie");
                return mapping.findForward("oauthErrorPage");
            }
            final String sessionClientId = cookie.getValue();
            if (!StringUtils.isEmpty(sessionClientId)) {
                return redirectToRedirectUrl(mapping, request, response, person, cookie);
            }
        } else {
            logger.debug("Person should not be null since this a redirect from this action with cookie");
        }
    }

    return mapping.findForward("oauthErrorPage");

}

From source file:edu.ucmerced.cas.web.support.CasShibCookieRetrievingCookieGenerator.java

public void addCookie(final HttpServletRequest request, final HttpServletResponse response,
        final String cookieValue) {
    // instantiate a new CookieGenerator upon every request because the
    // cookie name and path are possibly going to be different for each
    // request/*from  ww  w  .j  a va 2 s. c o  m*/
    LocalCookieGenerator cookieGenerator = newCookieGeneratorInstance(request);

    if (!StringUtils.hasText(request.getParameter(RememberMeCredentials.REQUEST_PARAMETER_REMEMBER_ME))) {
        cookieGenerator.addCookie(response, cookieValue);
    } else {
        final Cookie cookie = cookieGenerator.createCookie(cookieValue);
        cookie.setMaxAge(this.rememberMeMaxAge);
        if (cookieGenerator.isCookieSecure()) {
            cookie.setSecure(true);
        }
        response.addCookie(cookie);
    }
}

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

/**
 * Method added to generate simulated data for bytes sent and received
 * @return String : Random generated String
 *//*from  ww w  . ja v  a  2 s . c  o m*/
@RequestMapping(value = "/showTrafficSimulationPage.htm")
public ModelAndView showTrafficsimulation(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) {

    int START_INDEX = 2;
    int END_INDEX = 100;
    TrafficSimulationDTO trafficSimulationDTO = new TrafficSimulationDTO();

    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }

    String tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
            cookie);
    response.addCookie(getTenantLogoCookieInResponse(tenantId, cookie));

    Random randomGen = new Random();
    int randomNum = randomGen.nextInt(END_INDEX - START_INDEX + 1) + START_INDEX;

    StringBuilder strbldr = new StringBuilder();
    for (int i = 0; i < randomNum; i++) {
        strbldr.append(Character.toChars((int) (Math.floor(26 * randomGen.nextDouble()) + 65)));
    }

    trafficSimulationDTO.setTenantId(tenantId);
    trafficSimulationDTO.setRandomString(strbldr.toString());
    return new ModelAndView("trafficSimulation", "trafficSimulationDTO", trafficSimulationDTO);

}