Example usage for javax.servlet.http Cookie setMaxAge

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

Introduction

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

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

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);
    response.addCookie(cookie);/*from  w  w w.j  av a2 s  .  c  o m*/
}

From source file:com.mawujun.util.web.CookieGenerator.java

/**
 * Add a cookie with the given value to the response,
 * using the cookie descriptor settings of this generator.
 * <p>Delegates to <code>createCookie</code> for cookie creation.
 * @param response the HTTP response to add the cookie to
 * @param cookieValue the value of the cookie to add
 * @see #setCookieName/*from w w w  .j  ava  2 s  . co m*/
 * @see #setCookieDomain
 * @see #setCookiePath
 * @see #setCookieMaxAge
 * @see #createCookie
 */
public void addCookie(HttpServletResponse response, String cookieValue) {
    Cookie cookie = createCookie(cookieValue);
    cookie.setMaxAge(getCookieMaxAge());
    if (isCookieSecure()) {
        cookie.setSecure(true);
    }
    response.addCookie(cookie);
    if (logger.isDebugEnabled()) {
        logger.debug("Added cookie with name [" + getCookieName() + "] and value [" + cookieValue + "]");
    }
}

From source file:com.wavemaker.spinup.web.SpinupController.java

/**
 * Postback method from the login form. Will either re-direct back to the form (in the case of errors) or redirect
 * to start the spinup process./*from ww  w .  j  a va 2 s .co  m*/
 * 
 * @param credentials User credentials
 * @param bindingResult the binding result from the form
 * @param request the HTTP request
 * @param response the HTTP response
 * @return the response (either a redirect to the form or a redirect to the spinup process)
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView processLogin(@Valid LoginCredentialsBean credentials, BindingResult bindingResult,
        HttpServletRequest request, HttpServletResponse response) {

    Assert.state(isAjaxRequest(request), "Unable to handle non AJAX post");

    // If we have binding errors, re-render the page
    if (bindingResult.hasErrors()) {
        return new ModelAndView();
    }

    try {
        // Login, add the cookie and redirect to start the spinup process
        this.logger.debug("Starting WaveMaker spinup");
        SharedSecret secret = getSecret(request);
        TransportToken transportToken = this.spinupService.login(secret, credentials);
        this.logger.debug("Login complete");
        String url = performSpinup(credentials, secret, transportToken, response);
        this.logger.debug("Perform spinup complete");
        Cookie cookie = new Cookie(COOKIE_NAME, transportToken.encode());
        cookie.setMaxAge(COOKIE_MAX_AGE);
        cookie.setDomain(this.spinupService.getDomain());
        response.addCookie(cookie);
        response.setHeader("X-Ajax-Redirect", url);
        response.setStatus(HttpStatus.NO_CONTENT.value());
        this.logger.debug("Wavemake spinup complete");
        return null;
    } catch (InvalidLoginCredentialsException e) {
        // On invalid login redirect with a message in flash scope
        return new ModelAndView().addObject("message", "Unable to login, please check your credentials");
    }

}

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);/*www  . java 2s  .  c  om*/

    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:io.syndesis.rest.v1.handler.connection.ConnectionHandler.java

@Override
public Connection create(@Context SecurityContext sec,
        @ConvertGroup(from = Default.class, to = AllValidations.class) final Connection connection) {
    final Date rightNow = new Date();
    final Connection updatedConnection = new Connection.Builder().createFrom(connection).createdDate(rightNow)
            .lastUpdated(rightNow).userId(sec.getUserPrincipal().getName()).build();

    final Set<CredentialFlowState> flowStates = CredentialFlowState.Builder.restoreFrom(state::restoreFrom,
            request);//from w w w . j av a 2s  .  c o m

    final Connection connectionToCreate = flowStates.stream().map(s -> {
        final Cookie removal = new Cookie(s.persistenceKey(), "");
        removal.setPath("/");
        removal.setMaxAge(0);

        response.addCookie(removal);

        return credentials.apply(updatedConnection, s);
    }).findFirst().orElse(updatedConnection);

    return Creator.super.create(sec, connectionToCreate);
}

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

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

    try {//from  ww w.  j  a v a2s. c  o m
        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.ms.commons.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response//from  w w w.j  a  va  2s  .  c  om
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = CookieUtils.encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

From source file:com.mmj.app.common.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response// w w w.j av a  2 s .  c  o  m
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = EncryptBuilder.getInstance().encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

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
 * /*w w  w  . ja  v  a2 s.  c o 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:com.junly.service.helper.TicketHelper.java

/** <p class="detail">
* ?cookie//from   www .  j av a 2s.c  om
* </p>
* @author junly
* @date 2016420 
* @param response
* @param cookie    
*/
public void deleteCookie(HttpServletResponse response, Cookie cookie) {
    if (cookie != null) {
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}