Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:com.openthinks.webscheduler.service.WebSecurityService.java

public Optional<User> validateUserByCookie(WebAttributers was) {
    Cookie[] cookies = was.getRequest().getCookies();
    if (cookies == null)
        return Optional.empty();
    Cookie rememberCookie = null;// ww w  .  j  a  v a2s  . c  o m
    for (Cookie cookie : cookies) {
        if (StaticDict.COOKIE_REMEMBER_ME.equals(cookie.getName()) && cookie.getValue() != null) {
            rememberCookie = cookie;
            break;
        }
    }
    if (rememberCookie != null) {
        User user = getUsers().findByCookie(rememberCookie.getValue());
        if (user != null) {
            User loginUserInfo = user.clone();//fix second login failed issue
            loginUserInfo.setPass(null);
            return Optional.of(loginUserInfo);
        }
    }
    return Optional.empty();
}

From source file:controllers.AuthFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Cookie[] cookies = httpRequest.getCookies();
    String status = "No cookie";
    // Check cookie with name auth
    if (cookies != null) {
        String token = null;/*w ww . jav a2 s .c  om*/
        for (Cookie cookie : cookies) {
            status = "No token cookie";
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
                break;
            }
        }

        // Check whether the auth token hasn't expired yet
        if (token != null) {
            status = "Token cookie exists";
            JSONObject obj = ISConnector.validateToken(token);
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            if (obj != null && obj.containsKey("error")) { //Authorization failed, expired access token
                status = "Authentication failed";
                String uri = req.getRequestURI();
                this.context.log("Requested Resource:: " + uri);

                // Get session and set session
                HttpSession session = req.getSession(false);
                this.context.log("Unauthorized access request");
                res.sendRedirect(req.getContextPath() + "/login");
                return;
            } else {
                status = "Authentication succeed";
                if (obj != null && obj.containsKey("id")) {
                    long id = (long) obj.get("id");
                    int u_id = (int) id;
                    UserWS.UserWS_Service service = new UserWS.UserWS_Service();
                    UserWS.UserWS port = service.getUserWSPort();
                    User user = (User) port.getUser(u_id);
                    if (user != null) {
                        req.setAttribute("user", user);
                    }
                }
            }
        }
    }
    request.setAttribute("status", status);
    // Pass the request along the filter chain
    chain.doFilter(request, response);
}

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. jav  a2s  . c  om
    }
    return null;
}

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);
    }// w  ww.ja  va2  s . c  o m
    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:org.apache.oodt.security.sso.OpenSSOImpl.java

private String getCookieVal(String name) {
    Cookie[] cookies = this.req.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie.getValue().startsWith("\"") && cookie.getValue().endsWith("\"")
                    ? cookie.getValue().substring(1, cookie.getValue().length() - 1)
                    : cookie.getValue();
        }//from  www. jav  a  2 s .c  o m
    }

    return null;
}

From source file:com.acmeair.web.RESTCookieSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    try {//from ww w  . j av  a 2  s  .  co  m
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();
        // The following code is to ensure that OG is always set on the thread
        try {
            TransactionService txService = getTxService();
            if (txService != null)
                txService.prepareForTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // could do .startsWith for now, but plan to move LOGOUT to its own REST interface eventually
        if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH)) {
            // if logging in, let the request flow
            chain.doFilter(req, resp);
            return;
        }

        Cookie cookies[] = request.getCookies();
        Cookie sessionCookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
                    sessionCookie = c;
                }
                if (sessionCookie != null)
                    break;
            }
            String sessionId = "";
            if (sessionCookie != null) // We need both cookie to work
                sessionId = sessionCookie.getValue().trim();
            else {
                log.info("falling through with a sessionCookie break, but it was null");
            }
            // did this check as the logout currently sets the cookie value to "" instead of aging it out
            // see comment in LogingREST.java
            if (sessionId.equals("")) {
                log.info("sending SC_FORBIDDEN due to empty session cookie");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // Need the URLDecoder so that I can get @ not %40
            ValidateTokenCommand validateCommand = new ValidateTokenCommand(sessionId);
            CustomerSession cs = validateCommand.execute();
            if (cs != null) {
                request.setAttribute(LOGIN_USER, cs.getCustomerid());
                chain.doFilter(req, resp);
                return;
            } else {
                log.info("sending SC_FORBIDDEN due  to validateCommand returning null");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        // if we got here, we didn't detect the session cookie, so we need to return 403
        log.info("sending SC_FORBIDDEN due finding no sessionCookie");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

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);
                    }//from   w ww . j a v  a  2  s. co  m
                }
            }
        }
    }
    return redirect;
}

From source file:hudson.Functions.java

public static Cookie getCookie(HttpServletRequest req, String name) {
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }/*from  w ww .  j ava 2 s .co m*/
        }
    }
    return null;
}

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  a2 s. co 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();
}

From source file:org.esigate.servlet.impl.RequestFactory.java

public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException {
    HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext,
            filterChain);//from   w  ww .  j  av  a  2 s  . c o  m
    // create request line
    String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(),
            request.getRequestURI(), request.getQueryString(), null);
    ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null);
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion));
    builder.setContext(context);
    // copy headers
    @SuppressWarnings("rawtypes")
    Enumeration names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        @SuppressWarnings("rawtypes")
        Enumeration values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            builder.addHeader(name, value);
        }
    }
    // create entity
    HttpServletRequestEntity entity = new HttpServletRequestEntity(request);
    builder.setEntity(entity);

    builder.setRemoteAddr(request.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = request.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());

    // Copy cookies
    // As cookie header contains only name=value so we don't need to copy
    // all attributes!
    javax.servlet.http.Cookie[] src = request.getCookies();
    if (src != null) {
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            builder.addCookie(dest);
        }
    }
    builder.setSession(new HttpServletSession(request));
    builder.setContextPath(request.getContextPath());
    return builder.build();
}