Search in sources :

Example 31 with CharBuffer

use of java.nio.CharBuffer in project netty by netty.

the class Unpooled method copiedBuffer.

/**
     * Creates a new big-endian buffer whose content is a subregion of
     * the specified {@code string} encoded in the specified {@code charset}.
     * The new buffer's {@code readerIndex} and {@code writerIndex} are
     * {@code 0} and the length of the encoded string respectively.
     */
public static ByteBuf copiedBuffer(CharSequence string, int offset, int length, Charset charset) {
    if (string == null) {
        throw new NullPointerException("string");
    }
    if (length == 0) {
        return EMPTY_BUFFER;
    }
    if (string instanceof CharBuffer) {
        CharBuffer buf = (CharBuffer) string;
        if (buf.hasArray()) {
            return copiedBuffer(buf.array(), buf.arrayOffset() + buf.position() + offset, length, charset);
        }
        buf = buf.slice();
        buf.limit(length);
        buf.position(offset);
        return copiedBuffer(buf, charset);
    }
    return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset);
}
Also used : CharBuffer(java.nio.CharBuffer)

Example 32 with CharBuffer

use of java.nio.CharBuffer in project graphdb by neo4j-attic.

the class AbstractDynamicStore method allocateRecords.

public Collection<DynamicRecord> allocateRecords(long startBlock, char[] src) {
    assert getFileChannel() != null : "Store closed, null file channel";
    assert src != null : "Null src argument";
    List<DynamicRecord> recordList = new LinkedList<DynamicRecord>();
    long nextBlock = startBlock;
    long prevBlock = Record.NO_PREV_BLOCK.intValue();
    int srcOffset = 0;
    int dataSize = getBlockSize() - BLOCK_HEADER_SIZE;
    do {
        DynamicRecord record = new DynamicRecord(nextBlock);
        record.setCreated();
        record.setInUse(true);
        assert prevBlock != nextBlock;
        record.setPrevBlock(prevBlock);
        if ((src.length - srcOffset) * 2 > dataSize) {
            byte[] data = new byte[dataSize];
            CharBuffer charBuf = ByteBuffer.wrap(data).asCharBuffer();
            charBuf.put(src, srcOffset, dataSize / 2);
            record.setData(data);
            prevBlock = nextBlock;
            nextBlock = nextBlockId();
            record.setNextBlock(nextBlock);
            srcOffset += dataSize / 2;
        } else {
            if (srcOffset == 0) {
                record.setCharData(src);
            } else {
                byte[] data = new byte[(src.length - srcOffset) * 2];
                CharBuffer charBuf = ByteBuffer.wrap(data).asCharBuffer();
                charBuf.put(src, srcOffset, src.length - srcOffset);
                record.setData(data);
            }
            nextBlock = Record.NO_NEXT_BLOCK.intValue();
            record.setNextBlock(nextBlock);
        }
        recordList.add(record);
    } while (nextBlock != Record.NO_NEXT_BLOCK.intValue());
    return recordList;
}
Also used : CharBuffer(java.nio.CharBuffer) LinkedList(java.util.LinkedList)

Example 33 with CharBuffer

use of java.nio.CharBuffer in project platformlayer by platformlayer.

the class CsrParser method tryDecodeAsString.

private String tryDecodeAsString(byte[] data) {
    try {
        // We do this so we get strict input processing
        CharsetDecoder decoder = Charsets.UTF_8.newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPORT);
        decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        CharBuffer charBuffer = decoder.decode(byteBuffer);
        return charBuffer.toString();
    } catch (Exception e) {
        log.debug("Cannot decode as string", e);
        return null;
    }
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException)

Example 34 with CharBuffer

use of java.nio.CharBuffer in project platformlayer by platformlayer.

the class KeyParser method tryDecodeAsString.

private String tryDecodeAsString(byte[] data) {
    try {
        CharsetDecoder decoder = Utf8.CHARSET.newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPORT);
        decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        CharBuffer charBuffer = decoder.decode(byteBuffer);
        return charBuffer.toString();
    } catch (Exception e) {
        log.debug("Cannot decode as string", e);
        return null;
    }
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) ByteBuffer(java.nio.ByteBuffer)

Example 35 with CharBuffer

use of java.nio.CharBuffer in project ratpack by ratpack.

the class NettyHandlerAdapter method newRequest.

private void newRequest(final ChannelHandlerContext ctx, final HttpRequest nettyRequest) throws Exception {
    if (!nettyRequest.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());
    //Find the content length we will use this as an indicator of a body
    Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);
    String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);
    //If there is a content length or transfer encoding that indicates there is a body
    boolean hasBody = (contentLength > 0) || (transferEncoding != null);
    RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;
    final Channel channel = ctx.channel();
    if (requestBody != null) {
        channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);
    }
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final DefaultRequest request = new DefaultRequest(Instant.now(), requestHeaders, nettyRequest.method(), nettyRequest.protocolVersion(), nettyRequest.uri(), remoteAddress, socketAddress, serverRegistry.get(ServerConfig.class), requestBody);
    final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    final AtomicBoolean transmitted = new AtomicBoolean(false);
    final DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, nettyRequest, request, nettyHeaders, requestBody);
    ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);
    Action<Action<Object>> subscribeHandler = thing -> {
        transmitted.set(true);
        ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
    };
    final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(applicationConstants, request, channel, responseTransmitter, subscribeHandler);
    final Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);
    requestConstants.response = response;
    DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {
        if (requestBody != null) {
            requestBody.close();
            channel.attr(BODY_ACCUMULATOR_KEY).set(null);
        }
        if (!transmitted.get()) {
            Handler lastHandler = requestConstants.handler;
            StringBuilder description = new StringBuilder();
            description.append("No response sent for ").append(request.getMethod().getName()).append(" request to ").append(request.getUri());
            if (lastHandler != null) {
                description.append(" (last handler: ");
                if (lastHandler instanceof DescribingHandler) {
                    ((DescribingHandler) lastHandler).describeTo(description);
                } else {
                    DescribingHandlers.describeTo(lastHandler, description);
                }
                description.append(")");
            }
            String message = description.toString();
            LOGGER.warn(message);
            response.getHeaders().clear();
            ByteBuf body;
            if (development) {
                CharBuffer charBuffer = CharBuffer.wrap(message);
                body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8);
                response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8);
            } else {
                body = Unpooled.EMPTY_BUFFER;
            }
            response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes());
            responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body);
        }
    });
}
Also used : AttributeKey(io.netty.util.AttributeKey) DescribingHandlers(ratpack.handling.internal.DescribingHandlers) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Unpooled(io.netty.buffer.Unpooled) ByteBuf(io.netty.buffer.ByteBuf) MutableHeaders(ratpack.http.MutableHeaders) ServerConfig(ratpack.server.ServerConfig) Registry(ratpack.registry.Registry) CharsetUtil(io.netty.util.CharsetUtil) DefaultRenderController(ratpack.render.internal.DefaultRenderController) io.netty.channel(io.netty.channel) DefaultContext(ratpack.handling.internal.DefaultContext) Logger(org.slf4j.Logger) CharBuffer(java.nio.CharBuffer) ClosedChannelException(java.nio.channels.ClosedChannelException) ratpack.http.internal(ratpack.http.internal) ChainHandler(ratpack.handling.internal.ChainHandler) IOException(java.io.IOException) DescribingHandler(ratpack.handling.internal.DescribingHandler) Instant(java.time.Instant) InetSocketAddress(java.net.InetSocketAddress) ByteBufUtil(io.netty.buffer.ByteBufUtil) io.netty.handler.codec.http(io.netty.handler.codec.http) Response(ratpack.http.Response) Headers(ratpack.http.Headers) Action(ratpack.func.Action) Handler(ratpack.handling.Handler) Handlers(ratpack.handling.Handlers) ExecController(ratpack.exec.ExecController) Action(ratpack.func.Action) MutableHeaders(ratpack.http.MutableHeaders) Headers(ratpack.http.Headers) InetSocketAddress(java.net.InetSocketAddress) CharBuffer(java.nio.CharBuffer) ByteBuf(io.netty.buffer.ByteBuf) ServerConfig(ratpack.server.ServerConfig) MutableHeaders(ratpack.http.MutableHeaders) DescribingHandler(ratpack.handling.internal.DescribingHandler) ChainHandler(ratpack.handling.internal.ChainHandler) DescribingHandler(ratpack.handling.internal.DescribingHandler) Handler(ratpack.handling.Handler) Response(ratpack.http.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultContext(ratpack.handling.internal.DefaultContext)

Aggregations

CharBuffer (java.nio.CharBuffer)387 ByteBuffer (java.nio.ByteBuffer)143 CoderResult (java.nio.charset.CoderResult)81 CharsetDecoder (java.nio.charset.CharsetDecoder)45 IOException (java.io.IOException)41 Charset (java.nio.charset.Charset)28 Test (org.junit.Test)23 CharacterCodingException (java.nio.charset.CharacterCodingException)12 CharsetEncoder (java.nio.charset.CharsetEncoder)12 FileInputStream (java.io.FileInputStream)11 IntBuffer (java.nio.IntBuffer)10 Reader (java.io.Reader)9 BufferOverflowException (java.nio.BufferOverflowException)9 DoubleBuffer (java.nio.DoubleBuffer)9 FloatBuffer (java.nio.FloatBuffer)9 LongBuffer (java.nio.LongBuffer)9 ShortBuffer (java.nio.ShortBuffer)9 BufferUnderflowException (java.nio.BufferUnderflowException)7 ValueWrapper (org.apache.geode.internal.memcached.ValueWrapper)7 ReadableByteChannel (java.nio.channels.ReadableByteChannel)6