Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.zz.globalsession.filter.AbstractGlobalSessionFilter.java

private Cookie getCurrentValidSessionIdCookie(HttpServletRequest req) {
    if (req.getCookies() != null) {
        for (Cookie cookie : req.getCookies()) {
            if (cookie.getName().equals(settings.getSessionIdKey()) && cookie.getValue() != null
                    && cookie.getValue().trim().length() > 0) {
                if (isValidSession(createGlobalSessionRequest(req, cookie.getValue()))) {
                    if (log.isDebugEnabled()) {
                        log.debug("SessionId cookie is found. (" + settings.getSessionIdKey() + " -> "
                                + cookie.getValue() + ")");
                    }//from   w  w  w  .  ja v a  2 s .  c  o m
                    return cookie;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("SessionId cookie is found but it's invalid. (" + settings.getSessionIdKey()
                                + " -> " + cookie.getValue() + ")");
                    }
                    continue;
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("SessionId cookie is not found.");
    }
    return null;
}

From source file:net.sourceforge.subsonic.service.PlayerService.java

/**
 * Reads the player ID from the cookie in the HTTP request.
 *
 * @param request  The HTTP request./*  w  w w. j a v  a 2 s.  c o m*/
 * @param username The name of the current user.
 * @return The player ID embedded in the cookie, or <code>null</code> if cookie is not present.
 */
private String getPlayerIdFromCookie(HttpServletRequest request, String username) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }
    String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username);
    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:fr.cph.stock.web.servlet.portfolio.AddEquityServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    try {//w ww .j  ava2  s .  c o m
        String lang = CookieManagement.getCookieLanguage(Arrays.asList(request.getCookies()));
        LanguageFactory language = LanguageFactory.getInstance();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String manual = request.getParameter("manual");
        if (manual != null && manual.equals("true")) {
            String manualName = request.getParameter("manualName");
            String manualUnitCostPrice = request.getParameter("manualUnitCostPrice");
            String manualQuantity = request.getParameter("manualQuantity");
            String manualParityPersonal = request.getParameter("manualParityPersonal");
            String manualCurrency = request.getParameter("manualCurrency");
            String manualIndustry = request.getParameter("manualIndustry");
            String manualSector = request.getParameter("manualSector");
            String manualQuote = request.getParameter("manualQuote");

            Double quantity = NumberUtils.createDouble(manualQuantity);
            Double unitCostPrice = NumberUtils.createDouble(manualUnitCostPrice);
            Double parityPersonal = null;
            if (!manualParityPersonal.equals("")) {
                parityPersonal = NumberUtils.createDouble(manualParityPersonal);
            }
            Double quote = NumberUtils.createDouble(manualQuote);
            Company company = business.createManualCompany(manualName, manualIndustry, manualSector,
                    Currency.getEnum(manualCurrency), quote);

            Equity equity = new Equity();
            equity.setQuantity(quantity);
            equity.setUnitCostPrice(unitCostPrice);
            equity.setParityPersonal(parityPersonal);
            try {
                business.createManualEquity(user.getId(), company, equity);
                request.setAttribute("added", language.getLanguage(lang).get("CONSTANT_ADDED") + " !");
            } catch (EquityException e) {
                request.setAttribute("addError", e.getMessage());
            }
        } else {
            String ticker = request.getParameter("ticker").toUpperCase();
            String unitCostP = request.getParameter("unitCostPrice");
            String quant = request.getParameter("quantity");
            String parityPerso = request.getParameter("parityPersonal");

            Double quantity = NumberUtils.createDouble(quant);
            Double unitCostPrice = NumberUtils.createDouble(unitCostP);
            Double parityPersonal = null;
            if (!parityPerso.equals("")) {
                parityPersonal = NumberUtils.createDouble(parityPerso);
            }

            Equity equity = new Equity();
            equity.setQuantity(quantity);
            equity.setUnitCostPrice(unitCostPrice);
            equity.setParityPersonal(parityPersonal);
            try {
                business.createEquity(user.getId(), ticker, equity);
                request.setAttribute("added", language.getLanguage(lang).get("CONSTANT_ADDED") + " !");
            } catch (YahooException | EquityException e) {
                request.setAttribute("addError", e.getMessage());
            }
        }

        request.getRequestDispatcher("home").forward(request, response);
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new ServletException("Error: " + t.getMessage(), t);
    }
}

From source file:hudson.Functions.java

public static boolean isAutoRefresh(HttpServletRequest request) {
    String param = request.getParameter("auto_refresh");
    if (param != null) {
        return Boolean.parseBoolean(param);
    }/*from   ww  w. j a  va  2 s  .com*/
    Cookie[] cookies = request.getCookies();
    if (cookies == null)
        return false; // when API design messes it up, we all suffer

    for (Cookie c : cookies) {
        if (c.getName().equals("hudson_auto_refresh")) {
            return Boolean.parseBoolean(c.getValue());
        }
    }
    return false;
}

From source file:com.orangeleap.webtools.controller.json.LogoutController.java

@RequestMapping("/logout.json")
public void logout(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String guid = request.getParameter("guid");

    final String sessionId = request.getParameter("sessionId");

    if (StringUtils.isNotBlank(sessionId)) {
        final Cookie sessionCookies[] = request.getCookies();
        Cookie sessionCookie = null;/*from  w w w .  j av  a 2 s . co  m*/

        for (final Cookie aCookie : sessionCookies) {
            if (aCookie.getName().equals("sessionId")) {
                aCookie.setMaxAge(0);
                aCookie.setValue("");
                sessionCookie = aCookie;
                break;
            }
        }
        if (sessionCookie == null) {
            sessionCookie = new Cookie("sessionId", "");
        }
        response.addCookie(sessionCookie);
        sessionCache.remove(sessionId);
    }

    final Widget widget = widgetService.getWidget(guid);
    final String authenticationUrl = widget.getWidgetAuthenticationURL();

    response.sendRedirect(authenticationUrl);
}

From source file:com.mobilehelix.appserver.session.SessionManager.java

private String getSessIDFromRequest(HttpServletRequest req) throws AppserverSystemException {
    String sessIDB64 = req.getHeader(HTTPHeaderConstants.MH_SESSION_ID_HEADER);
    if ((sessIDB64 == null) && (req.getCookies() != null)) {
        for (Cookie c : req.getCookies()) {
            if (HTTPHeaderConstants.MH_SESSION_ID_HEADER.equalsIgnoreCase(c.getName())) {
                sessIDB64 = c.getValue();
                break;
            }/*  w  ww.j a v  a  2s .c om*/
        }
    }
    // Decode the B64-encoded key.
    if (sessIDB64 != null) {
        byte[] sessID = Base64.decodeBase64(sessIDB64);
        return this.hashSessionID(sessID);
    }
    return null;
}

From source file:shiver.me.timbers.spring.security.jwt.AuthenticationRequestJwtTokenParserTest.java

@Test
@SuppressWarnings("unchecked")
public void Can_parse_a_jwt_token_from_a_header() throws JwtInvalidTokenException {

    final HttpServletRequest request = mock(HttpServletRequest.class);

    final String token = someString();
    final Object principal = new Object();
    final Authentication expected = mock(Authentication.class);

    // Given//from w w w  .  java  2  s .co m
    given(request.getCookies()).willReturn(new Cookie[0]);
    given(request.getHeader(tokenName)).willReturn(token);
    given(principleTokenParser.parse(token)).willReturn(principal);
    given(authenticationConverter.convert(principal)).willReturn(expected);

    // When
    final Authentication actual = tokenParser.parse(request);

    // Then
    assertThat(actual, is(expected));
}

From source file:net.sf.j2ep.servers.ClusterContainer.java

/**
 * Checks the request for any session. If there is a session created we
 * make sure that the server returned is the one the issued the session.
 * If no session is included in the request we will choose the next server
 * in a round-robin fashion.//  w  ww.  ja  v a  2 s. c  o  m
 * 
 * @see net.sf.j2ep.model.ServerContainer#getServer(javax.servlet.http.HttpServletRequest)
 */
public Server getServer(HttpServletRequest request) {
    String serverId = getServerIdFromCookie(request.getCookies());
    ClusteredServer server = (ClusteredServer) servers.get(serverId);
    if (server == null || !server.online()) {
        server = getNextServer();
    } else {
        log.debug("Server found in session");
    }

    if (server.online()) {
        log.debug("Using id " + server.getServerId() + " for this request");
    } else {
        log.error("All the servers in this cluster are offline. Using id " + server.getServerId()
                + ", will probably not work");
    }
    return server;
}

From source file:com.identityconcepts.shibboleth.WSFedLoginHandler.java

/**
 * Perform login with WSFedLoginHandler/*from w w w . ja v a 2 s  .co m*/
 *
 * @param  request  HTTPServletRequest
 * @param  response HTTPServletResponse
 */
public void login(final HttpServletRequest request, final HttpServletResponse response) {
    try {
        String redirectURL = null;
        if (isPassThrough(request.getCookies())) {
            log.debug("Cookie '{}' is set: continue with clientauthn protected servlet.", COOKIE_NAME);

            // construct URL for authenticationServlet
            redirectURL = getRedirectURL(request, authenticationServletURL);
        } else {
            // not passThrough
            log.debug("Cookie '{}' is not set: continue with x509 login page.", COOKIE_NAME);
            redirectURL = getRedirectURL(request, loginPageURL);
        }
        // send redirect
        if (!(redirectURL == null)) {
            log.debug("Redirect to {}", redirectURL);
            response.sendRedirect(redirectURL);
        } else {
            log.error("Could not set redirect URL, please check the configuration.");
        }
    } catch (IOException ex) {
        log.error("Unable to redirect to login page or authentication servlet.", ex);
    }

}

From source file:com.alfaariss.oa.util.web.CookieTool.java

/**
 * Returns the cookie value./*from  w w  w .jav  a  2  s.c  o  m*/
 * @param sCookie The cookie name.
 * @param oRequest The servlet request.
 * @return The cookie value or NULL if not available.
 */
public String getCookieValue(String sCookie, HttpServletRequest oRequest) {
    assert oRequest != null : "Supplied request == null";

    String sValue = null;
    Cookie[] cookies = oRequest.getCookies();
    if (cookies != null) //Cookies found
    {
        for (Cookie cookie : cookies) //For all cookies
        {
            if (cookie.getName().equals(sCookie)) //cookie found
            {
                sValue = cookie.getValue();
                //remove '"' surrounding cookie value if applicable
                int iLength = sValue.length();
                if (sValue.charAt(0) == '"' && sValue.charAt(iLength - 1) == '"') {
                    sValue = sValue.substring(1, iLength - 1);
                }
            }
        }
    }
    return sValue;
}