Search in sources :

Example 6 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project jersey by jersey.

the class NettyResponseWriter method writeResponseStatusAndHeaders.

@Override
public synchronized OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException {
    if (responseWritten) {
        LOGGER.log(Level.FINE, "Response already written.");
        return null;
    }
    responseWritten = true;
    String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
    int statusCode = responseContext.getStatus();
    HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode) : new HttpResponseStatus(statusCode, reasonPhrase);
    DefaultHttpResponse response;
    if (contentLength == 0) {
        response = new DefaultFullHttpResponse(req.protocolVersion(), status);
    } else {
        response = new DefaultHttpResponse(req.protocolVersion(), status);
    }
    for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
        response.headers().add(e.getKey(), e.getValue());
    }
    if (contentLength == -1) {
        HttpUtil.setTransferEncodingChunked(response, true);
    } else {
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }
    if (HttpUtil.isKeepAlive(req)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    ctx.writeAndFlush(response);
    if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {
        JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());
        if (HttpUtil.isTransferEncodingChunked(response)) {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        } else {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        }
        return jerseyChunkedInput;
    } else {
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        return null;
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) List(java.util.List) Map(java.util.Map) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput)

Example 7 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project asterixdb by apache.

the class HttpServerHandler method respond.

protected void respond(ChannelHandlerContext ctx, HttpVersion httpVersion, HttpResponseStatus status) {
    DefaultHttpResponse response = new DefaultHttpResponse(httpVersion, status);
    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse)

Example 8 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionClose.

@Test(dataProvider = "connectionClose")
public void testConnectionClose(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertTrue(pool.isDisposeCalled());
    Assert.assertFalse(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Example 9 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionKeepAlive.

@Test(dataProvider = "connectionKeepAlive")
public void testConnectionKeepAlive(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertFalse(pool.isDisposeCalled());
    Assert.assertTrue(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Example 10 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project camel by apache.

the class HttpServerChannelHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    LOG.debug("Message received: {}", request);
    if (consumer.isSuspended()) {
        // are we suspended?
        LOG.debug("Consumer suspended, cannot service request {}", request);
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // if its an OPTIONS request then return which methods is allowed
    boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
    if ("OPTIONS".equals(request.method().name()) && !isRestrictedToOptions) {
        String s;
        if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
            s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
        } else {
            // allow them all
            s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.headers().set("Allow", s);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.method().name())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    if ("TRACE".equals(request.method().name()) && !consumer.getEndpoint().isTraceEnabled()) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // must include HOST header as required by HTTP 1.1
    if (!request.headers().contains(HttpHeaderNames.HOST.toString())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
        //response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // is basic auth configured
    NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
    if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
        String url = request.uri();
        // drop parameters from url
        if (url.contains("?")) {
            url = ObjectHelper.before(url, "?");
        }
        // we need the relative path without the hostname and port
        URI uri = new URI(request.uri());
        String target = uri.getPath();
        // strip the starting endpoint path so the target is relative to the endpoint uri
        String path = consumer.getConfiguration().getPath();
        if (path != null && target.startsWith(path)) {
            // need to match by lower case as we want to ignore case on context-path
            path = path.toLowerCase(Locale.US);
            String match = target.toLowerCase(Locale.US);
            if (match.startsWith(path)) {
                target = target.substring(path.length());
            }
        }
        // is it a restricted resource?
        String roles;
        if (security.getSecurityConstraint() != null) {
            // if restricted returns null, then the resource is not restricted and we should not authenticate the user
            roles = security.getSecurityConstraint().restricted(target);
        } else {
            // assume any roles is valid if no security constraint has been configured
            roles = "*";
        }
        if (roles != null) {
            // basic auth subject
            HttpPrincipal principal = extractBasicAuthSubject(request);
            // authenticate principal and check if the user is in role
            Subject subject = null;
            boolean inRole = true;
            if (principal != null) {
                subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
                if (subject != null) {
                    String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                    inRole = matchesRoles(roles, userRoles);
                }
            }
            if (principal == null || subject == null || !inRole) {
                if (principal == null) {
                    LOG.debug("Http Basic Auth required for resource: {}", url);
                } else if (subject == null) {
                    LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                } else {
                    LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                }
                // restricted resource, so send back 401 to require valid username/password
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                ctx.writeAndFlush(response);
                // close the channel
                ctx.channel().close();
                return;
            } else {
                LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
            }
        }
    }
    // let Camel process this message
    super.channelRead0(ctx, msg);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) NettyHttpSecurityConfiguration(org.apache.camel.component.netty4.http.NettyHttpSecurityConfiguration) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) URI(java.net.URI) HttpPrincipal(org.apache.camel.component.netty4.http.HttpPrincipal) Subject(javax.security.auth.Subject)

Aggregations

DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)64 HttpResponse (io.netty.handler.codec.http.HttpResponse)34 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)23 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 HttpContent (io.netty.handler.codec.http.HttpContent)14 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)11 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)11 ChannelFuture (io.netty.channel.ChannelFuture)10 HttpRequest (io.netty.handler.codec.http.HttpRequest)10 ByteBuf (io.netty.buffer.ByteBuf)9 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)9 HttpObject (io.netty.handler.codec.http.HttpObject)9 RandomAccessFile (java.io.RandomAccessFile)9 Test (org.junit.Test)9 FileNotFoundException (java.io.FileNotFoundException)7 IOException (java.io.IOException)7 Channel (io.netty.channel.Channel)6 File (java.io.File)6 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)5 URL (java.net.URL)5