Search in sources :

Example 81 with ByteBuf

use of io.netty.buffer.ByteBuf in project grpc-java by grpc.

the class NettyTestUtil method compressionFrame.

static ByteBuf compressionFrame(byte[] data) {
    ByteBuf buf = Unpooled.buffer();
    buf.writeByte(0);
    buf.writeInt(data.length);
    buf.writeBytes(data);
    return buf;
}
Also used : ByteBuf(io.netty.buffer.ByteBuf)

Example 82 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class NettyConverter method toByteBuffer.

@Converter
public static ByteBuf toByteBuffer(byte[] bytes) {
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(bytes.length);
    buf.writeBytes(bytes);
    return buf;
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) Converter(org.apache.camel.Converter)

Example 83 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class DefaultNettyHttpBinding method toNettyRequest.

@Override
public HttpRequest toNettyRequest(Message message, String uri, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyRequest: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpRequest) {
        return (HttpRequest) message.getBody();
    }
    String uriForRequest = uri;
    if (configuration.isUseRelativePath()) {
        int indexOfPath = uri.indexOf((new URI(uri)).getPath());
        if (indexOfPath > 0) {
            uriForRequest = uri.substring(indexOfPath);
        }
    }
    // just assume GET for now, we will later change that to the actual method to use
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriForRequest);
    Object body = message.getBody();
    if (body != null) {
        // support bodies as native Netty
        ByteBuf buffer;
        if (body instanceof ByteBuf) {
            buffer = (ByteBuf) body;
        } else {
            // try to convert to buffer first
            buffer = message.getBody(ByteBuf.class);
            if (buffer == null) {
                // fallback to byte array as last resort
                byte[] data = message.getMandatoryBody(byte[].class);
                buffer = NettyConverter.toByteBuffer(data);
            }
        }
        if (buffer != null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriForRequest, buffer);
            int len = buffer.readableBytes();
            // set content-length
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len);
            LOG.trace("Content-Length: {}", len);
        } else {
            // we do not support this kind of body
            throw new NoTypeConversionAvailableException(body, ByteBuf.class);
        }
    }
    // update HTTP method accordingly as we know if we have a body or not
    HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
    request.setMethod(method);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (configuration.isBridgeEndpoint()) {
        String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
        // Need to remove the Host key as it should be not used
        message.getHeaders().remove("host");
    }
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
        if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
            continue;
        }
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                request.headers().add(key, headerValue);
            }
        }
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        request.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // must include HOST header as required by HTTP 1.1
    // use URI as its faster than URL (no DNS lookup)
    URI u = new URI(uri);
    String hostHeader = u.getHost() + (u.getPort() == 80 ? "" : ":" + u.getPort());
    request.headers().set(HttpHeaderNames.HOST.toString(), hostHeader);
    LOG.trace("Host: {}", hostHeader);
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class);
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaderValues.KEEP_ALIVE.toString();
        } else {
            connection = HttpHeaderValues.CLOSE.toString();
        }
    }
    request.headers().set(HttpHeaderNames.CONNECTION.toString(), connection);
    LOG.trace("Connection: {}", connection);
    return request;
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) ByteBuf(io.netty.buffer.ByteBuf) URI(java.net.URI) TypeConverter(org.apache.camel.TypeConverter) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 84 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class HttpServerChannelHandler method extractBasicAuthSubject.

/**
     * Extracts the username and password details from the HTTP basic header Authorization.
     * <p/>
     * This requires that the <tt>Authorization</tt> HTTP header is provided, and its using Basic.
     * Currently Digest is <b>not</b> supported.
     *
     * @return {@link HttpPrincipal} with username and password details, or <tt>null</tt> if not possible to extract
     */
protected static HttpPrincipal extractBasicAuthSubject(HttpRequest request) {
    String auth = request.headers().get("Authorization");
    if (auth != null) {
        String constraint = ObjectHelper.before(auth, " ");
        if (constraint != null) {
            if ("Basic".equalsIgnoreCase(constraint.trim())) {
                String decoded = ObjectHelper.after(auth, " ");
                // the decoded part is base64 encoded, so we need to decode that
                ByteBuf buf = NettyConverter.toByteBuffer(decoded.getBytes());
                ByteBuf out = Base64.decode(buf);
                try {
                    String userAndPw = out.toString(Charset.defaultCharset());
                    String username = ObjectHelper.before(userAndPw, ":");
                    String password = ObjectHelper.after(userAndPw, ":");
                    HttpPrincipal principal = new HttpPrincipal(username, password);
                    LOG.debug("Extracted Basic Auth principal from HTTP header: {}", principal);
                    return principal;
                } finally {
                    buf.release();
                    out.release();
                }
            }
        }
    }
    return null;
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) HttpPrincipal(org.apache.camel.component.netty4.http.HttpPrincipal)

Example 85 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class DatagramPacketObjectDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf) msg.content();
        Object result = delegateDecoder.decode(ctx, payload);
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<Object, InetSocketAddress>(result, msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)1557 Test (org.junit.Test)668 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)162 IOException (java.io.IOException)99 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)89 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)81 Test (org.testng.annotations.Test)68 InetSocketAddress (java.net.InetSocketAddress)60 Channel (io.netty.channel.Channel)57 ChannelFuture (io.netty.channel.ChannelFuture)56 ArrayList (java.util.ArrayList)55 Map (java.util.Map)45 ChannelPromise (io.netty.channel.ChannelPromise)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)36 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)35 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 HashMap (java.util.HashMap)34 CountDownLatch (java.util.concurrent.CountDownLatch)34 RecyclableDuplicateByteBuf (io.netty.buffer.RecyclableDuplicateByteBuf)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32