Example usage for io.netty.buffer ByteBuf setIndex

List of usage examples for io.netty.buffer ByteBuf setIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf setIndex.

Prototype

public abstract ByteBuf setIndex(int readerIndex, int writerIndex);

Source Link

Document

Sets the readerIndex and writerIndex of this buffer in one shot.

Usage

From source file:org.apache.camel.component.netty4.http.DefaultNettyHttpBinding.java

License:Apache License

@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();
    }/*from  ww  w.  java 2  s  .  com*/

    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ByteBuf buffer;
    // 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);

    LOG.trace("HTTP Status Code: {}", code);

    // 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 = NettyConverter.toByteBuffer(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 = NettyConverter.toByteBuffer(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 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.getBody(byte[].class);
            if (data != null) {
                buffer = NettyConverter.toByteBuffer(data);
            } else {
                // and if byte array fails then try String
                String str;
                if (body != null) {
                    str = message.getMandatoryBody(String.class);
                } else {
                    str = "";
                }
                buffer = NettyConverter.toByteBuffer(str.getBytes());
            }
        }
    }

    HttpResponse response = null;

    if (buffer != null) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), 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);
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
    }

    TypeConverter tc = message.getExchange().getContext().getTypeConverter();

    // append headers
    // 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);
            }
        }
    }

    // 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;
}

From source file:org.apache.tajo.plan.function.stream.CSVLineDeserializer.java

License:Apache License

public void deserialize(final ByteBuf lineBuf, Tuple output) throws IOException, TextLineParsingError {
    int[] projection = targetColumnIndexes;
    if (lineBuf == null || targetColumnIndexes == null || targetColumnIndexes.length == 0) {
        return;/*from   ww  w  .  j a  v a 2  s.  c o  m*/
    }

    final int rowLength = lineBuf.readableBytes();
    int start = 0, fieldLength = 0, end = 0;

    //Projection
    int currentTarget = 0;
    int currentIndex = 0;

    while (end != -1) {
        end = lineBuf.forEachByte(start, rowLength - start, processor);

        if (end < 0) {
            fieldLength = rowLength - start;
        } else {
            fieldLength = end - start - delimiterCompensation;
        }

        if (projection.length > currentTarget && currentIndex == projection[currentTarget]) {
            lineBuf.setIndex(start, start + fieldLength);
            Datum datum = fieldSerDer.deserialize(lineBuf, schema.getColumn(currentIndex), currentIndex,
                    nullChars);
            output.put(currentIndex, datum);
            currentTarget++;
        }

        if (projection.length == currentTarget) {
            break;
        }

        start = end + 1;
        currentIndex++;
    }
}

From source file:org.apache.tajo.storage.regex.RegexLineDeserializer.java

License:Apache License

@Override
public void deserialize(final ByteBuf lineBuf, Tuple output) throws IOException, TextLineParsingError {

    if (lineBuf == null || targetColumnIndexes.length == 0) {
        return;/*from w w w  .  j  a v a 2  s .  com*/
    }

    String line = decoder.decode(lineBuf.nioBuffer(lineBuf.readerIndex(), lineBuf.readableBytes())).toString();
    int[] projection = targetColumnIndexes;

    // Projection
    int currentTarget = 0;
    int currentIndex = 0;
    Matcher m = inputPattern.matcher(line);

    if (!m.matches()) {
        unmatchedRows++;
        if (unmatchedRows >= nextUnmatchedRows) {
            nextUnmatchedRows *= 100;
            // Report the row
            LOG.warn("" + unmatchedRows + " unmatched rows are found: " + line);
        }
    } else {

        int groupCount = m.groupCount();
        int currentGroup = 1;
        while (currentGroup <= groupCount) {

            if (projection.length > currentTarget && currentIndex == projection[currentTarget]) {

                try {
                    Datum datum = fieldSerDer.deserialize(currentIndex,
                            lineBuf.setIndex(m.start(currentGroup), m.end(currentGroup)), nullChars);

                    output.put(currentTarget, datum);
                } catch (Exception e) {
                    partialMatchedRows++;
                    if (partialMatchedRows >= nextPartialMatchedRows) {
                        nextPartialMatchedRows *= 100;
                        // Report the row
                        LOG.warn("" + partialMatchedRows + " partially unmatched rows are found, "
                                + " cannot find group " + currentIndex + ": " + line);
                    }
                    output.put(currentTarget, NullDatum.get());
                }
                currentTarget++;
            }

            if (projection.length == currentTarget) {
                break;
            }

            currentIndex++;
            currentGroup++;
        }
    }

    /* If a text row is less than table schema size, tuple should set to NullDatum */
    if (projection.length > currentTarget) {
        for (; currentTarget < projection.length; currentTarget++) {
            output.put(currentTarget, NullDatum.get());
        }
    }
}

From source file:org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput.java

License:Open Source License

@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {

    if (!open) {/* www  .jav  a 2  s.  co  m*/
        return null;
    }

    ByteBuffer top = queue.poll(READ_TIMEOUT, TimeUnit.MILLISECONDS);

    if (top == null) {
        // returning empty buffer instead of null causes flush (which is needed for BroadcasterTest and others..).
        return Unpooled.EMPTY_BUFFER;
    }

    if (top == VOID) {
        open = false;
        return null;
    }

    int topRemaining = top.remaining();
    ByteBuf buffer = allocator.buffer(topRemaining);

    buffer.setBytes(0, top);
    buffer.setIndex(0, topRemaining);

    if (top.remaining() > 0) {
        queue.addFirst(top);
    }

    offset += topRemaining;

    return buffer;
}