Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

void removeCookie(String cookieName, HttpServletResponse response) throws UnsupportedEncodingException {
    Cookie cookie = new Cookie(cookieName, URLEncoder.encode("", "UTF-8"));
    cookie.setMaxAge(0);//from  w w w. java  2s  .  c o  m
    response.addCookie(cookie);
}

From source file:csns.web.controller.SectionController.java

@RequestMapping("/section/taught")
public String taught(@RequestParam(required = false) Quarter quarter, ModelMap models, HttpSession session,
        HttpServletResponse response) {//w w  w . j av  a  2 s  . c om
    Cookie cookie = new Cookie("default-home", "/section/taught");
    cookie.setPath("/");
    cookie.setMaxAge(100000000);
    response.addCookie(cookie);

    return list("taught", quarter, models, session);
}

From source file:com.persistent.cloudninja.web.security.CNAuthenticationProcessingFilter.java

/**
 * This method queries the database for the respective member and tries to get the logo url.<br/>
 * if found create the cookie with value as URL returns cookie with empty string
 * /*from w  w w  . j  av a 2s .co m*/
 * 
 * @param memberId
 * @return
 */
private Cookie createLogoCookie(String tenantId) {

    String logoUrl = "";
    // DAO to get the URL
    Tenant tenant = hibernateTemplate.get(Tenant.class, tenantId);
    String logoFilename = tenant.getLogoFileName();
    if (null == logoFilename || logoFilename.trim().length() == 0) {
        // 
        logoUrl = "";
    } else {
        // create logo URL from config property file
        logoUrl = getUrlFromConfig(logoFilename, tenantId);
    }
    Cookie logoCokie = new Cookie("CLOUDNINJALOGO", logoUrl);
    logoCokie.setMaxAge(-1);
    logoCokie.setPath("/");
    return logoCokie;
}

From source file:net.geoprism.data.importer.ExcelController.java

@Override
public void importExcelFile(MultipartFileParameter file, String country, String downloadToken)
        throws IOException, ServletException {
    // The reason we're including a cookie here is because the browser does not give us any indication of when our
    // response from the server is successful and its downloading the file.
    // This "hack" sends a downloadToken to the client, which the client then checks for the existence of every so
    // often. When the cookie exists, it knows its downloading it.
    // http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download

    Cookie cookie = new Cookie("downloadToken", downloadToken);
    cookie.setMaxAge(10 * 60); // 10 minute cookie expiration
    resp.addCookie(cookie);//from   w w  w  . j  a v a  2  s. c  o  m

    try {
        if (file == null) {
            throw new RuntimeException(
                    LocalizationFacadeDTO.getFromBundles(this.getClientRequest(), "file.required"));
        }

        InputStream istream = file.getInputStream();

        try {
            InputStream result = ExcelUtilDTO.importExcelFile(this.getClientRequest(), istream, country);

            if (result != null) {
                // copy it to response's OutputStream
                this.resp.setContentType("application/xlsx");
                this.resp.setHeader("Content-Disposition",
                        "attachment; filename=\"" + file.getFilename() + "\"");

                IOUtils.copy(result, this.resp.getOutputStream());
            } else {
                this.resp.getWriter().print("<p id=\"upload_result\" class=\"success\"></p>");
            }

            this.resp.flushBuffer();
        } finally {
            istream.close();
        }
    } catch (Throwable t) {
        this.resp.getWriter()
                .print("<p id=\"upload_result\" class=\"error\">" + t.getLocalizedMessage() + "</p>");
    }
}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>// w  w  w . j  a v a2s .  c om
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:com.perimeterx.api.PerimeterX.java

/**
 * Verify http request using cookie or PX server call
 *
 * @param req             - current http call examined by PX
 * @param responseWrapper - response wrapper on which we will set the response according to PX verification. {@see javax.xml.ws.ResponseWrapper}
 * @throws PXException//from  w  ww . j  ava 2 s  .  com
 */
public boolean pxVerify(HttpServletRequest req, HttpServletResponseWrapper responseWrapper) throws PXException {
    if (!moduleEnabled()) {
        logger.info("PerimeterX verification SDK is disabled");
        return true;
    }

    // Remove captcha cookie to prevent re-use
    Cookie cookie = new Cookie(Constants.COOKIE_CAPTCHA_KEY, StringUtils.EMPTY);
    cookie.setMaxAge(0);
    responseWrapper.addCookie(cookie);

    PXContext context = new PXContext(req, this.ipProvider, configuration.getAppId());
    if (captchaValidator.verify(context)) {
        return handleVerification(context, responseWrapper, BlockReason.COOKIE);
    }
    S2SCallReason callReason = cookieValidator.verify(context);
    logger.info("Risk API call reason: {}", callReason);
    // Cookie is valid (exists and not expired) so we can block according to it's score
    if (callReason == S2SCallReason.NONE) {
        logger.info("No risk API Call is needed, using cookie");
        return handleVerification(context, responseWrapper, BlockReason.COOKIE);
    }

    context.setS2sCallReason(callReason);
    // Calls risk_api and populate the data retrieved to the context
    RiskRequest request = RiskRequest.fromContext(context);
    RiskResponse response = serverValidator.verify(request);
    context.setScore(response.getScores().getNonHuman());
    context.setUuid(response.getUuid());
    return handleVerification(context, responseWrapper, BlockReason.SERVER);
}

From source file:com.erudika.para.security.CachedCsrfTokenRepository.java

private void storeTokenAsCookie(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    if (isValidButNotInCookie(token, request)) {
        Cookie c = new Cookie(cookieName, token.getToken());
        c.setMaxAge(Config.SESSION_TIMEOUT_SEC.intValue());
        // don't enable HttpOnly - javascript can't access the cookie if enabled
        c.setHttpOnly(false);/* w  ww.j  av  a  2s . co  m*/
        c.setPath("/");
        response.addCookie(c);
    }
}

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

protected String positionCookie(ServletRequest servletRequest, ServletResponse servletResponse, String mlLang,
        String cookieName, boolean content) {
    if (mlLang == null || mlLang.length() == 0) {
        // try to get the cookie and set the content locale prop there
        Cookie[] cookies = ((HttpServletRequest) servletRequest).getCookies();
        Cookie cookie;/*from  www. j a v  a2s. c om*/
        boolean found = false;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                cookie = cookies[i];
                if (cookie.getName().equals(cookieName)) {
                    String lang = cookie.getValue();
                    if (content) {
                        if (lang.length() == 0) {
                            I18NUtil.setContentLocale(null);
                        } else {
                            I18NUtil.setContentLocale(new Locale(lang));
                        }
                        return lang;
                    } else {
                        I18NUtil.setLocale(new Locale(lang));
                        return lang;
                    }

                }
            }
        }
    } else {
        Cookie mlpref = getCookie(servletRequest, cookieName);

        if (mlpref == null) {
            mlpref = new Cookie(cookieName, mlLang);
        } else
            mlpref.setValue(mlLang);
        // Set expiry date after 24 Hrs for both the cookies.
        //mlpref.setMaxAge(60 * 60 * 24);

        ((HttpServletResponse) servletResponse).addCookie(mlpref);
        if (content) {
            I18NUtil.setContentLocale(new Locale(mlLang));
            return mlLang;
        } else {
            I18NUtil.setLocale(new Locale(mlLang));
            return mlLang;
        }
        /*
         * { if(mlLang.equals("reset")) { Cookie mlpref = new
         * Cookie(cookieName, mlLang); // Set expiry date after 24 Hrs for
         * both the cookies. mlpref.setMaxAge(0); mlpref.setValue("");
         * ((HttpServletResponse) servletResponse).addCookie(mlpref); if
         * (content) { I18NUtil.setContentLocale(null); return mlLang; }
         * else { I18NUtil.setLocale(null); return mlLang; } } else
         */

    }

    return mlLang;
}

From source file:com.utest.webservice.impl.v2.UserWebServiceImpl.java

@PUT
@Path("/logout")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Override/*www.  j a v a 2 s  .  co  m*/
public Boolean logout(@Context MessageContext context) throws Exception {
    Integer auth = UserUtil.getCurrentUserId();
    if (auth == null) {
        throw new org.apache.cxf.interceptor.security.AccessDeniedException("No logged in user!");
    }

    final AuthenticatedUserInfo authInfo = (AuthenticatedUserInfo) SecurityContextHolder.getContext()
            .getAuthentication().getPrincipal();
    userService.logout(authInfo, SessionUtil.extractSession(context, false));
    context.getHttpServletResponse().addCookie(new Cookie(SessionUtil.AUTH_TOKEN, null));
    return Boolean.TRUE;
}

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * Store user cookies.//  ww w  . j a  v a2  s . com
 *
 * @param cookies the cookies
 * @param user the user
 */
public static void storeUserCookies(CookieManager cookies, UserManager user) {

    cookies.setCookie(new Cookie(Fields.COOKIE_PATH, user.getWorkspaceId()));

    if (user.getData() != null && user.getData().hasInformation()) {
        UserData userData = user.getData();
        try {
            cookies.setCookie(new Cookie(Fields.COOKIE_USER, userData.toJson()));
        } catch (JsonProcessingException e) {
            LOGGER.error(e, "Cannot store cookies, due to json errors");
        }
    }

}