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:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request./* w  w  w . j a va2 s . com*/
 *
 * @param req servlet request to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
    String serializedJWT = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                LOG.info(cookieName + " cookie has been found and is being processed");
                serializedJWT = cookie.getValue();
                break;
            }
        }
    }
    return serializedJWT;
}

From source file:com.google.gerrit.httpd.ProjectOAuthFilter.java

private AuthInfo extractAuthInfo(Cookie cookie) throws UnsupportedEncodingException {
    String username = URLDecoder.decode(cookie.getName().substring(GIT_COOKIE_PREFIX.length()), UTF_8.name());
    String value = cookie.getValue();
    int splitPos = value.lastIndexOf('@');
    if (splitPos < 1 || splitPos == value.length() - 1) {
        // no providerId in the cookie value => assume default provider
        // note: a leading/trailing at sign is considered to belong to
        // the access token rather than being a separator
        return new AuthInfo(username, cookie.getValue(), defaultAuthPlugin, defaultAuthProvider);
    }//  w  ww. j a va2s .  co  m
    String token = value.substring(0, splitPos);
    String providerId = value.substring(splitPos + 1);
    splitPos = providerId.lastIndexOf(':');
    if (splitPos < 1 || splitPos == providerId.length() - 1) {
        // no colon at all or leading/trailing colon: malformed providerId
        return null;
    }
    String pluginName = providerId.substring(0, splitPos);
    String exportName = providerId.substring(splitPos + 1);
    OAuthLoginProvider provider = loginProviders.get(pluginName, exportName);
    if (provider == null) {
        return null;
    }
    return new AuthInfo(username, token, pluginName, exportName);
}

From source file:net.ymate.framework.webmvc.AbstractWebErrorProcessor.java

private String __doParseExceptionDetail(Throwable e) {
    IRequestContext _requestCtx = WebContext.getRequestContext();
    HttpServletRequest _request = WebContext.getRequest();
    WebContext _context = WebContext.getContext();
    ////from   w  ww . j a v a  2s  .c  om
    StringBuilder _errSB = new StringBuilder("An exception occurred at ")
            .append(DateTimeUtils.formatTime(System.currentTimeMillis(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS_SSS))
            .append(":\n");
    _errSB.append("-------------------------------------------------\n");
    _errSB.append("-- ThreadId: ").append(Thread.currentThread().getId()).append("\n");
    _errSB.append("-- RequestMapping: ").append(_requestCtx.getRequestMapping()).append("\n");
    _errSB.append("-- ResponseStatus: ").append(((GenericResponseWrapper) WebContext.getResponse()).getStatus())
            .append("\n");
    _errSB.append("-- Method: ").append(_requestCtx.getHttpMethod().name()).append("\n");
    _errSB.append("-- RemoteAddrs: ").append(JSON.toJSONString(WebUtils.getRemoteAddrs(_request))).append("\n");
    RequestMeta _meta = _context.getAttribute(RequestMeta.class.getName());
    if (_meta != null) {
        _errSB.append("-- Controller: ").append(_meta.getTargetClass().getName()).append(":")
                .append(_meta.getMethod().getName()).append("\n");
    }
    _errSB.append("-- ContextAttributes:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getAttributes().entrySet()) {
        if (!StringUtils.startsWith(_entry.getKey(), "net.ymate.platform.webmvc")) {
            _errSB.append("\t  ").append(_entry.getKey()).append(": ")
                    .append(JSON.toJSONString(_entry.getValue())).append("\n");
        }
    }
    _errSB.append("-- Parameters:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getParameters().entrySet()) {
        _errSB.append("\t  ").append(_entry.getKey()).append(": ").append(JSON.toJSONString(_entry.getValue()))
                .append("\n");
    }
    _errSB.append("-- Attributes:").append("\n");
    Enumeration _enum = _request.getAttributeNames();
    while (_enum.hasMoreElements()) {
        String _attrName = (String) _enum.nextElement();
        _errSB.append("\t  ").append(_attrName).append(": ")
                .append(JSON.toJSONString(_request.getAttribute(_attrName))).append("\n");
    }
    _errSB.append("-- Headers:").append("\n");
    _enum = _request.getHeaderNames();
    while (_enum.hasMoreElements()) {
        String _headName = (String) _enum.nextElement();
        if ("cookie".equalsIgnoreCase(_headName)) {
            continue;
        }
        _errSB.append("\t  ").append(_headName).append(": ")
                .append(JSON.toJSONString(_request.getHeader(_headName))).append("\n");
    }
    _errSB.append("-- Cookies:").append("\n");
    Cookie[] _cookies = _request.getCookies();
    if (_cookies != null) {
        for (Cookie _cookie : _cookies) {
            _errSB.append("\t  ").append(_cookie.getName()).append(": ")
                    .append(JSON.toJSONString(_cookie.getValue())).append("\n");
        }
    }
    _errSB.append("-- Session:").append("\n");
    for (Map.Entry<String, Object> _entry : _context.getSession().entrySet()) {
        _errSB.append("\t  ").append(_entry.getKey()).append(": ").append(JSON.toJSONString(_entry.getValue()))
                .append("\n");
    }
    _errSB.append(__doExceptionToString(e));
    _errSB.append("-------------------------------------------------\n");
    //
    return _errSB.toString();
}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>/*from  ww w .  java  2s.  c o m*/
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:ed.net.CookieJar.java

public List<Cookie> clean(boolean removeNonpersistent) {
    List<Cookie> deadCookies = new ArrayList<Cookie>();

    for (Cookie c : _cookies.values()) {
        if (isExpired(c))
            deadCookies.add(c);// ww w.  j av a  2s  .  c  om

        if (removeNonpersistent && c.getMaxAge() < 0)
            deadCookies.add(c);
    }
    for (Cookie deadCookie : deadCookies)
        _cookies.remove(deadCookie.getName());

    return deadCookies;
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }/*ww w . j a v  a  2 s.  c  o m*/

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}

From source file:com.stratelia.webactiv.survey.servlets.SurveyRequestRouter.java

/**
 * Read cookie from anonymous user and set status of anonymous user to allow him to vote or not
 * @param request the current HttpServletRequest
 * @param surveySC the survey session controller
 *//*from   ww w  .java  2s  . c om*/
private void setAnonymousParticipationStatus(HttpServletRequest request, SurveySessionController surveySC) {
    surveySC.hasAlreadyParticipated(false);
    String surveyId = request.getParameter("SurveyId");
    if (surveyId != null) {
        Cookie[] cookies = request.getCookies();
        String cookieName = SurveySessionController.COOKIE_NAME + surveyId;
        for (int i = 0; i < cookies.length; i++) {
            Cookie currentCookie = cookies[i];
            if (currentCookie.getName().equals(cookieName)) {
                surveySC.hasAlreadyParticipated(true);
                break;
            }
        }
    }
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;/*from  w w w  . j  av  a2 s.  c o  m*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }//from   w  w  w.  j av a  2 s  . c  o  m
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        // cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("=================parameter from request====================");
    Enumeration ereq = request.getParameterNames();
    while (ereq.hasMoreElements()) {
        String name = (String) ereq.nextElement();
        System.out.println(name + "[" + request.getParameter(name) + "]");
    }/*from w  w  w. jav a  2 s  . com*/
    System.out.println("=================end====================");

    String userTabaoId = request.getParameter("id");

    if (StringUtils.isEmpty(userTabaoId)) {
        userTabaoId = "1";
    }
    try {
        IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User _loginUser = mgr.getUserByTaobaoId(userTabaoId);

        addCookie(_loginUser, request, response);

        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            System.out.println("=====cookie is null=======");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                        + cookie.getMaxAge() + ")]");
            }

        }

        //request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, _loginUser);

        System.out.println("loginuser:" + _loginUser);

        response.sendRedirect(request.getContextPath());
        return;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

}