Example usage for javax.servlet.http Cookie getPath

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

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Returns the path on the server to which the browser returns this cookie.

Usage

From source file:org.piraso.web.base.WebEntryUtils.java

public static CookieEntry toEntry(Cookie cookie) {
    CookieEntry entry = new CookieEntry();

    entry.setName(cookie.getName());//  w w  w . ja  va  2s .co m
    entry.setValue(cookie.getValue());
    entry.setComment(cookie.getComment());
    entry.setDomain(cookie.getDomain());
    entry.setMaxAge(cookie.getMaxAge());
    entry.setPath(cookie.getPath());
    entry.setSecure(cookie.getSecure());
    entry.setVersion(cookie.getVersion());

    return entry;
}

From source file:org.projectforge.business.user.filter.UserFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (log.isDebugEnabled() == true) {
        log.debug("doFilter " + request.getRequestURI() + ": " + request.getSession().getId());
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                log.debug("Cookie " + cookie.getName() + ", path=" + cookie.getPath() + ", value="
                        + cookie.getValue() + ", secure=" + cookie.getVersion() + ", maxAge="
                        + cookie.getMaxAge() + ", domain=" + cookie.getDomain());
            }/*from   ww  w  .j  a va  2  s  . c o  m*/
        }
    }
    final HttpServletResponse response = (HttpServletResponse) resp;
    UserContext userContext = null;
    try {
        MDC.put("ip", (Object) request.getRemoteAddr());
        MDC.put("session", (Object) request.getSession().getId());
        if (ignoreFilterFor(request) == true) {
            // Ignore the filter for this request:
            if (log.isDebugEnabled() == true) {
                log.debug("Ignore: " + request.getRequestURI());
            }
            chain.doFilter(request, response);
        } else {
            // final boolean sessionTimeout = request.isRequestedSessionIdValid() == false;
            userContext = (UserContext) request.getSession().getAttribute(SESSION_KEY_USER);
            if (userContext != null) {
                if (updateRequiredFirst == false) {
                    // Get the fresh user from the user cache (not in maintenance mode because user group cache is perhaps not initialized correctly
                    // if updates of e. g. the user table are necessary.
                    userContext.refreshUser();
                }
                if (log.isDebugEnabled() == true) {
                    log.debug("User found in session: " + request.getRequestURI());
                }
            } else if (updateRequiredFirst == false) {
                // Ignore stay-logged-in if redirect to update page is required.
                userContext = checkStayLoggedIn(request, response);
                if (userContext != null) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("User's stay logged-in cookie found: " + request.getRequestURI());
                    }
                    userContext.setStayLoggedIn(true); // Used by MenuMobilePage.
                    UserFilter.login(request, userContext);
                }
            }
            final PFUserDO user = userContext != null ? userContext.getUser() : null;
            if (user != null) {
                MDC.put("user", (Object) user.getUsername());
                ThreadLocalUserContext.setUserContext(userContext);
                request = decorateWithLocale(request);
                chain.doFilter(request, response);
            } else {
                if (((HttpServletRequest) req).getRequestURI().startsWith(WICKET_PAGES_PREFIX) == true) {
                    // Access-checking is done by Wicket, not by this filter:
                    request = decorateWithLocale(request);
                    chain.doFilter(request, response);
                } else {
                    response.getWriter().append("No access.");
                }
            }
        }
    } finally {
        ThreadLocalUserContext.clear();
        MDC.remove("ip");
        MDC.remove("session");
        final PFUserDO user = userContext != null ? userContext.getUser() : null;
        if (user != null) {
            MDC.remove("user");
        }
        if (log.isDebugEnabled() == true) {
            StringBuffer sb = new StringBuffer();
            sb.append("doFilter finished for ");
            sb.append(request.getRequestURI());
            if (request.getSession(false) != null) {
                sb.append(request.getSession(false).getId());
            } else {
                sb.append("No active session available.");
            }
            log.debug(sb.toString());
        }
    }
}

From source file:org.projectforge.web.UserFilter.java

public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (log.isDebugEnabled() == true) {
        log.debug("doFilter " + request.getRequestURI() + ": " + request.getSession().getId());
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                log.debug("Cookie " + cookie.getName() + ", path=" + cookie.getPath() + ", value="
                        + cookie.getValue() + ", secure=" + cookie.getVersion() + ", maxAge="
                        + cookie.getMaxAge() + ", domain=" + cookie.getDomain());
            }//from ww  w.j av  a  2  s  .  c o  m
        }
    }
    final HttpServletResponse response = (HttpServletResponse) resp;
    PFUserDO user = null;
    try {
        MDC.put("ip", request.getRemoteAddr());
        MDC.put("session", request.getSession().getId());
        if (ignoreFilterFor(request) == true) {
            // Ignore the filter for this request:
            if (log.isDebugEnabled() == true) {
                log.debug("Ignore: " + request.getRequestURI());
            }
            chain.doFilter(request, response);
        } else {
            // final boolean sessionTimeout = request.isRequestedSessionIdValid() == false;
            user = (PFUserDO) request.getSession().getAttribute(SESSION_KEY_USER);
            if (user != null) {
                if (log.isDebugEnabled() == true) {
                    log.debug("User found in session: " + request.getRequestURI());
                }
            } else if (updateRequiredFirst == false) {
                // Ignore stay-logged-in if redirect to update page is required.
                user = checkStayLoggedIn(request, response);
                if (user != null) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("User's stay logged-in cookie found: " + request.getRequestURI());
                    }
                    user.setAttribute(USER_ATTR_STAY_LOGGED_IN, true); // Used by MenuMobilePage.
                    UserFilter.login(request, user);
                }
            }
            if (user != null) {
                MDC.put("user", user.getUsername());
                PFUserContext.setUser(user);
                request = decorateWithLocale(request, user);
                chain.doFilter(request, response);
            } else {
                if (((HttpServletRequest) req).getRequestURI().startsWith(WICKET_PAGES_PREFIX) == true) {
                    // Access-checking is done by Wicket, not by this filter:
                    request = decorateWithLocale(request, user);
                    chain.doFilter(request, response);
                } else {
                    response.getWriter().append("No access.");
                }
            }
        }
    } finally {
        PFUserContext.setUser(null);
        MDC.remove("ip");
        MDC.remove("session");
        if (user != null) {
            MDC.remove("user");
        }
        if (log.isDebugEnabled() == true) {
            log.debug("doFilter finished for " + request.getRequestURI() + ": " + request.getSession().getId());
        }
    }
}

From source file:org.projectforge.web.UserFilter.java

/**
 * User is not logged. Checks a stay-logged-in-cookie.
 * @return user if valid cookie found, otherwise null.
 *//*from   w w w  .  j  a  v a2s .  c  o  m*/
private PFUserDO checkStayLoggedIn(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie sessionIdCookie = getCookie(request, "JSESSIONID");
    if (sessionIdCookie != null && sessionIdCookie.getSecure() == false && request.isSecure() == true) {
        // Hack for developers: Safari (may-be also other browsers) don't update unsecure cookies for secure connections. This seems to be
        // occurring
        // if you use ProjectForge on localhost with http and https (e. g. for testing). You have to delete this cookie normally in your
        // browser.
        final Cookie cookie = new Cookie("JSESSIONID", "to be deleted");
        cookie.setMaxAge(0);
        cookie.setPath(sessionIdCookie.getPath()); // Doesn't work for Safari: getPath() returns always null!
        response.addCookie(cookie);
    }
    final Cookie stayLoggedInCookie = getStayLoggedInCookie(request);
    if (stayLoggedInCookie != null) {
        final String value = stayLoggedInCookie.getValue();
        if (StringUtils.isBlank(value) == true) {
            return null;
        }
        final String[] values = value.split(":");
        if (values == null || values.length != 3) {
            log.warn("Invalid cookie found: " + value);
            return null;
        }
        final Integer userId = NumberHelper.parseInteger(values[0]);
        final PFUserDO user = userDao.internalGetById(userId);
        if (user == null) {
            log.warn("Invalid cookie found (user not found): " + value);
            return null;
        }
        if (user.getUsername().equals(values[1]) == false) {
            log.warn("Invalid cookie found (user name wrong, maybe changed): " + value);
            return null;
        }
        if (values[2] == null || values[2].equals(user.getStayLoggedInKey()) == false) {
            log.warn("Invalid cookie found (stay-logged-in key, maybe renewed and/or user password changed): "
                    + value);
            return null;
        }
        if (Login.getInstance().checkStayLoggedIn(user) == false) {
            log.warn("Stay-logged-in wasn't accepted by the login handler: " + user.getUserDisplayname());
            return null;
        }
        addStayLoggedInCookie(request, response, stayLoggedInCookie);
        log.info("User successfully logged in using stay-logged-in method: " + user.getUserDisplayname());
        return user;
    }
    return null;
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Generates a reusable http client wrapper which can be given to {@link #fireRequest(HttpClientWrapper, String, Method, Map, Object, boolean)}
 * as an efficiency mechanism//  www .j a v a2 s  .  com
 * 
 * @param multiThreaded true if you want to allow the client to run in multiple threads
 * @param idleConnectionTimeout if this is 0 then it will use the defaults, otherwise connections will be timed out after this long (ms)
 * @param cookies to send along with every request from this client
 * @return the reusable http client wrapper
 */
public static HttpClientWrapper makeReusableHttpClient(boolean multiThreaded, int idleConnectionTimeout,
        Cookie[] cookies) {
    HttpClientWrapper wrapper;
    HttpClient client;
    MultiThreadedHttpConnectionManager connectionManager = null;
    if (multiThreaded) {
        connectionManager = new MultiThreadedHttpConnectionManager();
        client = new HttpClient(connectionManager);
    } else {
        client = new HttpClient();
    }
    if (idleConnectionTimeout <= 0) {
        idleConnectionTimeout = 5000;
    }
    client.getHttpConnectionManager().closeIdleConnections(idleConnectionTimeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(idleConnectionTimeout);
    // create the initial state
    HttpState initialState = new HttpState();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            org.apache.commons.httpclient.Cookie mycookie = new org.apache.commons.httpclient.Cookie(
                    c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure());
            initialState.addCookie(mycookie);
        }
        client.setState(initialState);
    }
    // set some defaults
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    wrapper = new HttpClientWrapper(client, connectionManager, initialState);
    return wrapper;
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Snoop on the request if the request parameter snoop=1 output appears in the log, at
 * level INFO/*from  w  ww  . ja v a2  s. c o m*/
 *
 * @param request
 */
private void snoopRequest(HttpServletRequest request) {
    boolean snoop = "1".equals(request.getParameter("snoop"));
    if (snoop) {
        StringBuilder sb = new StringBuilder("SData Request :");
        sb.append("\n\tRequest Path :").append(request.getPathInfo());
        sb.append("\n\tMethod :").append(request.getMethod());
        for (Enumeration<?> hnames = request.getHeaderNames(); hnames.hasMoreElements();) {
            String name = (String) hnames.nextElement();
            sb.append("\n\tHeader :").append(name).append("=[").append(request.getHeader(name)).append("]");
        }
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                sb.append("\n\tCookie:");
                sb.append("name[").append(c.getName());
                sb.append("]path[").append(c.getPath());
                sb.append("]value[").append(c.getValue());
            }
        }
        sb.append("]");
        LOG.info(sb.toString());
    }
}

From source file:org.sakaiproject.sdata.tool.SnoopHandler.java

/**
 * @param request/*from  w  ww . j  av  a2 s . co m*/
 */
private void snoopRequest(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder("SData Request :").append(request);
    sb.append("\n\tRequest Path :").append(request.getPathInfo());
    sb.append("\n\tMethod :").append(request.getMethod());
    for (Enumeration<?> hnames = request.getHeaderNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tHeader :").append(name).append("=[").append(request.getHeader(name)).append("]");
    }
    for (Enumeration<?> hnames = request.getParameterNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tParameter :").append(name).append("=[").append(request.getParameter(name)).append("]");
    }
    if (request.getCookies() != null) {
        for (Cookie c : request.getCookies()) {
            sb.append("\n\tCookie:");
            sb.append("name[").append(c.getName());
            sb.append("]path[").append(c.getPath());
            sb.append("]value[").append(c.getValue());
        }
    }
    sb.append("]");
    for (Enumeration<?> hnames = request.getAttributeNames(); hnames.hasMoreElements();) {
        String name = (String) hnames.nextElement();
        sb.append("\n\tAttribute :").append(name).append("=[").append(request.getAttribute(name)).append("]");
    }
    HttpSession session = request.getSession();
    sb.append("\n\tUser :").append(request.getRemoteUser());
    if (session != null) {
        sb.append("\n\tSession ID :").append(session.getId());
        for (Enumeration<?> hnames = session.getAttributeNames(); hnames.hasMoreElements();) {
            String name = (String) hnames.nextElement();
            sb.append("\n\tSession Attribute :").append(name).append("=[").append(session.getAttribute(name))
                    .append("]");
        }

    } else {
        sb.append("\n\tNo Session");
    }

    LOG.info(sb.toString());
}

From source file:org.sakaiproject.util.RequestFilter.java

protected void addCookie(HttpServletResponse res, Cookie cookie) {

    if (!m_cookieHttpOnly) {
        // Use the standard servlet mechanism for setting the cookie
        res.addCookie(cookie);/*w ww.  j  a v  a2 s  .  c om*/
    } else {
        // Set the cookie manually

        StringBuffer sb = new StringBuffer();

        ServerCookie.appendCookieValue(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
                cookie.getPath(), cookie.getDomain(), cookie.getComment(), cookie.getMaxAge(),
                cookie.getSecure(), m_cookieHttpOnly);

        res.addHeader("Set-Cookie", sb.toString());
    }
    return;
}

From source file:org.sonar.server.authentication.CsrfVerifierTest.java

@Test
public void verify_state() throws Exception {
    String state = "state";
    when(request.getCookies()).thenReturn(new Cookie[] { new Cookie("OAUTHSTATE", sha256Hex(state)) });
    when(request.getParameter("state")).thenReturn(state);

    underTest.verifyState(request, response);

    verify(response).addCookie(cookieArgumentCaptor.capture());
    Cookie updatedCookie = cookieArgumentCaptor.getValue();
    assertThat(updatedCookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(updatedCookie.getValue()).isNull();
    assertThat(updatedCookie.getPath()).isEqualTo("/");
    assertThat(updatedCookie.getMaxAge()).isEqualTo(0);
}

From source file:org.sonar.server.authentication.CsrfVerifierTest.java

private void verifyCookie(Cookie cookie, boolean isSecured) {
    assertThat(cookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(cookie.getValue()).isNotEmpty();
    assertThat(cookie.getPath()).isEqualTo("/");
    assertThat(cookie.isHttpOnly()).isTrue();
    assertThat(cookie.getMaxAge()).isEqualTo(-1);
    assertThat(cookie.getSecure()).isEqualTo(isSecured);
}