Example usage for io.netty.buffer ByteBuf hasArray

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

Introduction

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

Prototype

public abstract boolean hasArray();

Source Link

Document

Returns true if and only if this buffer has a backing byte array.

Usage

From source file:org.apache.distributedlog.common.util.ByteBufUtils.java

License:Apache License

public static byte[] getArray(ByteBuf buffer) {
    if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.writableBytes() == 0) {
        return buffer.array();
    }// w ww.j  a v a2  s  . c  o  m
    byte[] data = new byte[buffer.readableBytes()];
    buffer.getBytes(buffer.readerIndex(), data);
    return data;
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.codec.ReplyDecoder.java

License:Apache License

private Segment decodeSegment(ByteBuf in, int len, byte type) {
    long msb = in.readLong();
    long lsb = in.readLong();
    long hash = in.readLong();

    // #readBytes throws a 'REPLAY' exception if there are not enough bytes
    // available for reading
    ByteBuf data = in.readBytes(len - 25);
    byte[] segment;
    if (data.hasArray()) {
        segment = data.array();/*from  w w w .  ja  v a 2 s  .c o  m*/
    } else {
        segment = new byte[len - 25];
        in.readBytes(segment);
    }

    Hasher hasher = Hashing.murmur3_32().newHasher();
    long check = hasher.putBytes(segment).hash().padToLong();
    if (hash == check) {
        SegmentId id = new SegmentId(store.getTracker(), msb, lsb);
        Segment s = new Segment(store.getTracker(), id, ByteBuffer.wrap(segment));
        log.debug("received segment with id {} and size {}", id, s.size());
        return s;
    }
    log.debug("received corrupted segment {}, ignoring", new UUID(msb, lsb));
    return null;
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.codec.ReplyDecoder.java

License:Apache License

private IdArrayBasedBlob decodeBlob(ByteBuf in, int length, byte type) {
    int inIdLen = in.readInt();
    byte[] bid = new byte[inIdLen];
    in.readBytes(bid);/*from   ww  w.  jav  a 2 s . c o  m*/
    String id = new String(bid, Charset.forName("UTF-8"));

    long hash = in.readLong();
    // #readBytes throws a 'REPLAY' exception if there are not enough bytes
    // available for reading
    ByteBuf data = in.readBytes(length);
    byte[] blob;
    if (data.hasArray()) {
        blob = data.array();
    } else {
        blob = new byte[length];
        data.readBytes(blob);
    }

    Hasher hasher = Hashing.murmur3_32().newHasher();
    long check = hasher.putBytes(blob).hash().padToLong();
    if (hash == check) {
        log.debug("received blob with id {} and size {}", id, blob.length);
        return new IdArrayBasedBlob(blob, id);
    }
    log.debug("received corrupted binary {}, ignoring", id);
    return null;
}

From source file:org.apache.reef.wake.remote.transport.netty.ChunkedReadWriteHandler.java

License:Apache License

/**
 * Thread-safe since there is no shared instance state.
 * Just prepend size to the message and stream it through
 * a chunked stream and let the base method handle the actual
 * chunking.//  ww w . jav a 2  s  .  co m
 * <p/>
 * We do not need to tag the writes since the base class ChunkedWriteHandler
 * serializes access to the channel and first write will complete before
 * the second begins.
 */
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    if (msg instanceof ByteBuf) {

        final ByteBuf bf = (ByteBuf) msg;

        if (bf.hasArray()) {
            final byte[] data = bf.array();
            final byte[] size = sizeAsByteArr(data.length);
            final ByteBuf writeBuffer = Unpooled.wrappedBuffer(size, data);
            final ByteBufCloseableStream stream = new ByteBufCloseableStream(writeBuffer);
            final ChunkedStream chunkedStream = new ChunkedStream(stream,
                    NettyChannelInitializer.MAXFRAMELENGTH - 1024);
            super.write(ctx, chunkedStream, promise);
        } else {
            super.write(ctx, msg, promise);
        }

    } else {
        super.write(ctx, msg, promise);
    }
}

From source file:org.asynchttpclient.providers.netty4.util.ByteBufUtil.java

License:Apache License

public static byte[] byteBuf2bytes(ByteBuf b) {
    int readable = b.readableBytes();
    int readerIndex = b.readerIndex();
    if (b.hasArray()) {
        byte[] array = b.array();
        if (b.arrayOffset() == 0 && readerIndex == 0 && array.length == readable) {
            return array;
        }//from  w ww  . java 2s.  com
    }
    byte[] array = new byte[readable];
    b.getBytes(readerIndex, array);
    return array;
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {

    boolean skipClose = false;
    AtmosphereResponse response = null;//  w w w .java  2  s . co m
    AtmosphereRequest request = null;
    Action a = null;
    boolean resumeOnBroadcast = false;
    boolean keptOpen = false;
    ChannelWriter asyncWriter = null;
    String method = "GET";
    boolean writeHeader = false;
    boolean forceSuspend = false;
    boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

    try {
        if (messageEvent instanceof HttpRequest) {
            final HttpRequest hrequest = (HttpRequest) messageEvent;

            byte[] body = EMPTY;
            if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) {
                ByteBuf b = FullHttpRequest.class.cast(messageEvent).content();
                if (b.isReadable()) {
                    body = new byte[b.readableBytes()];
                    b.readBytes(body);
                }
            }

            // First let's try to see if it's a static resources
            if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                try {
                    hrequest.headers().add(STATIC_MAPPING, "true");
                    super.channelRead(ctx, messageEvent);

                    if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Unexpected State", e);
                } finally {
                    hrequest.headers().set(STATIC_MAPPING, "false");
                }
            }

            boolean ka = HttpHeaders.isKeepAlive(hrequest);
            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka)
                    : new StreamWriter(ctx.channel(), true, ka);

            method = hrequest.getMethod().name();

            request = createAtmosphereRequest(ctx, hrequest, body);
            request.setAttribute(KEEP_ALIVE, new Boolean(ka));

            // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
            AtmosphereRequestImpl.Body b = request.body();
            if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty()
                    && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) {
                forceSuspend = true;
            }
        } else {
            request = State.class.cast(ctx.attr(ATTACHMENT).get()).request;
            boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput();
            Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka)
                    : new StreamWriter(ctx.channel(), isLast, ka);
            method = request.getMethod();
            ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content();

            if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                request.body(internalBuffer.array());
            } else {
                logger.trace("Unable to read in memory the request's bytes. Using stream");
                request.body(new ByteBufInputStream(internalBuffer));
            }

            if (!isLast) {
                forceSuspend = true;
            }
        }

        response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader)
                .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0")
                .request(request).build();

        if (config.supportChunking()) {
            response.setHeader("Transfer-Encoding", "chunked");
        }

        a = framework.doCometSupport(request, response);
        if (forceSuspend) {
            a.type(Action.TYPE.SUSPEND);
            // leave the stream open
            keptOpen = true;
        }

        String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
        if (transport == null) {
            transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
        }

        if (a.type() == Action.TYPE.SUSPEND) {
            if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                    || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                keptOpen = true;
            } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT)
                    || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                resumeOnBroadcast = true;
            }
        }

        final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
        final State state = new State(request, action == null ? Action.CONTINUE : action);

        ctx.attr(ATTACHMENT).set(state);

        if (action != null && action.type() == Action.TYPE.SUSPEND) {
            if (action.timeout() != -1) {
                final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (!w.get().isClosed()
                                && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                            AtmosphereResourceImpl impl = state.resource();
                            if (impl != null) {
                                asynchronousProcessor.endRequest(impl, false);
                                f.get().cancel(true);
                            }
                        }
                    }
                }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
            }
        } else if (action != null && action.type() == Action.TYPE.RESUME) {
            resumeOnBroadcast = false;
        }
    } catch (AtmosphereMappingException ex) {
        if (method.equalsIgnoreCase("GET")) {
            logger.trace("Unable to map the request {}, trying static file", messageEvent);
        }
    } catch (Throwable e) {
        logger.error("Unable to process request", e);
        throw new IOException(e);
    } finally {
        try {
            if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                if (!skipClose && response != null) {
                    asyncWriter.close(response);
                } else {
                    httpChannels.add(ctx.channel());
                }
            }
        } finally {
            if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                request.destroy();
                response.destroy();
                framework.notify(Action.TYPE.DESTROYED, request, response);
            }
        }
    }
}

From source file:org.fiware.kiara.netty.Buffers.java

License:Open Source License

public static ByteBuffer toByteBuffer(ByteBuf msg) {
    final byte[] array;
    final int offset;
    final int length = msg.readableBytes();
    if (msg.hasArray()) {
        array = msg.array();//  ww w . j av  a2s  .  com
        offset = msg.arrayOffset() + msg.readerIndex();
    } else {
        array = new byte[length];
        msg.getBytes(msg.readerIndex(), array, 0, length);
        offset = 0;
    }

    return ByteBuffer.wrap(array, offset, length);
}

From source file:org.fiware.kiara.transport.http.HttpHandler.java

License:Open Source License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("Handler: {} / Channel: {}", this, ctx.channel());
    if (mode == Mode.SERVER) {
        if (msg instanceof FullHttpRequest) {
            final FullHttpRequest request = (FullHttpRequest) msg;

            HttpRequestMessage transportMessage = new HttpRequestMessage(this, request);
            transportMessage.setPayload(request.content().copy().nioBuffer());

            if (logger.isDebugEnabled()) {
                logger.debug("RECEIVED CONTENT {}", HexDump.dumpHexString(transportMessage.getPayload()));
                //logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload()));
            }/*from w  w w. j av a  2 s .c o m*/

            notifyListeners(transportMessage);

            boolean keepAlive = HttpHeaders.isKeepAlive(request);
        }
    } else {
        // CLIENT
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            headers = response.headers();
            //if (!response.headers().isEmpty()) {
            //    contentType = response.headers().get("Content-Type");
            //}
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            if (buf.isReadable()) {
                if (buf.hasArray()) {
                    bout.write(buf.array(), buf.readerIndex(), buf.readableBytes());
                } else {
                    byte[] bytes = new byte[buf.readableBytes()];
                    buf.getBytes(buf.readerIndex(), bytes);
                    bout.write(bytes);
                }
            }
            if (content instanceof LastHttpContent) {
                //ctx.close();
                bout.flush();
                HttpResponseMessage response = new HttpResponseMessage(this, headers);
                response.setPayload(ByteBuffer.wrap(bout.toByteArray(), 0, bout.size()));
                onResponse(response);
                bout.reset();
            }
        }
    }
}

From source file:org.onosproject.xmpp.core.ctl.handlers.XmppEncoderTest.java

License:Apache License

@Test
public void testEncode() throws Exception {
    Packet iq = new IQ();
    ByteBuf buffer = Unpooled.buffer();
    xmppEncoder.encode(channelHandlerContext, iq, buffer);
    assertThat(buffer.hasArray(), Matchers.is(true));
}

From source file:org.ratpackframework.http.internal.DefaultRequest.java

License:Apache License

@Override
public byte[] getBytes() {
    ByteBuf buffer = getBuffer();
    if (buffer.hasArray()) {
        return buffer.array();
    } else {/*from w ww  .j a v  a  2s  . c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.writerIndex());
        try {
            writeBodyTo(baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return baos.toByteArray();
    }
}