Example usage for io.netty.handler.codec.http DefaultHttpRequest headers

List of usage examples for io.netty.handler.codec.http DefaultHttpRequest headers

Introduction

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

Prototype

@Override
    public HttpHeaders headers() 

Source Link

Usage

From source file:com.linecorp.armeria.server.tracing.HttpTracingServiceInvocationHandlerTest.java

License:Apache License

@Test
public void testGetTraceData() {
    DefaultHttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    httpRequest.headers().add(traceHeaders());

    ServiceInvocationContext ctx = mock(ServiceInvocationContext.class);
    when(ctx.originalRequest()).thenReturn(httpRequest);

    TraceData traceData = serviceInvocationHandler.getTraceData(ctx);
    assertThat(traceData.getSpanId(), is(testSpanId));
    assertThat(traceData.getSample(), is(true));
}

From source file:com.linecorp.armeria.server.tracing.HttpTracingServiceInvocationHandlerTest.java

License:Apache License

@Test
public void testGetTraceDataIfRequestIsNotContainTraceData() {
    DefaultHttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    httpRequest.headers().add(emptyHttpHeaders());

    ServiceInvocationContext ctx = mock(ServiceInvocationContext.class);
    when(ctx.originalRequest()).thenReturn(httpRequest);

    TraceData traceData = serviceInvocationHandler.getTraceData(ctx);
    assertThat(traceData.getSample(), is(nullValue()));
    assertThat(traceData.getSpanId(), is(nullValue()));
}

From source file:com.linecorp.armeria.server.tracing.HttpTracingServiceInvocationHandlerTest.java

License:Apache License

private static void testGetTraceDataIfRequestIsNotSampled(HttpHeaders headers) {
    DefaultHttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    httpRequest.headers().add(headers);

    ServiceInvocationContext ctx = mock(ServiceInvocationContext.class);
    when(ctx.originalRequest()).thenReturn(httpRequest);

    TraceData traceData = serviceInvocationHandler.getTraceData(ctx);
    assertThat(traceData.getSpanId(), is(nullValue()));
    assertThat(traceData.getSample(), is(false));
}

From source file:com.mastfrog.netty.http.client.RequestBuilder.java

License:Open Source License

public HttpRequest build() {
    if (url == null) {
        throw new IllegalStateException("URL not set");
    }/*from   w  w  w  . j a  v a  2 s. c om*/
    URL u = getURL();
    if (!u.isValid()) {
        if (u.getProblems() != null) {
            u.getProblems().throwIfFatalPresent();
        } else {
            throw new IllegalArgumentException("Invalid url " + u);
        }
    }
    if (u.getHost() == null) {
        throw new IllegalStateException("URL host not set: " + u);
    }
    String uri = u.getPathAndQuery();
    if (uri.isEmpty()) {
        uri = "/";
    }
    HttpMethod mth = HttpMethod.valueOf(method.name());
    DefaultHttpRequest h = body == null ? new DefaultHttpRequest(version, mth, uri)
            : new DefaultFullHttpRequest(version, mth, uri, body);
    for (Entry<?> e : entries) {
        e.addTo(h.headers());
    }
    if (!noHostHeader) {
        h.headers().add(HttpHeaders.Names.HOST, u.getHost().toString());
    }
    if (!h.headers().contains(HttpHeaders.Names.CONNECTION) && !noConnectionHeader) {
        h.headers().add(HttpHeaders.Names.CONNECTION, "close");
    }
    if (!noDateHeader) {
        h.headers().add(HttpHeaders.Names.DATE, Headers.DATE.toString(DateTime.now()));
    }
    if (store != null) {
        store.decorate(h);
    }
    return h;
}

From source file:io.crate.protocols.http.HttpAuthUpstreamHandlerTest.java

@Test
public void testNotNoHbaConfig() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);

    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
    request.headers().add("X-Real-Ip", "10.1.0.100");

    ch.writeInbound(request);/*from  w  w  w .  j a  v  a2 s . c  om*/
    assertFalse(handler.authorized());

    assertUnauthorized(ch.readOutbound(),
            "No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\"\n");
}

From source file:io.liveoak.container.protocols.http.HttpResourceRequestDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DefaultHttpRequest msg, List<Object> out) throws Exception {

    URI uri = new URI(msg.getUri());
    String query = uri.getRawQuery();
    if (query == null) {
        query = "?";
    } else {//from   w w  w.  ja  v  a 2 s .  c  o m
        query = "?" + query;
    }

    QueryStringDecoder decoder = new QueryStringDecoder(query);

    String path = uri.getPath();

    int lastDotLoc = path.lastIndexOf('.');

    String extension = null;

    if (lastDotLoc > 0) {
        extension = path.substring(lastDotLoc + 1);
    }

    String acceptHeader = msg.headers().get(HttpHeaders.Names.ACCEPT);
    if (acceptHeader == null) {
        acceptHeader = "application/json";
    }
    MediaTypeMatcher mediaTypeMatcher = new DefaultMediaTypeMatcher(acceptHeader, extension);

    ResourceParams params = DefaultResourceParams.instance(decoder.parameters());

    // for cases when content is preset, and bypasses HttpRequestBodyHandler
    ByteBuf content = null;
    if (msg instanceof DefaultFullHttpRequest) {
        content = ((DefaultFullHttpRequest) msg).content().retain();
    }

    if (msg.getMethod().equals(HttpMethod.POST)) {
        String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE);
        MediaType contentType = new MediaType(contentTypeHeader);
        out.add(new DefaultResourceRequest.Builder(RequestType.CREATE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType)
                .requestAttribute(HTTP_REQUEST, msg)
                .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build());
    } else if (msg.getMethod().equals(HttpMethod.GET)) {
        out.add(new DefaultResourceRequest.Builder(RequestType.READ, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader))
                .requestAttribute(HTTP_REQUEST, msg).pagination(decodePagination(params))
                .returnFields(decodeReturnFields(params)).sorting(decodeSorting(params)).build());
    } else if (msg.getMethod().equals(HttpMethod.PUT)) {
        String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE);
        MediaType contentType = new MediaType(contentTypeHeader);
        out.add(new DefaultResourceRequest.Builder(RequestType.UPDATE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType)
                .requestAttribute(HTTP_REQUEST, msg)
                .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build());
    } else if (msg.getMethod().equals(HttpMethod.DELETE)) {
        out.add(new DefaultResourceRequest.Builder(RequestType.DELETE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader))
                .requestAttribute(HTTP_REQUEST, msg).build());
    }
}

From source file:io.liveoak.container.protocols.websocket.WebSocketHandshakerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        DefaultHttpRequest req = (DefaultHttpRequest) msg;
        String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
        if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
            // ensure FullHttpRequest by installing HttpObjectAggregator in front of this handler
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToWebSocketsHandshake(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        } else {// w  ww  .  ja v  a 2  s  . c om
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToPlainHttp(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        }
    } else {
        // do the handshake
        FullHttpRequest req = (FullHttpRequest) msg;
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.getUri(), null,
                false);
        WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            ChannelFuture future = handshaker.handshake(ctx.channel(), req);
            future.addListener(f -> {
                this.configurator.switchToWebSockets(ctx.pipeline());
            });
        }
    }
}

From source file:io.reactivex.netty.contexts.http.ClientHandlerTest.java

License:Apache License

private static void sendRequestAndAssert(HandlerHolder holder) throws Exception {
    holder.correlator.onNewServerRequest(holder.requestId, new ContextsContainerImpl(holder.keySupplier));

    try {/*from w w  w  .  j av a  2 s . c o m*/
        DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        holder.addSerializedContext(request, CTX_1_NAME, CTX_1_VAL, new BidirectionalTestContextSerializer());
        holder.handler.write(holder.ctx, request, holder.ctx.newPromise());

        Assert.assertNotNull("Context container not set after request sent.",
                ContextAttributeStorageHelper.getContainer(holder.ctx, holder.requestId));

        ContextKeySupplier supplier = new HttpContextKeySupplier(request.headers());
        ContextsContainer container = new ContextsContainerImpl(supplier);

        Assert.assertEquals("Context not available in the container.", CTX_1_VAL,
                container.getContext(CTX_1_NAME));
        Assert.assertEquals("Request Id header not added.", holder.getRequestId(),
                request.headers().get(holder.getProvider().getRequestIdContextKeyName()));
    } finally {
        holder.correlator.onServerProcessingEnd(holder.requestId);
        System.err.println("Sent server processing end callback to correlator.");
        RxContexts.DEFAULT_CORRELATOR.dumpThreadState(System.err);
    }
}

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

License:Apache License

@Test
public void testSetCookie() throws Exception {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    Cookie cookie = new DefaultCookie(cookie1Name, cookie1Value);
    cookie.setPath(cookie1Path);/*from w  w  w. j a  v  a  2  s  .  c  o m*/
    cookie.setDomain(cookie1Domain);
    new HttpClientRequest<ByteBuf>(nettyRequest).withCookie(cookie);
    String cookieHeader = nettyRequest.headers().get(HttpHeaders.Names.COOKIE);
    Assert.assertNotNull("No cookie header found.", cookieHeader);
    Set<Cookie> decodeCookies = CookieDecoder.decode(cookieHeader);
    Assert.assertNotNull("No cookie found with name.", decodeCookies);
    Assert.assertEquals("Unexpected number of cookies.", 1, decodeCookies.size());
    Cookie decodedCookie = decodeCookies.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, decodedCookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, decodedCookie.getPath());
    Assert.assertEquals("Unexpected cookie domain.", cookie1Domain, decodedCookie.getDomain());
}

From source file:io.reactivex.netty.protocol.http.server.CookieTest.java

License:Apache License

@Test
public void testGetCookie() throws Exception {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    String cookie1Header = cookie1Name + '=' + cookie1Value + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path="
            + cookie1Path + "; domain=" + cookie1Domain;
    nettyRequest.headers().add(HttpHeaders.Names.COOKIE, cookie1Header);
    HttpServerRequest<ByteBuf> request = new HttpServerRequest<ByteBuf>(nettyRequest,
            PublishSubject.<ByteBuf>create());
    Map<String, Set<Cookie>> cookies = request.getCookies();
    Assert.assertEquals("Unexpected number of cookies.", 1, cookies.size());
    Set<Cookie> cookies1 = cookies.get(cookie1Name);
    Assert.assertNotNull("No cookie found with name: " + cookie1Name, cookies1);
    Assert.assertEquals("Unexpected number of cookies with name: " + cookie1Name, 1, cookies1.size());
    Cookie cookie = cookies1.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, cookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, cookie.getPath());
}