Example usage for io.netty.handler.codec.http HttpHeaders getHeader

List of usage examples for io.netty.handler.codec.http HttpHeaders getHeader

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders getHeader.

Prototype

@Deprecated
public static String getHeader(HttpMessage message, CharSequence name, String defaultValue) 

Source Link

Usage

From source file:com.cu.http.container.core.adaptor.NettyServletRequest.java

License:Apache License

@Override
public Locale getLocale() {
    String locale = HttpHeaders.getHeader(this.originalRequest, Names.ACCEPT_LANGUAGE,
            DEFAULT_LOCALE.toString());//from w  w w. j av  a2 s.c  o m
    return new Locale(locale);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./*from  w  w w .  j a  v a2  s. c o  m*/
 * @param content the content of the blob.
 * @return the blob ID of the blob.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private String postBlobAndVerify(HttpHeaders headers, ByteBuffer content)
        throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.POST, "/", headers, content);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    discardContent(responseParts, 1);
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    return blobId;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./*w  w w .j  a v a 2s.com*/
 * @param content the content of the blob.
 * @return the blob ID of the blob.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private String postBlobAndVerify(HttpHeaders headers, ByteBuffer content)
        throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.POST, "/", headers, content);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    discardContent(responseParts, 1);
    assertTrue("Channel should be active", HttpHeaders.isKeepAlive(response));
    return blobId;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Posts a blob with the given {@code headers} and {@code content}.
 * @param headers the headers required./* w w  w.j  a va  2 s.c  o m*/
 * @param content the content of the blob.
 * @param usermetadata the {@link ByteBuffer} that represents user metadata
 * @return the blob ID of the blob.
 * @throws Exception
 */
private String multipartPostBlobAndVerify(HttpHeaders headers, ByteBuffer content, ByteBuffer usermetadata)
        throws Exception {
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", headers);
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, content, usermetadata);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(encoder.finalizeRequest(), encoder, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.CREATED, response.getStatus());
    assertTrue("No Date header", HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE, null) != null);
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
    String blobId = HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION, null);

    if (blobId == null) {
        fail("postBlobAndVerify did not return a blob ID");
    }
    discardContent(responseParts, 1);
    assertTrue("Channel should be active", HttpHeaders.isKeepAlive(response));
    return blobId;
}

From source file:com.github.ambry.rest.NettyRequest.java

License:Open Source License

/**
 * Wraps the {@code request} in an implementation of {@link RestRequest} so that other layers can understand the
 * request./*  w  w w.  j  a  v a 2s . com*/
 * <p/>
 * Note on content size: The content size is deduced in the following order:-
 * 1. From the {@link RestUtils.Headers#BLOB_SIZE} header.
 * 2. If 1 fails, from the {@link HttpHeaders.Names#CONTENT_LENGTH} header.
 * 3. If 2 fails, it is set to -1 which means that the content size is unknown.
 * If content size is set in the header (i.e. not -1), the actual content size should match that value. Otherwise, an
 * exception will be thrown.
 * @param request the {@link HttpRequest} that needs to be wrapped.
 * @param nettyMetrics the {@link NettyMetrics} instance to use.
 * @throws IllegalArgumentException if {@code request} is null.
 * @throws RestServiceException if the {@link HttpMethod} defined in {@code request} is not recognized as a
 *                                {@link RestMethod}.
 */
public NettyRequest(HttpRequest request, NettyMetrics nettyMetrics) throws RestServiceException {
    if (request == null) {
        throw new IllegalArgumentException("Received null HttpRequest");
    }
    restRequestMetricsTracker.nioMetricsTracker.markRequestReceived();
    HttpMethod httpMethod = request.getMethod();
    if (httpMethod == HttpMethod.GET) {
        restMethod = RestMethod.GET;
    } else if (httpMethod == HttpMethod.POST) {
        restMethod = RestMethod.POST;
    } else if (httpMethod == HttpMethod.DELETE) {
        restMethod = RestMethod.DELETE;
    } else if (httpMethod == HttpMethod.HEAD) {
        restMethod = RestMethod.HEAD;
    } else {
        nettyMetrics.unsupportedHttpMethodError.inc();
        throw new RestServiceException("http method not supported: " + httpMethod,
                RestServiceErrorCode.UnsupportedHttpMethod);
    }
    this.request = request;
    this.query = new QueryStringDecoder(request.getUri());
    this.nettyMetrics = nettyMetrics;

    if (HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE, null) != null) {
        size = Long.parseLong(HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE));
    } else {
        size = HttpHeaders.getContentLength(request, -1);
    }

    // query params.
    for (Map.Entry<String, List<String>> e : query.parameters().entrySet()) {
        StringBuilder value = null;
        if (e.getValue() != null) {
            StringBuilder combinedValues = combineVals(new StringBuilder(), e.getValue());
            if (combinedValues.length() > 0) {
                value = combinedValues;
            }
        }
        allArgs.put(e.getKey(), value);
    }

    Set<io.netty.handler.codec.http.Cookie> nettyCookies = null;
    // headers.
    for (Map.Entry<String, String> e : request.headers()) {
        StringBuilder sb;
        if (e.getKey().equals(HttpHeaders.Names.COOKIE)) {
            String value = e.getValue();
            if (value != null) {
                nettyCookies = CookieDecoder.decode(value);
            }
        } else {
            boolean valueNull = request.headers().get(e.getKey()) == null;
            if (!valueNull && allArgs.get(e.getKey()) == null) {
                sb = new StringBuilder(e.getValue());
                allArgs.put(e.getKey(), sb);
            } else if (!valueNull) {
                sb = (StringBuilder) allArgs.get(e.getKey());
                sb.append(MULTIPLE_HEADER_VALUE_DELIMITER).append(e.getValue());
            } else if (!allArgs.containsKey(e.getKey())) {
                allArgs.put(e.getKey(), null);
            }
        }
    }

    // turn all StringBuilders into String
    for (Map.Entry<String, Object> e : allArgs.entrySet()) {
        if (allArgs.get(e.getKey()) != null) {
            allArgs.put(e.getKey(), (e.getValue()).toString());
        }
    }
    // add cookies to the args as java cookies
    if (nettyCookies != null) {
        Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies);
        allArgs.put(RestUtils.Headers.COOKIE, cookies);
    }
    allArgsReadOnly = Collections.unmodifiableMap(allArgs);
}

From source file:io.reactivex.netty.protocol.http.client.HttpRequestHeaders.java

License:Apache License

public String getHeader(CharSequence name, String defaultValue) {
    return HttpHeaders.getHeader(nettyRequest, name, defaultValue);
}

From source file:io.reactivex.netty.protocol.http.client.HttpRequestHeaders.java

License:Apache License

public String getHeader(String name, String defaultValue) {
    return HttpHeaders.getHeader(nettyRequest, name, defaultValue);
}

From source file:io.reactivex.netty.protocol.http.client.HttpResponseHeaders.java

License:Apache License

public String getHeader(CharSequence name, String defaultValue) {
    return HttpHeaders.getHeader(nettyResponse, name, defaultValue);
}

From source file:io.reactivex.netty.protocol.http.client.HttpResponseHeaders.java

License:Apache License

public String getHeader(String name, String defaultValue) {
    return HttpHeaders.getHeader(nettyResponse, name, defaultValue);
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private AtmosphereRequest createAtmosphereRequest(final ChannelHandlerContext ctx, final HttpRequest request,
        byte[] body) throws URISyntaxException, UnsupportedEncodingException, MalformedURLException {
    final String base = getBaseUri(request);
    final URI requestUri = new URI(base.substring(0, base.length() - 1) + request.getUri());
    final String ct = HttpHeaders.getHeader(request, "Content-Type", "text/plain");
    final long cl = HttpHeaders.getContentLength(request, 0);
    String method = request.getMethod().name();

    String queryString = requestUri.getQuery();
    Map<String, String[]> qs = new HashMap<String, String[]>();
    if (queryString != null) {
        parseQueryString(qs, queryString);
    }//  w w w . j  a v  a 2s.c  o m

    if (ct.equalsIgnoreCase("application/x-www-form-urlencoded")) {
        if (FullHttpRequest.class.isAssignableFrom(request.getClass())) {
            parseQueryString(qs, new String(body));
        }
    }

    String u = requestUri.toURL().toString();
    int last = u.indexOf("?") == -1 ? u.length() : u.indexOf("?");
    String url = u.substring(0, last);
    int l;

    if (url.contains(config.mappingPath())) {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3
                + config.mappingPath().length();
    } else {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3;
    }

    HttpSession session = null;
    if (framework.getAtmosphereConfig().isSupportSession()) {
        String[] transport = qs.get(HeaderConfig.X_ATMOSPHERE_TRANSPORT);
        if (transport != null && transport.length > 0) {
            String[] uuid = qs.get(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
            if (uuid != null && uuid.length > 0) {
                // TODO: Session is only supported until an unsubscribe is received.
                if (transport[0].equalsIgnoreCase(HeaderConfig.DISCONNECT_TRANSPORT_MESSAGE)) {
                    sessions.remove(uuid[0]);
                } else {
                    session = sessions.get(uuid[0]);

                    if (session == null) {
                        session = new FakeHttpSession("-1", null, System.currentTimeMillis(), -1);
                    }
                }
            }
        }
    }

    final Map<String, Object> attributes = new HashMap<String, Object>();
    AtmosphereRequestImpl.Builder requestBuilder = new AtmosphereRequestImpl.Builder();
    requestBuilder.requestURI(url.substring(l)).requestURL(url).pathInfo(url.substring(l))
            .headers(getHeaders(request)).method(method).contentType(ct).contentLength(cl)
            // We need to read attribute after doComet
            .destroyable(false).attributes(attributes).servletPath(config.mappingPath()).session(session)
            .cookies(getCookies(request)).queryStrings(qs)
            .remoteInetSocketAddress(new Callable<InetSocketAddress>() {
                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().remoteAddress();
                }
            }).localInetSocketAddress(new Callable<InetSocketAddress>() {

                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().localAddress();
                }
            });

    if (body.length > 0) {
        requestBuilder.body(body);
    }

    return requestBuilder.build();

}