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:io.gravitee.management.security.config.basic.filter.JWTAuthenticationFilter.java

@Override
@SuppressWarnings(value = "unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    final Optional<Cookie> optionalStringToken;

    if (req.getCookies() == null) {
        optionalStringToken = Optional.empty();
    } else {//w  w w  . j a v a 2 s.  com
        optionalStringToken = Arrays.stream(req.getCookies())
                .filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny();
    }
    if (optionalStringToken.isPresent()) {
        String stringToken = optionalStringToken.get().getValue();

        final String authorizationSchema = "Bearer";
        if (stringToken.contains(authorizationSchema)) {
            stringToken = stringToken.substring(authorizationSchema.length()).trim();
            try {
                final Map<String, Object> verify = jwtVerifier.verify(stringToken);

                final List<SimpleGrantedAuthority> authorities = ((List<Map>) verify.get(JWTClaims.PERMISSIONS))
                        .stream().map(map -> new SimpleGrantedAuthority(map.get("authority").toString()))
                        .collect(Collectors.toList());

                final UserDetails userDetails = new UserDetails(getStringValue(verify.get(JWTClaims.SUBJECT)),
                        "", authorities, getStringValue(verify.get(JWTClaims.EMAIL)),
                        getStringValue(verify.get(JWTClaims.FIRSTNAME)),
                        getStringValue(verify.get(JWTClaims.LASTNAME)));

                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()));
            } catch (Exception e) {
                LOGGER.error("Invalid token", e);

                final Cookie bearerCookie = jwtCookieGenerator.generate(null);
                res.addCookie(bearerCookie);

                res.sendError(HttpStatusCode.UNAUTHORIZED_401);
            }
        } else {
            LOGGER.info("Authorization schema not found");
        }
    } else {
        LOGGER.info("Authorization cookie not found");
    }
    chain.doFilter(request, response);
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchByDate(HttpServletRequest request, HttpServletResponse response) {
    Cookie sbdCookie = null;//  w  w w  . j  av  a2s .c om

    String searchByDate = request.getParameter("searchByDate");
    if (searchByDate == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchByDate")) {
                sbdCookie = c;
            }
        }
        if (sbdCookie != null) {
            searchByDate = sbdCookie.getValue();
        } else {
            searchByDate = new SimpleDateFormat("dd.MM.yyyy").format(Calendar.getInstance().getTime());
        }
    } else {
        sbdCookie = new Cookie("searchByDate", searchByDate);
        sbdCookie.setPath("/");
        response.addCookie(sbdCookie);
    }
    return searchByDate;
}

From source file:ShoppingCartViewerCookie.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String sessionid = null;//from  www  .  ja v a 2s. c om
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("sessionid")) {
                sessionid = cookies[i].getValue();
                break;
            }
        }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
        sessionid = generateSessionId();
        Cookie c = new Cookie("sessionid", sessionid);
        res.addCookie(c);
    }

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
        out.println("<B>None</B>");
    } else {
        out.println("<UL>");
        for (int i = 0; i < items.length; i++) {
            out.println("<LI>" + items[i]);
        }
        out.println("</UL>");
    }

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");

    // Offer a help page.
    out.println("For help, click <A HREF=\"/servlet/Help" + "?topic=ShoppingCartViewerCookie\">here</A>");

    out.println("</BODY></HTML>");
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchBy(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie sbtCookie = null;/* www . j  a v a  2s  .c  o m*/

    String searchBy = request.getParameter("searchBy");
    if (searchBy == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchBy")) {
                sbtCookie = c;
            }
        }
        if (sbtCookie != null) {
            searchBy = URLDecoder.decode(sbtCookie.getValue(), "UTF-8");
        } else {
            searchBy = "";
        }
    } else {
        sbtCookie = new Cookie("searchBy", URLEncoder.encode(searchBy, "UTF-8"));
        sbtCookie.setPath("/");
        response.addCookie(sbtCookie);
    }
    return searchBy;
}

From source file:net.longfalcon.web.BaseController.java

protected boolean isCookieSet(String cookieName, HttpServletRequest httpServletRequest) {
    try {//from  ww  w. ja  va2  s .co  m
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName) && ValidatorUtil.isNotNull(cookie.getValue())) {
                return true;
            }
        }
    } catch (Exception e) {
        _log.error(e);
    }
    return false;
}

From source file:org.apache.jsp.fileUploader_jsp.java

public static String getBrowserInfiniteCookie(HttpServletRequest request) {
    Cookie[] cookieJar = request.getCookies();
    if (cookieJar != null) {
        for (Cookie cookie : cookieJar) {
            if (cookie.getName().equals("infinitecookie")) {
                //System.out.println("Got Browser Cookie Line 109: " + cookie.getValue());
                return cookie.getValue() + ";";
            }//from ww w .j av  a2 s  .  c o m
        }
    }
    return null;
}

From source file:com.jnj.b2b.storefront.controllers.pages.LoginPageController.java

protected boolean doRedirect(final HttpServletRequest request, final HttpServletResponse response,
        final boolean isUserAnonymous, final String guid) {
    boolean redirect = true;

    if (!isUserAnonymous && guid != null && request.getCookies() != null) {
        final String guidCookieName = cookieGenerator.getCookieName();
        if (guidCookieName != null) {
            for (final Cookie cookie : request.getCookies()) {
                if (guidCookieName.equals(cookie.getName())) {
                    if (guid.equals(cookie.getValue())) {
                        redirect = false;
                        break;
                    } else {
                        cookieGenerator.removeCookie(response);
                    }// w w w  .  java  2s .  c o m
                }
            }
        }
    }
    return redirect;
}

From source file:cn.vlabs.umt.ui.servlet.LogoutServlet.java

private String getUserName(HttpServletRequest request) {
    User user = SessionUtils.getUser(request);
    String username = null;//from  w  ww . j  a  va2  s .  c  om
    if (user == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (Attributes.COOKIE_NAME.equals(cookie.getName())
                        && StringUtils.isNotEmpty(cookie.getValue())) {
                    try {
                        username = new String(cred.decrypt(HexUtil.toBytes(cookie.getValue())), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                    }
                }
            }
        }
    } else {
        username = user.getCstnetId();
    }
    return username;
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchWithinDate(HttpServletRequest request, HttpServletResponse response) {
    Cookie sbtCookie = null;/*ww w.ja va  2 s.c o m*/

    String searchWithinDate = request.getParameter("searchWithinDate");
    if (searchWithinDate == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchWithinDate")) {
                sbtCookie = c;
            }
        }
        if (sbtCookie != null) {
            searchWithinDate = sbtCookie.getValue();
        } else {
            searchWithinDate = "true";
        }
    } else {
        sbtCookie = new Cookie("searchWithinDate", searchWithinDate);
        sbtCookie.setPath("/");
        response.addCookie(sbtCookie);
    }
    return searchWithinDate;
}

From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java

private String getGeoNodeCookieValue(HttpServletRequest request) {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Inspecting the http request looking for the GeoNode Session ID.");
    }/*from w  w  w . j a v a  2  s.  c o  m*/
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Found " + cookies.length + " cookies!");
        }
        for (Cookie c : cookies) {
            if (GEONODE_COOKIE_NAME.equals(c.getName())) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine("Found GeoNode cookie: " + c.getValue());
                }
                return c.getValue();
            }
        }
    } else {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Found no cookies!");
        }
    }

    return null;
}