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:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//from w ww. j a  va 2  s . c o m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.apache.catalina.authenticator.AuthenticatorBase.java

/**
 * Register an authenticated Principal and authentication type in our
 * request, in the current session (if there is one), and with our
 * SingleSignOn valve, if there is one.  Set the appropriate cookie
 * to be returned.//from  w ww  .  ja  v  a 2  s.c o  m
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are generating
 * @param principal The authenticated Principal to be registered
 * @param authType The authentication type to be registered
 * @param username Username used to authenticate (if any)
 * @param password Password used to authenticate (if any)
 */
protected void register(HttpRequest request, HttpResponse response, Principal principal, String authType,
        String username, String password) {

    if (log.isDebugEnabled())
        log.debug("Authenticated '" + principal.getName() + "' with type '" + authType + "'");

    // Cache the authentication information in our request
    request.setAuthType(authType);
    request.setUserPrincipal(principal);

    Session session = getSession(request, false);
    // Cache the authentication information in our session, if any
    if (cache) {
        if (session != null) {
            session.setAuthType(authType);
            session.setPrincipal(principal);
            if (username != null)
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
            else
                session.removeNote(Constants.SESS_USERNAME_NOTE);
            if (password != null)
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
            else
                session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
    }

    // Construct a cookie to be returned to the client
    if (sso == null)
        return;

    // Only create a new SSO entry if the SSO did not already set a note
    // for an existing entry (as it would do with subsequent requests
    // for DIGEST and SSL authenticated contexts)
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (ssoId == null) {
        // Construct a cookie to be returned to the client
        HttpServletResponse hres = (HttpServletResponse) response.getResponse();
        ssoId = generateSessionId();
        Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, ssoId);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        hres.addCookie(cookie);

        // Register this principal with our SSO valve
        sso.register(ssoId, principal, authType, username, password);
        request.setNote(Constants.REQ_SSOID_NOTE, ssoId);

    } else {
        // Update the SSO session with the latest authentication data
        sso.update(ssoId, principal, authType, username, password);
    }

    // Fix for Bug 10040
    // Always associate a session with a new SSO reqistration.
    // SSO entries are only removed from the SSO registry map when
    // associated sessions are destroyed; if a new SSO entry is created
    // above for this request and the user never revisits the context, the
    // SSO entry will never be cleared if we don't associate the session
    if (session == null)
        session = getSession(request, true);
    sso.associate(ssoId, session);

}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request,
        HttpServletResponse response) {//from w  w w.  j a va2s . co m
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), "LOGGED_OUT");
    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
    sharedSession.invalidate();

}

From source file:com.jfinal.core.Controller.java

/**
 * Set Cookie to response./*from  www  . j  a  v  a 2  s. c om*/
 * @param name cookie name
 * @param value cookie value
 * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately.  n>0 : max age in n seconds.
 * @param path see Cookie.setPath(String)
 * @param domain the domain name within which this cookie is visible; form is according to RFC 2109
 */
public Controller setCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
    Cookie cookie = new Cookie(name, value);
    if (domain != null)
        cookie.setDomain(domain);
    cookie.setMaxAge(maxAgeInSeconds);
    cookie.setPath(path);
    response.addCookie(cookie);
    return this;
}

From source file:org.syncope.console.commons.PreferenceManager.java

public void set(final Request request, final Response response, final Map<String, List<String>> prefs) {

    Cookie prefCookie = ((WebRequest) request).getCookie(Constants.PREFS_COOKIE_NAME);

    final Map<String, String> current = new HashMap<String, String>();

    if (prefCookie == null || !StringUtils.hasText(prefCookie.getValue())) {
        prefCookie = new Cookie(Constants.PREFS_COOKIE_NAME, null);
    } else {//w  w w .j  a  v  a  2s .  co  m
        current.putAll(getPrefs(new String(Base64.decodeBase64(prefCookie.getValue().getBytes()))));
    }

    // after retrieved previous setting in order to overwrite the key ...
    for (Entry<String, List<String>> entry : prefs.entrySet()) {
        current.put(entry.getKey(), StringUtils.collectionToDelimitedString(entry.getValue(), ";"));
    }

    try {
        prefCookie.setValue(new String(Base64.encodeBase64(setPrefs(current).getBytes())));
    } catch (IOException e) {
        LOG.error("Could not set preferences " + current, e);
    }

    prefCookie.setMaxAge(ONE_YEAR_TIME);
    ((WebResponse) response).addCookie(prefCookie);
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void removeSessionCookie(String cookieName, HttpServletResponse response) {
    Validate.notNull(response);//from w w  w.  j av  a2  s. com
    if (cookieName == null || cookieName.isEmpty()) {
        log.warn("Cookie name is null or empty. Ignoring.");
        return;
    }
    log.debug("Removing cookie " + cookieName);
    Cookie sessionCookie = new Cookie(cookieName, "");
    sessionCookie.setPath("/");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;//from w ww  .  jav  a 2s . c  om
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java

/**
 * This method simulates the authentication process against a content 
 * source, so that every document is consider here as public.
 * <p>/*from  w  ww . j av  a 2  s . c o m*/
 * Creates the authentication cookie and always return 200, unless there is 
 * any problem processing the request.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP No authentication start");

    //
    // Launch the authentication process
    //

    // Protection
    try {

        Cookie extAuthCookie = null;
        extAuthCookie = new Cookie("gsa_basic_noauth", "");

        extAuthCookie.setValue("true");

        String authCookieDomain = null;
        String authCookiePath = null;
        int authMaxAge = -1;

        // Cache cookie properties
        authCookieDomain = (request.getAttribute("authCookieDomain")).toString();
        authCookiePath = (request.getAttribute("authCookiePath")).toString();
        //authMaxAge
        try {
            authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
        } catch (NumberFormatException nfe) {
            logger.error(
                    "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
        }

        // Set extra cookie parameters
        extAuthCookie.setDomain(authCookieDomain);
        extAuthCookie.setPath(authCookiePath);
        extAuthCookie.setMaxAge(authMaxAge);

        // Log info
        if (logger.isDebugEnabled())
            logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":"
                    + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain()
                    + ":" + extAuthCookie.getSecure());

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP No Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

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");
    }/*from www  .  j a  v a  2 s  .  c  om*/
    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:ELK.ELKController.java

private void initializeRoutes() throws IOException {
    // this is the blog home page
    get(new FreemarkerBasedRoute("/", "ELKTemplate.ftl") {
        @Override//from  w ww  .  java2  s.  com
        public void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

            // this is where we would normally load up the blog data
            // but this week, we just display a placeholder.
            HashMap<String, String> root = new HashMap<String, String>();

            template.process(root, writer);
        }
    });
    /*
            get(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
        ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
            
        SimpleHash root = new SimpleHash();
        System.out.println("We are good");
        BasicDBObject query = new BasicDBObject();
        VMsDBCollection.deleteMany(query);
            
        //HashMap<String, String> root = new HashMap<String, String>();
        if(!(mes == null || mes.length == 0)) {
            for (int i = 0; i < mes.length; i++) {
                Document text = new Document();
                VirtualMachine vm = (VirtualMachine) mes[i];
            
                if(!vm.getName().contains("Template")) {
                    String name = vm.getName();
                    text.append("name", name);
                    Document DB_VMs = new Document("_id", name);
            
                    if(vm.getConfig() != null) {
                        String instanceId = vm.getConfig().getInstanceUuid();
                        text.append("instanceId", instanceId);
                    }
            
                    System.out.println("VM Name : " + name);
            
                    String conectionState = vm.getRuntime().getConnectionState().toString();
                    text.append("conectionState", conectionState);
                    DB_VMs.append("conectionState", conectionState);
            
                    String ip = vm.getGuest().getIpAddress();
                    text.append("ip", ip);
                    DB_VMs.append("ip", ip);
            
                    String powerState = vm.getRuntime().getPowerState().toString();
                    text.append("powerState", powerState);
            
                    if (vm.getTriggeredAlarmState() == null) {
                        text.append("alarmState", "notTriggered");
                        DB_VMs.append("powerState", "notTriggered");
                    } else {
                        text.append("alarmState", "Triggered");
                        DB_VMs.append("powerState", "Triggered");
                    }
            
                    String launchTime = writeActualDate(vm.getRuntime().getBootTime());
                    text.append("launchTime", launchTime);
                    DB_VMs.append("launchTime", launchTime);
            
                    posts.add(text);
                    VMsDBCollection.insertOne(DB_VMs);
            
                }
            }
        }
        root.put("VMs", posts);
        template.process(root, writer);
    }
            });*/
    /*
            get(new FreemarkerBasedRoute("/create_vm", "create_vm.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        SimpleHash root = new SimpleHash();
        System.out.println("Inside Create VM backend");
            
        template.process(root, writer);
    }
            });*/
    /*
            post(new FreemarkerBasedRoute("/create_vm", "/create_vm.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            
        if (request.queryParams("Create") != null) {
            
            ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
            
            
            //Clone VM
            String vmname = request.queryParams("vmname");
            String vm_template = request.queryParams("OS");
            
            VirtualMachine vm = (VirtualMachine) new InventoryNavigator(
                    rootFolder).searchManagedEntity("VirtualMachine", vm_template);
            
            VirtualMachineRuntimeInfo vmri = vm.getRuntime();
            
            HostSystem hs = new HostSystem(vm.getServerConnection(), vmri.getHost());
            
            Datacenter dc = (Datacenter) new InventoryNavigator(rootFolder).searchManagedEntity("Datacenter", "T03-DC");
            ResourcePool rp = (ResourcePool) new InventoryNavigator(dc).searchManagedEntities("ResourcePool")[0];
            
            if (vm == null) {
                System.out.println("No VM found with name " + vm_template);
            
                SimpleHash root = new SimpleHash();
            
                root.put("login_error", "No template available");
                template.process(root, writer);
            } else {
                try {
                    VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
            
                    VirtualMachineRelocateSpec locateSpec = new VirtualMachineRelocateSpec();
                    locateSpec.setPool(rp.getMOR());
                    cloneSpec.setLocation(locateSpec);
                    cloneSpec.setPowerOn(false);
                    cloneSpec.setTemplate(false);
            
                    Task task = vm.cloneVM_Task((Folder) vm.getParent(),
                            vm_template, cloneSpec);
                    System.out.println("Launching the VM clone task. " + "Please wait ...");
                    String status = task.waitForTask();
                    if (status == Task.SUCCESS) {
                        System.out.println("VM got cloned successfully.");
                    } else {
                        System.out.println("Failure -: VM cannot be cloned");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            
                response.redirect("/display_vms");
            }
        } else if (request.queryParams("Cancle") != null) {
            
            response.redirect("/display_vms");
            
        }
    }
            });
    */

    /*
            post(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10);
        SimpleHash root = new SimpleHash();
            
        BasicDBObject query = new BasicDBObject();
        ArrayList<String> VM_list = new ArrayList<String>();
        MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator();
            
        while (cursor.hasNext()) {
            
            String a = cursor.next().toJson();
            System.out.println(a);
            
            try {
                JSONObject jsonObject = new JSONObject(a);
                String vm_name = jsonObject.getString("_id");
                VM_list.add(vm_name);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
        }
            
        //take VM list from DB
        if (request.queryParams("PowerOn") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Power ON VM " + VM_name);
                    powerOn(VM_name);
                }
            
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("PowerOff") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Power Off VM " + VM_name);
                    powerOff(VM_name);
                }
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("Delete") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox)
                    System.out.println("Delete VM "+ VM_name);
                deleteVM(VM_name);
            }
            response.redirect("/display_vms");
            
        } else if (request.queryParams("Get_Chart") != null) {
            Iterator vm_iterator = VM_list.iterator();
            while(vm_iterator.hasNext()) {
                String VM_name = vm_iterator.next().toString();
                boolean myCheckBox = request.queryParams(VM_name) != null;
                if (myCheckBox) {
                    System.out.println("Get VM " + VM_name +"Charts" );
                    CurrentSelectedVM = VM_name;
                }
            }
            response.redirect("/gChart");
            
        } else if (request.queryParams("Create") != null) {
            response.redirect("/create_vm");
            
        }else {
            System.out.println("Invalid ");
            response.redirect("/display_vms");
            // ???
        }
            
    }
            });
    */
    /*      // google chart handler
          get(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") {
    @Override
    public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            
        if (CurrentSelectedVM != null) {
            
            ArrayList<ArrayList> gchartData = statsDAO.getGchart(CurrentSelectedVM);
            SimpleHash root = new SimpleHash();
            root.put("VMName", CurrentSelectedVM);
            CurrentSelectedVM = null;
            
            root.put("gcdata", gchartData);
            //System.out.println(gchartData);
            // System.out.println(gchartData.get(0));
            
            template.process(root, writer);
        }
            
    }
          });*/

    /*       post(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") {
    @Override
    protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            
        if (request.queryParams("Home") != null) {
            response.redirect("/display_vms");
        }
    }
           });
    */

    // handle the signup post
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/login");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for blog
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("welcome() can't identify the user, redirecting to signup");
                response.redirect("/signup");

            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", username);

                template.process(root, writer);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the welcome page
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/ConfigureAlarm");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // allows the user to logout of the blog
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);

            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
    get(new FreemarkerBasedRoute("/ConfigureAlarm", "ConfigureAlarmForm.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });

}