Search in sources :

Example 96 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project camel by apache.

the class NettyConfiguration method parseURI.

public void parseURI(URI uri, Map<String, Object> parameters, NettyComponent component, String... supportedProtocols) throws Exception {
    protocol = uri.getScheme();
    boolean found = false;
    for (String supportedProtocol : supportedProtocols) {
        if (protocol != null && protocol.equalsIgnoreCase(supportedProtocol)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new IllegalArgumentException("Unrecognized Netty protocol: " + protocol + " for uri: " + uri);
    }
    setHost(uri.getHost());
    if (uri.getPort() != -1) {
        setPort(uri.getPort());
    }
    ssl = component.getAndRemoveOrResolveReferenceParameter(parameters, "ssl", boolean.class, false);
    sslHandler = component.getAndRemoveOrResolveReferenceParameter(parameters, "sslHandler", SslHandler.class, sslHandler);
    passphrase = component.getAndRemoveOrResolveReferenceParameter(parameters, "passphrase", String.class, passphrase);
    keyStoreFormat = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreFormat", String.class, keyStoreFormat == null ? "JKS" : keyStoreFormat);
    securityProvider = component.getAndRemoveOrResolveReferenceParameter(parameters, "securityProvider", String.class, securityProvider == null ? "SunX509" : securityProvider);
    keyStoreFile = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreFile", File.class, keyStoreFile);
    trustStoreFile = component.getAndRemoveOrResolveReferenceParameter(parameters, "trustStoreFile", File.class, trustStoreFile);
    keyStoreResource = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreResource", String.class, keyStoreResource);
    trustStoreResource = component.getAndRemoveOrResolveReferenceParameter(parameters, "trustStoreResource", String.class, trustStoreResource);
    clientPipelineFactory = component.getAndRemoveOrResolveReferenceParameter(parameters, "clientPipelineFactory", ClientPipelineFactory.class, clientPipelineFactory);
    serverPipelineFactory = component.getAndRemoveOrResolveReferenceParameter(parameters, "serverPipelineFactory", ServerPipelineFactory.class, serverPipelineFactory);
    // set custom encoders and decoders first
    List<ChannelHandler> referencedEncoders = component.resolveAndRemoveReferenceListParameter(parameters, "encoders", ChannelHandler.class, null);
    addToHandlersList(encoders, referencedEncoders, ChannelHandler.class);
    List<ChannelHandler> referencedDecoders = component.resolveAndRemoveReferenceListParameter(parameters, "decoders", ChannelHandler.class, null);
    addToHandlersList(decoders, referencedDecoders, ChannelHandler.class);
    // then set parameters with the help of the camel context type converters
    EndpointHelper.setReferenceProperties(component.getCamelContext(), this, parameters);
    EndpointHelper.setProperties(component.getCamelContext(), this, parameters);
    // additional netty options, we don't want to store an empty map, so set it as null if empty
    options = IntrospectionSupport.extractProperties(parameters, "option.");
    if (options != null && options.isEmpty()) {
        options = null;
    }
    // add default encoders and decoders
    if (encoders.isEmpty() && decoders.isEmpty()) {
        if (isAllowDefaultCodec()) {
            // are we textline or object?
            if (isTextline()) {
                Charset charset = getEncoding() != null ? Charset.forName(getEncoding()) : CharsetUtil.UTF_8;
                encoders.add(ChannelHandlerFactories.newStringEncoder(charset));
                ChannelBuffer[] delimiters = delimiter == TextLineDelimiter.LINE ? Delimiters.lineDelimiter() : Delimiters.nulDelimiter();
                decoders.add(ChannelHandlerFactories.newDelimiterBasedFrameDecoder(decoderMaxLineLength, delimiters));
                decoders.add(ChannelHandlerFactories.newStringDecoder(charset));
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using textline encoders and decoders with charset: {}, delimiter: {} and decoderMaxLineLength: {}", new Object[] { charset, delimiter, decoderMaxLineLength });
                }
            } else {
                // object serializable is then used
                encoders.add(ChannelHandlerFactories.newObjectEncoder());
                decoders.add(ChannelHandlerFactories.newObjectDecoder());
                LOG.debug("Using object encoders and decoders");
            }
        } else {
            LOG.debug("No encoders and decoders will be used");
        }
    } else {
        LOG.debug("Using configured encoders and/or decoders");
    }
}
Also used : Charset(java.nio.charset.Charset) ChannelHandler(org.jboss.netty.channel.ChannelHandler) File(java.io.File) SslHandler(org.jboss.netty.handler.ssl.SslHandler) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 97 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project camel by apache.

the class NettyConverter method toByteBuffer.

@Converter
public static ChannelBuffer toByteBuffer(byte[] bytes, Exchange exchange) {
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer(bytes.length);
    buf.writeBytes(bytes);
    return buf;
}
Also used : ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) Converter(org.apache.camel.Converter)

Example 98 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project camel by apache.

the class HttpClientChannelHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    // store response, as this channel handler is created per pipeline
    Object msg = messageEvent.getMessage();
    // it may be a chunked message
    if (msg instanceof HttpChunk) {
        HttpChunk chunk = (HttpChunk) msg;
        if (LOG.isTraceEnabled()) {
            LOG.trace("HttpChunk received: {} isLast: {}", chunk, chunk.isLast());
        }
        if (msg instanceof HttpChunkTrailer) {
            // chunk trailer only has headers
            HttpChunkTrailer trailer = (HttpChunkTrailer) msg;
            for (Map.Entry<String, String> entry : trailer.trailingHeaders()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Adding trailing header {}={}", entry.getKey(), entry.getValue());
                }
                response.headers().add(entry.getKey(), entry.getValue());
            }
        } else {
            // append chunked content
            buffer.writeBytes(chunk.getContent());
            if (LOG.isTraceEnabled()) {
                LOG.trace("Wrote {} bytes to chunk buffer", buffer.writerIndex());
            }
        }
        if (chunk.isLast()) {
            // the content is a copy of the buffer with the actual data we wrote to it
            int end = buffer.writerIndex();
            ChannelBuffer copy = buffer.copy(0, end);
            // the copy must not be readable when the content was chunked, so set the index to the end
            copy.setIndex(end, end);
            response.setContent(copy);
            // we get the all the content now, so call super to process the received message
            super.messageReceived(ctx, messageEvent);
        }
    } else if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        Exchange exchange = super.getExchange(ctx);
        if (!HttpHeaders.isKeepAlive(response)) {
            // just want to make sure we close the channel if the keepAlive is not true
            exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("HttpResponse received: {} chunked:", response, response.isChunked());
        }
        if (response.getStatus().getCode() == HttpResponseStatus.CONTINUE.getCode()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("HttpResponse received: {}: {}", response, response.getStatus());
            }
        } else if (!response.isChunked()) {
            // the response is not chunked so we have all the content
            super.messageReceived(ctx, messageEvent);
        } else {
            // the response is chunkced so use a dynamic buffer to receive the content in chunks
            buffer = ChannelBuffers.dynamicBuffer();
        }
    } else {
        // ignore not supported message
        if (LOG.isTraceEnabled() && msg != null) {
            LOG.trace("Ignoring non supported response message of type {} -> {}", msg.getClass(), msg);
        }
    }
}
Also used : Exchange(org.apache.camel.Exchange) HttpChunkTrailer(org.jboss.netty.handler.codec.http.HttpChunkTrailer) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Map(java.util.Map) HttpChunk(org.jboss.netty.handler.codec.http.HttpChunk) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 99 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project camel by apache.

the class DefaultNettyHttpBinding method toNettyResponse.

@Override
public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyResponse: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpResponse) {
        return (HttpResponse) message.getBody();
    }
    // the response code is 200 for OK and 500 for failed
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;
    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
    LOG.trace("HTTP Status Code: {}", code);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // 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();
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null);
        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);
                response.headers().add(key, headerValue);
            }
        }
    }
    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ChannelBuffer buffer;
    // if there was an exception then use that as body
    if (cause != null) {
        if (configuration.isTransferException()) {
            // we failed due an exception, and transfer it as java serialized object
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(cause);
            oos.flush();
            IOHelper.close(oos, bos);
            // the body should be the serialized java object of the exception
            body = ChannelBuffers.copiedBuffer(bos.toByteArray());
            // force content type to be serialized java object
            message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
        } else {
            // we failed due an exception so print it as plain text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            cause.printStackTrace(pw);
            // the body should then be the stacktrace
            body = ChannelBuffers.copiedBuffer(sw.toString().getBytes());
            // force content type to be text/plain as that is what the stacktrace is
            message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        }
        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }
    if (body instanceof ChannelBuffer) {
        buffer = (ChannelBuffer) body;
    } else {
        // try to convert to buffer first
        buffer = message.getBody(ChannelBuffer.class);
        if (buffer == null) {
            // fallback to byte array as last resort
            byte[] data = message.getBody(byte[].class);
            if (data != null) {
                buffer = ChannelBuffers.copiedBuffer(data);
            } else {
                // and if byte array fails then try String
                String str;
                if (body != null) {
                    str = message.getMandatoryBody(String.class);
                } else {
                    str = "";
                }
                buffer = ChannelBuffers.copiedBuffer(str.getBytes());
            }
        }
    }
    if (buffer != null) {
        response.setContent(buffer);
        // We just need to reset the readerIndex this time
        if (buffer.readerIndex() == buffer.writerIndex()) {
            buffer.setIndex(0, buffer.writerIndex());
        }
        // TODO How to enable the chunk transport 
        int len = buffer.readableBytes();
        // set content-length
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
        LOG.trace("Content-Length: {}", len);
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
    // Read the connection header from the exchange property
    if (connection == null) {
        connection = message.getExchange().getProperty(HttpHeaders.Names.CONNECTION, String.class);
    }
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaders.Values.KEEP_ALIVE;
        } else {
            connection = HttpHeaders.Values.CLOSE;
        }
    }
    response.headers().set(HttpHeaders.Names.CONNECTION, connection);
    // Just make sure we close the channel when the connection value is close
    if (connection.equalsIgnoreCase(HttpHeaders.Values.CLOSE)) {
        message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    LOG.trace("Connection: {}", connection);
    return response;
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 100 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project databus by linkedin.

the class ChunkedBodyReadableByteChannel method getChunk.

private boolean getChunk() {
    boolean result = false;
    _chunkQueueLock.lock();
    try {
        ChannelBuffer nextChunk = _chunks.poll();
        boolean doLoop = !_noMoreChunks;
        while (doLoop && null == nextChunk && !_noMoreChunks) {
            try {
                _hasChunksCondition.await();
            } catch (InterruptedException ie) {
                LOG.info("interrupted");
                doLoop = false;
            }
            if (!_open.get())
                break;
            nextChunk = _chunks.poll();
        }
        if (null != nextChunk) {
            _currentBuffer = nextChunk;
            if (0 == _currentBuffer.readableBytes())
                signalNoMoreChunksWithLock();
            if (0 == _chunks.size() || MAX_BUFFERED_CHUNKS - 1 == _chunks.size())
                _hasChunkSpaceCondition.signalAll();
            result = true;
        }
    } finally {
        _chunkQueueLock.unlock();
    }
    return result;
}
Also used : ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Aggregations

ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)312 Test (org.junit.Test)63 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)59 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)49 Test (org.testng.annotations.Test)49 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)46 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)43 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)37 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)34 Checkpoint (com.linkedin.databus.core.Checkpoint)27 ByteBuffer (java.nio.ByteBuffer)27 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)25 IOException (java.io.IOException)23 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)23 ArrayList (java.util.ArrayList)21 Channel (org.jboss.netty.channel.Channel)19 ChannelFuture (org.jboss.netty.channel.ChannelFuture)18 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)17 BlockLogBuffer (org.neo4j.com.BlockLogBuffer)16 Map (java.util.Map)14