Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.epam.cme.storefront.interceptors.beforecontroller.SecureRequestCookieCheckBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception // NOPMD
{
    final String path = getUrlPathHelper().getServletPath(request);
    if (request.isSecure() && !getExcludeUrls().contains(path)) {
        boolean redirect = true;
        final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
        if (guid != null && request.getCookies() != null) {
            final String guidCookieName = getCookieGenerator().getCookieName();
            if (guidCookieName != null) {
                for (final Cookie cookie : request.getCookies()) {
                    if (guidCookieName.equals(cookie.getName())) {
                        if (guid.equals(cookie.getValue())) {
                            redirect = false;
                            break;
                        } else {
                            LOG.info("Found secure cookie with invalid value. expected [" + guid + "] actual ["
                                    + cookie.getValue() + "]. removing.");
                            getCookieGenerator().removeCookie(response);
                        }//from  www  .  ja v  a  2  s  .  c o  m
                    }
                }
            }
        }
        if (redirect) {
            LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie")
                    + ", redirecting");
            getRedirectStrategy().sendRedirect(request, response, getLoginUrl());
            return false;
        }
    }

    return true;
}

From source file:com.epam.training.storefront.interceptors.beforecontroller.SecureRequestCookieCheckBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception //NOPMD
{
    final String path = getUrlPathHelper().getServletPath(request);
    if (request.isSecure() && !getExcludeUrls().contains(path)) {
        boolean redirect = true;
        final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
        if (guid != null && request.getCookies() != null) {
            final String guidCookieName = getCookieGenerator().getCookieName();
            if (guidCookieName != null) {
                for (final Cookie cookie : request.getCookies()) {
                    if (guidCookieName.equals(cookie.getName())) {
                        if (guid.equals(cookie.getValue())) {
                            redirect = false;
                            break;
                        } else {
                            LOG.info("Found secure cookie with invalid value. expected [" + guid + "] actual ["
                                    + cookie.getValue() + "]. removing.");
                            getCookieGenerator().removeCookie(response);
                        }/*from w w  w .j  a v a  2s.com*/
                    }
                }
            }
        }
        if (redirect) {
            LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie")
                    + ", redirecting");
            getRedirectStrategy().sendRedirect(request, response, getLoginUrl());
            return false;
        }
    }

    return true;
}

From source file:spring.travel.site.controllers.OffersControllerTest.java

@Test
public void shouldGetOffersAndAdverts() throws Exception {
    stubGet("/user?id=123", new User("123", "Fred", "Flintstone", "freddyf", Optional.<Address>empty()));

    stubGet("/profile/user/123", new Profile(LifeCycle.Family, Spending.Economy, Gender.Male));

    stubGet("/loyalty/user/123", new Loyalty(Group.Bronze, 100));

    List<Offer> offers = Arrays.asList(new Offer("Offer 1", "Blah blah", "offer1.jpg"),
            new Offer("Offer 2", "Blah blah", "offer2.jpg"), new Offer("Offer 3", "Blah blah", "offer3.jpg"),
            new Offer("Offer 4", "Blah blah", "offer4.jpg"));

    stubGet("/offers?lifecycle=family&spending=economy&gender=male&loyalty=bronze", offers);

    List<Advert> adverts = Arrays.asList(new Advert("Advert 1", "advert1.jpg", "Blah blah"),
            new Advert("Advert 2", "advert2.jpg", "Blah blah"),
            new Advert("Advert 3", "advert3.jpg", "Blah blah"),
            new Advert("Advert 4", "advert4.jpg", "Blah blah"),
            new Advert("Advert 5", "advert5.jpg", "Blah blah"));

    stubGet("/adverts?count=4&target=low", adverts);

    String signature = "0923023985092384";
    String cookieName = "GETAWAY_SESSION";
    String encoded = "id=123";
    String cookieValue = signature + "-" + encoded;

    Cookie cookie = Mockito.mock(Cookie.class);
    when(cookie.getName()).thenReturn(cookieName);
    when(cookie.getValue()).thenReturn(cookieValue);

    when(mockVerifier.verify(encoded, signature)).thenReturn(true);

    MvcResult mvcResult = this.mockMvc
            .perform(get("/offers").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
                    .header("Cookie", cookieName + "=" + cookieValue))
            .andExpect(status().isOk()).andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(isA(ModelAndView.class))).andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk());

    ModelAndView modelAndView = (ModelAndView) mvcResult.getAsyncResult(1000);

    Map<String, Object> model = modelAndView.getModel();

    User user = (User) model.get("user");
    assertEquals("Fred", user.getFirstName());

    OffersView modelOffers = (OffersView) model.get("offers");
    assertNotNull(modelOffers);/*from  w  w  w .j  a  v  a2 s  .c  om*/
    assertEquals("Offer 1", modelOffers.getOffers().get(0).getTitle());

    AdvertsView modelAdverts = (AdvertsView) model.get("adverts");
    assertNotNull(modelAdverts);
    assertEquals("Advert 1", modelAdverts.getAdverts().get(0).getTitle());
}

From source file:com.baron.bm.controller.MemberController.java

@RequestMapping("/admin")
public String admin(HttpServletRequest request, Model model) {
    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals("bm_permission")) {
            System.out.println(cookie.getValue());
            if ("1".equals(cookie.getValue())) {
                List<BookModel> bookmodel = joinService.selectBestBook();
                List<MemberModel> memberList = joinService.selectBest();
                model.addAttribute("bookmodel", bookmodel);
                model.addAttribute("bestList", memberList);
                return "admin";
            } else
                return "adminfail";
        }//from   w  w w  .  j  av  a2 s.  c  o m
    }
    return null;
}

From source file:logout2_servlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w ww .java  2 s. c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String access_token = "";
    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie1 = cookies[i];
        if (cookies[i].getName().equals("access_token")) {
            access_token = cookie1.getValue();
            cookie = cookie1;
        }
    }
    System.out.println("TOKEN = " + access_token);

    String USER_AGENT = "Mozilla/5.0";
    String url = "http://localhost:8082/Identity_Service/logout_servlet";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "access_token=" + access_token;

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();

    JSONParser parser = new JSONParser();
    JSONObject obj = null;
    try {
        obj = (JSONObject) parser.parse(resp.toString());
    } catch (ParseException ex) {
        Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    String status = (String) obj.get("status");
    System.out.println(status);
    if (status.equals("ok")) {
        cookie.setMaxAge(0);
        response.sendRedirect("login.jsp");
    } else {

    }

}

From source file:com.vmware.identity.openidconnect.protocol.HttpRequest.java

public String getCookieValue(String cookieName) {
    Validate.notEmpty(cookieName, "cookieName");

    if (this.httpServletRequest != null && this.httpServletRequest.getCookies() != null) {
        for (Cookie cookie : this.httpServletRequest.getCookies()) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }/*from   w w  w .  j av  a  2s  .  co  m*/
        }
    }
    return null;
}

From source file:eu.semlibproject.annotationserver.managers.CookiesManager.java

/**
 * Remove an annotation server cookie//  ww w  .ja  va2s.  c o m
 * 
 * @param request
 * @param response
 * @param token 
 */
public void removeASCookie(HttpServletRequest request, HttpServletResponse response, String token) {

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cCookie = cookies[i];
            if (SemlibConstants.COOCKIE_NAME.equalsIgnoreCase(cCookie.getName())) {
                String value = cCookie.getValue();
                if (value.equals(token)) {
                    removeASCookie(response, cCookie);
                }
                break;
            }
        }
    }
}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public String getLanguageCode(HttpHeaders httpHeaders, UriInfo uriInfo) {
    javax.ws.rs.core.Cookie cookie = httpHeaders.getCookies().get(cookieName);
    Optional<String> cookieValue = Optional.ofNullable((cookie != null) ? cookie.getValue() : null);
    return getLanguageCode(uriInfo.getRequestUri().getQuery(), cookieValue);
}

From source file:com.google.ie.web.interceptor.LoginInterceptor.java

/**
 * Checks if the fcauth cookie is present with a non empty value
 * /*  w  w w  . j av  a 2  s .  c  o m*/
 * @param request
 * @return true if a valid fcauth cookie is present in the request, else
 *         false
 */
private boolean checkAuthToken(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie != null && cookie.getName().equals(getFcauthCookieName())) {
                // Cookie found. Check for value
                String authToken = cookie.getValue();
                if (authToken != null && authToken.length() > 0) {
                    LOG.info("Auth token found. Allowing request to proceed");
                    return true;
                }
            }
        }
    }
    LOG.warn("Auth token not found. Stopping request to proceed");
    return false;
}

From source file:org.ngrinder.infra.spring.UserHandlerMethodArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    User currentUser = getUserContext().getCurrentUser();

    String userParam = webRequest.getParameter("ownerId");
    if (StringUtils.isNotBlank(userParam) && currentUser.getRole().hasPermission(Permission.SWITCH_TO_ANYONE)) {
        return getUserService().getOne(userParam);
    }//from  w w  w  .j  a  v a 2s.c  o m

    // User want to do something through other User status and this
    // switchUser is other user Id
    String switchUser = null;
    Cookie[] cookies = getCookies(webRequest);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("switchUser".equals(cookie.getName()) && cookie.getMaxAge() != 0) {
                switchUser = cookie.getValue();
            }
        }
    }
    // Let this can be done with parameter as well.
    switchUser = StringUtils.defaultIfBlank(webRequest.getParameter("switchUser"), switchUser);

    if (currentUser.getUserId().equals(switchUser)) {
        currentUser.setOwnerUser(null);
    } else if (StringUtils.isNotEmpty(switchUser)) {
        User ownerUser = getUserService().getOne(switchUser);
        // CurrentUser should remember whose status he used
        if (currentUser.getRole().hasPermission(Permission.SWITCH_TO_ANYONE)
                || (ownerUser.getFollowers() != null && ownerUser.getFollowers().contains(currentUser))) {
            currentUser.setOwnerUser(ownerUser);
            return ownerUser;
        }
    } else if (StringUtils.isEmpty(switchUser)) {
        currentUser.setOwnerUser(null);
    }

    return currentUser.getFactualUser();
}