Example usage for io.netty.handler.codec.http.cookie Cookie name

List of usage examples for io.netty.handler.codec.http.cookie Cookie name

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.cookie Cookie name.

Prototype

String name();

Source Link

Document

Returns the name of this Cookie .

Usage

From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java

License:Apache License

private Map<String, Cookie> getCookies() {
    if (AssertUtil.isNull(cookiesMap)) {
        cookiesMap = new HashMap<>();
        //https://tools.ietf.org/html/rfc6265#section-5.4 Cookie Header?
        String cookieStrs = headers().get(HttpHeaders.Names.COOKIE);
        if (StringTools.isNotEmpty(cookieStrs)) {
            Set<Cookie> cookies = cookieDecoder.decode(cookieStrs);
            if (AssertUtil.isNotEmptyCollection(cookies)) {
                for (Cookie cookie : cookies) {
                    cookiesMap.put(cookie.name(), cookie);
                }/*from  ww  w  . ja  v  a2s  .c  o m*/
            }
        } else {
            return Collections.EMPTY_MAP;
        }
    }
    return cookiesMap;
}

From source file:com.bay1ts.bay.core.Request.java

License:Apache License

/**
 * @return request cookies (or empty Map if cookies aren't present)
 *///from  www.  ja v  a 2 s.  c  o m
public Map<String, String> cookies() {
    Map<String, String> result = new HashMap<>();
    String cookieString = fullHttpRequest.headers().get(HttpHeaderNames.COOKIE);
    Set<Cookie> cookieSet = null;
    if (cookieString != null) {
        cookieSet = ServerCookieDecoder.LAX.decode(cookieString);
    }
    if (cookieSet != null && !cookieSet.isEmpty()) {
        for (Cookie cookie : cookieSet) {
            result.put(cookie.name(), cookie.value());
        }
    }
    //        Cookie[] cookies = fullHttpRequest.getCookies();
    //        if (cookies != null) {
    //            for (Cookie cookie : cookies) {
    //                result.put(cookie.name(), cookie.value());
    //            }
    //        }
    return result;
}

From source file:com.bay1ts.bay.core.Request.java

License:Apache License

/**
 * Gets cookie by name./*  w  w  w  .  jav a  2s  . com*/
 *
 * @param name name of the cookie
 * @return cookie value or null if the cookie was not found
 */
public String cookie(String name) {
    String cookieString = fullHttpRequest.headers().get(HttpHeaderNames.COOKIE);
    Set<Cookie> cookieSet = null;
    if (cookieString != null) {
        cookieSet = ServerCookieDecoder.LAX.decode(cookieString);
    }
    if (cookieSet != null && !cookieSet.isEmpty()) {
        for (Cookie cookie : cookieSet) {
            if (cookie.name().equals(name)) {
                return cookie.value();
            }
        }
    }
    return null;
}

From source file:com.vmware.xenon.common.http.netty.CookieJar.java

License:Open Source License

/**
 * List cookies that apply for the given request URI.
 *
 * @param uri request URI//w  w w.jav  a2  s  .  co m
 */
public Map<String, String> list(URI uri) {
    Map<String, String> result = new HashMap<>();

    // Find cookies by the request URI
    String origin = buildOrigin(uri);
    Set<Cookie> byOrigin = this.cookiesByOrigin.get(origin);
    if (byOrigin != null) {
        for (Cookie cookie : byOrigin) {
            // Only add "secure" cookies if request URI has https scheme
            if (cookie.isSecure() && !uri.getScheme().equals(URI_SCHEME_HTTPS)) {
                continue;
            }

            result.put(cookie.name(), cookie.value());
        }
    }

    return result;
}

From source file:com.vmware.xenon.services.common.authn.TestBasicAuthenticationService.java

License:Open Source License

private boolean validateAuthToken(Operation op) {
    String cookieHeader = op.getResponseHeader(SET_COOKIE_HEADER);
    if (cookieHeader == null) {
        this.host.failIteration(new IllegalStateException("Missing cookie header"));
        return false;
    }// www .  j  ava2 s . c o  m

    Cookie tokenCookie = ClientCookieDecoder.LAX.decode(cookieHeader);
    if (!AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE.equals(tokenCookie.name())) {
        this.host.failIteration(new IllegalStateException("Missing auth cookie"));
        return false;
    }

    if (op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER) == null) {
        this.host.failIteration(new IllegalStateException("Missing auth token"));
        return false;
    }

    String authCookie = tokenCookie.value();
    String authToken = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);

    if (!authCookie.equals(authToken)) {
        this.host.failIteration(new IllegalStateException("Auth token and auth cookie don't match"));
        return false;
    }
    return true;
}

From source file:gribbit.http.request.Request.java

License:Open Source License

public Request(ChannelHandlerContext ctx, HttpRequest httpReq) throws ResponseException {
    this.reqReceivedTimeEpochMillis = System.currentTimeMillis();

    this.httpRequest = httpReq;
    HttpHeaders headers = httpReq.headers();

    // Netty changes the URI of the request to "/bad-request" if the HTTP request was malformed
    this.rawURL = httpReq.uri();
    if (rawURL.equals("/bad-request")) {
        throw new BadRequestException();
    } else if (rawURL.isEmpty()) {
        rawURL = "/";
    }/*w ww .  j  a v a2s . c  o  m*/

    // Decode the URL
    RequestURL requestURL = new RequestURL(rawURL);
    this.normalizedURL = requestURL.getNormalizedPath();
    this.queryParamToVals = requestURL.getQueryParams();

    // TODO: figure out how to detect HTTP/2 connections
    this.httpVersion = httpReq.protocolVersion().toString();

    // Get HTTP2 stream ID
    this.streamId = headers.getAsString(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());

    this.isSecure = ctx.pipeline().get(SslHandler.class) != null; // TODO: is this correct for HTTP2?

    // Decode cookies
    try {
        for (CharSequence cookieHeader : headers.getAll(COOKIE)) {
            for (Cookie cookie : ServerCookieDecoder.STRICT.decode(cookieHeader.toString())) {
                // Log.fine("Cookie in request: " + nettyCookie);
                if (cookieNameToCookies == null) {
                    cookieNameToCookies = new HashMap<>();
                }
                String cookieName = cookie.name();

                // Multiple cookies may be present in the request with the same name but with different paths
                ArrayList<Cookie> cookiesWithThisName = cookieNameToCookies.get(cookieName);
                if (cookiesWithThisName == null) {
                    cookieNameToCookies.put(cookieName, cookiesWithThisName = new ArrayList<>());
                }
                cookiesWithThisName.add(cookie);
            }
        }
    } catch (IllegalArgumentException e) {
        // Malformed cookies cause ServerCookieDecoder to throw IllegalArgumentException
        // Log.info("Malformed cookie in request");
        throw new BadRequestException();
    }
    // Sort cookies into decreasing order of path length, in case client doesn't conform to RFC6295,
    // delivering the cookies in this order itself. This allows us to get the most likely single
    // cookie for a given cookie name by reading the first cookie in a list for a given name.
    if (cookieNameToCookies != null) {
        for (Entry<String, ArrayList<Cookie>> ent : cookieNameToCookies.entrySet()) {
            Collections.sort(ent.getValue(), COOKIE_COMPARATOR);
        }
    }

    this.method = httpReq.method();

    // Force the GET method if HEAD is requested
    this.isHEADRequest = this.method == HttpMethod.HEAD;
    if (this.isHEADRequest) {
        this.method = HttpMethod.GET;
    }

    this.isKeepAlive = HttpUtil.isKeepAlive(httpReq) && httpReq.protocolVersion().equals(HttpVersion.HTTP_1_0);

    CharSequence host = headers.get(HOST);
    this.host = host == null ? null : host.toString();

    this.xRequestedWith = headers.get("X-Requested-With");
    this.accept = headers.get(ACCEPT);
    this.acceptCharset = headers.get(ACCEPT_CHARSET);
    this.acceptLanguage = headers.get(ACCEPT_LANGUAGE);
    this.origin = headers.get(ORIGIN);
    this.referer = headers.get(REFERER);
    this.userAgent = headers.get(USER_AGENT);

    InetSocketAddress requestorSocketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
    if (requestorSocketAddr != null) {
        InetAddress address = requestorSocketAddr.getAddress();
        if (address != null) {
            this.requestor = address.getHostAddress();
        }
    }

    CharSequence acceptEncoding = headers.get(ACCEPT_ENCODING);
    this.acceptEncodingGzip = acceptEncoding != null
            && acceptEncoding.toString().toLowerCase().contains("gzip");

    this.ifModifiedSince = headers.get(IF_MODIFIED_SINCE);
    if (this.ifModifiedSince != null && this.ifModifiedSince.length() > 0) {
        this.ifModifiedSinceEpochSecond = ZonedDateTime
                .parse(this.ifModifiedSince, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond();
    }

    //        // If this is a hash URL, look up original URL whose served resource was hashed to give this hash URL.
    //        // We only need to serve the resource at a hash URL once per resource per client, since resources served
    //        // from hash URLs are indefinitely cached in the browser.
    //        // TODO: Move cache-busting out of http package
    //        this.urlHashKey = CacheExtension.getHashKey(this.urlPath);
    //        this.urlPathUnhashed = this.urlHashKey != null ? CacheExtension.getOrigURL(this.urlPath) : this.urlPath;

    //        // Get flash messages from cookie, if any
    //        this.flashMessages = FlashMessage.fromCookieString(getCookieValue(Cookie.FLASH_COOKIE_NAME));
}

From source file:gribbit.http.response.Response.java

License:Open Source License

/**
 * Set a cookie in the response./*from w w  w  . j  av  a  2s. co  m*/
 * 
 * (As per RFC6295, the server can only return one cookie with a given name per response. We arbitrarily choose
 * the last value the cookie is set to as the one that is sent in the response, even if setCookie is called
 * multiple times for a given cookie name with different paths.)
 */
public Response setCookie(Cookie cookie) {
    if (cookies == null) {
        cookies = new HashMap<>();
    }
    cookies.put(cookie.name(), cookie);
    return this;
}

From source file:gribbit.http.response.Response.java

License:Open Source License

/**
 * Look through the request for cookies with the given name, and delete any matches in the response. (i.e. can
 * only delete cookies that are actually visible in the request.) Note that per RFC6295, the client should be
 * sending cookies in order of decreasing path length, and also the server can only send one Set-Cookie header
 * per cookie name, so if there are multiple matches, only the last match (the one with the shortest path) will
 * be deleted when the response is set, and you'll need to return multiple responses with the same deleteCookie
 * action applied to delete them all.//from ww  w  .  j  av  a2 s  . c  o m
 */
public Response deleteCookie(String cookieName) {
    ArrayList<Cookie> reqCookies = request.getCookies(cookieName);
    if (reqCookies != null) {
        Cookie firstCookie = reqCookies.iterator().next();
        setCookie(firstCookie.name(), /* value = */"", /* path = */firstCookie.path(), /* maxAgeSeconds = */
                0, /* httpOnly = */false);
    }
    return this;
}

From source file:io.syncframework.netty.RequestWrapper.java

License:Apache License

public void setRequest(HttpRequest request) {
    this.request = request;
    this.session = null;

    ///*  ww w.j  a  va 2  s  .com*/
    // setting headers...
    //
    for (Entry<String, String> entry : request.headers()) {
        String name = entry.getKey();
        String value = entry.getValue();

        if (log.isTraceEnabled())
            log.trace("header: {} -> {}", name, value);

        if (name.toLowerCase().equals(HttpHeaderNames.COOKIE.toString())) {
            ServerCookieDecoder decoder = ServerCookieDecoder.STRICT;
            Set<Cookie> cookies = decoder.decode(value);
            for (Cookie cookie : cookies) {
                cookieContext.put(cookie.name(), cookie.value());
            }
            continue;
        }

        List<String> values = headers.get(name);
        if (values == null) {
            values = new LinkedList<String>();
        }
        values.add(entry.getValue());
        headers.put(name, values);
    }

    //
    // parameters from the URL
    //
    QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
    Map<String, List<String>> uriAttributes = decoderQuery.parameters();
    for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
        parameters.put(attr.getKey(), attr.getValue());
    }
}

From source file:io.vertx.ext.web.client.impl.CookieStoreImpl.java

License:Open Source License

@Override
public Iterable<Cookie> get(Boolean ssl, String domain, String path) {
    assert domain != null && domain.length() > 0;

    String cleanPath;/*from  w w  w  .  j  av a 2 s  .co  m*/
    {
        String uri = HttpUtils.removeDots(path);
        // Remoe query params if present
        int pos = uri.indexOf('?');
        if (pos > -1) {
            uri = uri.substring(0, pos);
        }

        // Remoe frament identifier if present
        pos = uri.indexOf('#');
        if (pos > -1) {
            uri = uri.substring(0, pos);
        }
        cleanPath = uri;
    }

    TreeMap<String, Cookie> matches = new TreeMap<>();

    Consumer<Cookie> adder = c -> {
        if (ssl != Boolean.TRUE && c.isSecure()) {
            return;
        }
        if (c.path() != null && !cleanPath.equals(c.path())) {
            String cookiePath = c.path();
            if (!cookiePath.endsWith("/")) {
                cookiePath += '/';
            }
            if (!cleanPath.startsWith(cookiePath)) {
                return;
            }
        }
        matches.put(c.name(), c);
    };

    for (Cookie c : noDomainCookies.values()) {
        adder.accept(c);
    }

    Key key = new Key(domain, "", "");
    String prefix = key.domain.substring(0, 1);
    for (Entry<Key, Cookie> entry : domainCookies.tailMap(new Key(prefix, "", ""), true).entrySet()) {
        if (entry.getKey().domain.compareTo(key.domain) > 0) {
            break;
        }
        if (!key.domain.startsWith(entry.getKey().domain)) {
            continue;
        }
        adder.accept(entry.getValue());
    }

    return matches.values();
}