Example usage for io.netty.buffer ByteBufInputStream ByteBufInputStream

List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream

Introduction

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

Prototype

public ByteBufInputStream(ByteBuf buffer) 

Source Link

Document

Creates a new stream which reads data from the specified buffer starting at the current readerIndex and ending at the current writerIndex .

Usage

From source file:buildcraft.core.gui.BuildCraftContainer.java

License:Minecraft Mod Public

public void handleWidgetClientData(int widgetId, ByteBuf data) {
    InputStream input = new ByteBufInputStream(data);
    DataInputStream stream = new DataInputStream(input);

    try {//w w  w .j  a  v  a2  s  .c  om
        widgets.get(widgetId).handleClientPacketData(stream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ccostello.server.NetworkGameServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    //System.err.println(packet);

    GameMessage gm;/*from   w w  w .j a  v a2  s  .  c o m*/
    ByteBufInputStream is = new ByteBufInputStream(packet.content());
    gm = GameMessage.parseFrom(is);

    System.out.println("Received message: " + gm.toString());

    switch (gm.getMsgType()) {
    case REGISTER_CLIENT:
        IncomingMessagesManager.registerNewClient(gm, ctx, packet.sender());
        break;
    case USER_COMMAND:
        IncomingMessagesManager.processUserCommand(gm, ctx, packet.sender());
        break;
    case END_CLIENT:
        IncomingMessagesManager.unregisterClient(gm, ctx, packet.sender());
        break;
    default:
        break;
    }
}

From source file:cf.dropsonde.metron.ControlMessageHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
    try {//from w ww .  j a v a2  s  .  com
        messagesReceived++;
        final ByteBufInputStream input = new ByteBufInputStream(((DatagramPacket) message).content());
        final ControlMessage controlMessage = wire.parseFrom(input, ControlMessage.class);

        final control.UUID identifier = controlMessage.identifier;
        switch (controlMessage.controlType) {
        case HeartbeatRequest:
            final Heartbeat heartbeat = new Heartbeat.Builder()
                    .controlMessageIdentifier(new UUID(identifier.low, identifier.high))
                    .receivedCount(messagesReceived).errorCount(errorCount).sentCount(messagesSent).build();
            context.writeAndFlush(heartbeat);
            break;
        default:
            throw new IllegalStateException(
                    "Don't know how to handle messages of type: " + controlMessage.controlType);
        }
    } finally {
        if (message instanceof ReferenceCounted) {
            ((ReferenceCounted) message).release();
        }
    }
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketClientHandler.java

License:Apache License

public String decodeByteBuff(ByteBuf buf) throws IOException, DataFormatException {

    byte[] temp = new byte[buf.readableBytes()];
    ByteBufInputStream bis = new ByteBufInputStream(buf);
    bis.read(temp);/*w  ww  . ja v  a 2  s  .c om*/
    bis.close();
    Inflater decompresser = new Inflater(true);
    decompresser.setInput(temp, 0, temp.length);
    StringBuilder sb = new StringBuilder();
    byte[] result = new byte[1024];
    while (!decompresser.finished()) {
        int resultLength = decompresser.inflate(result);
        sb.append(new String(result, 0, resultLength, "UTF-8"));
    }
    decompresser.end();
    return sb.toString();
}

From source file:co.freeside.betamax.proxy.netty.ByteBufInputSupplier.java

License:Apache License

@Override
public InputStream getInput() throws IOException {
    return new ByteBufInputStream(buffer);
}

From source file:co.freeside.betamax.proxy.netty.NettyMessageAdapter.java

License:Apache License

@Override
protected InputStream getBodyAsStream() throws IOException {
    //Copy the body into a new ByteBuf so that it can be consumed multiple times.
    return new ByteBufInputStream(Unpooled.copiedBuffer(body));
}

From source file:co.rsk.rpc.netty.JsonRpcWeb3ServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder request) throws Exception {
    ByteBuf responseContent = Unpooled.buffer();
    int responseCode;
    try (ByteBufOutputStream os = new ByteBufOutputStream(responseContent);
            ByteBufInputStream is = new ByteBufInputStream(request.content().retain())) {

        responseCode = jsonRpcServer.handleRequest(is, os);
    } catch (Exception e) {
        String unexpectedErrorMsg = "Unexpected error";
        LOGGER.error(unexpectedErrorMsg, e);
        int errorCode = ErrorResolver.JsonError.CUSTOM_SERVER_ERROR_LOWER;
        responseContent = buildErrorContent(errorCode, unexpectedErrorMsg);
        responseCode = errorCode;/*from  w  ww. ja v a  2 s  .  co m*/
    }

    ctx.fireChannelRead(new Web3Result(responseContent, responseCode));
}

From source file:co.rsk.rpc.netty.RskJsonRpcHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder msg) {
    try {//from   ww w  .  j a v  a 2 s .com
        RskJsonRpcRequest request = serializer.deserializeRequest(new ByteBufInputStream(msg.copy().content()));

        // TODO(mc) we should support the ModuleDescription method filters
        JsonRpcResultOrError resultOrError = request.accept(this, ctx);
        JsonRpcIdentifiableMessage response = resultOrError.responseFor(request.getId());
        ctx.writeAndFlush(new TextWebSocketFrame(serializer.serializeMessage(response)));
        return;
    } catch (IOException e) {
        LOGGER.trace("Not a known or valid JsonRpcRequest", e);
    }

    // delegate to the next handler if the message can't be matched to a known JSON-RPC request
    ctx.fireChannelRead(msg.retain());
}

From source file:com.addthis.hydra.store.skiplist.Page.java

License:Apache License

public void decode(byte[] page) {
    parent.numPagesDecoded.getAndIncrement();
    ByteBuf buffer = Unpooled.wrappedBuffer(page);
    try {/*  w ww  .  ja v  a2 s.  c o  m*/
        InputStream in = new ByteBufInputStream(buffer);
        int flags = in.read() & 0xff;
        int gztype = flags & 0x0f;
        boolean isSparse = (flags & FLAGS_IS_SPARSE) != 0;
        boolean hasEstimates = (flags & FLAGS_HAS_ESTIMATES) != 0;
        int readEstimateTotal, readEstimates;
        switch (gztype) {
        case 1:
            in = new InflaterInputStream(in);
            break;
        case 2:
            in = new GZIPInputStream(in);
            break;
        case 3:
            in = new LZFInputStream(in);
            break;
        case 4:
            in = new SnappyInputStream(in);
            break;
        }
        K firstKey;
        byte[] nextFirstKey;
        if (isSparse) {
            encodeType = KeyCoder.EncodeType.SPARSE;
            DataInputStream dis = new DataInputStream(in);
            int entries = Varint.readUnsignedVarInt(dis);

            firstKey = keyCoder.keyDecode(Bytes.readBytes(in, Varint.readUnsignedVarInt(dis)));
            int nextFirstKeyLength = Varint.readUnsignedVarInt(dis);
            if (nextFirstKeyLength > 0) {
                nextFirstKey = Bytes.readBytes(in, nextFirstKeyLength);
            } else {
                nextFirstKey = null;
            }

            int bytes = 0;

            size = entries;
            keys = new ArrayList<>(size);
            values = new ArrayList<>(size);
            rawValues = new ArrayList<>(size);

            for (int i = 0; i < entries; i++) {
                byte kb[] = Bytes.readBytes(in, Varint.readUnsignedVarInt(dis));
                byte vb[] = Bytes.readBytes(in, Varint.readUnsignedVarInt(dis));
                bytes += kb.length + vb.length;
                keys.add(keyCoder.keyDecode(kb));
                values.add(null);
                rawValues.add(vb);
            }

            if (hasEstimates) {
                readEstimateTotal = Varint.readUnsignedVarInt(dis);
                readEstimates = Varint.readUnsignedVarInt(dis);
                setAverage(readEstimateTotal, readEstimates);
            } else {
                /** use a pessimistic/conservative byte/entry estimate */
                setAverage(bytes * estimateMissingFactor, entries);
            }
        } else {
            encodeType = KeyCoder.EncodeType.LEGACY;
            int entries = (int) Bytes.readLength(in);

            firstKey = keyCoder.keyDecode(Bytes.readBytes(in));
            nextFirstKey = Bytes.readBytes(in);

            int bytes = 0;

            size = entries;
            keys = new ArrayList<>(size);
            values = new ArrayList<>(size);
            rawValues = new ArrayList<>(size);

            for (int i = 0; i < entries; i++) {
                byte kb[] = Bytes.readBytes(in);
                byte vb[] = Bytes.readBytes(in);
                bytes += kb.length + vb.length;
                keys.add(keyCoder.keyDecode(kb));
                values.add(null);
                rawValues.add(vb);
            }

            if (hasEstimates) {
                readEstimateTotal = (int) Bytes.readLength(in);
                readEstimates = (int) Bytes.readLength(in);
                setAverage(readEstimateTotal, readEstimates);
            } else {
                /** use a pessimistic/conservative byte/entry estimate */
                setAverage(bytes * estimateMissingFactor, entries);
            }
        }

        updateMemoryEstimate();

        assert (this.firstKey.equals(firstKey));

        this.nextFirstKey = keyCoder.keyDecode(nextFirstKey);

        in.close();
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        buffer.release();
    }
}

From source file:com.allanbank.mongodb.netty.ByteToMessageDecoder.java

License:Apache License

/**
 * {@inheritDoc}/*  www .ja  v  a  2s .  c om*/
 * <p>
 * Overridden to read the messages from the {@link ByteBuf}.
 * </p>
 */
@Override
protected Object decode(final ChannelHandlerContext ctx, final ByteBuf in) throws Exception {

    final ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }

    final ByteBufInputStream instream = new ByteBufInputStream(frame);
    final BsonInputStream bin = new BsonInputStream(instream, myDecoderCache);

    try {
        final int length = bin.readInt();

        final int requestId = bin.readInt();
        final int responseId = bin.readInt();
        final int opCode = bin.readInt();

        final Operation op = Operation.fromCode(opCode);
        if (op == null) {
            // Huh? Dazed and confused
            throw new MongoDbException("Unexpected operation read '" + opCode + "'.");
        }

        final Header header = new Header(length, requestId, responseId, op);
        Message message = null;
        switch (op) {
        case REPLY:
            message = new Reply(header, bin);
            break;
        case QUERY:
            message = new Query(header, bin);
            break;
        case UPDATE:
            message = new Update(bin);
            break;
        case INSERT:
            message = new Insert(header, bin);
            break;
        case GET_MORE:
            message = new GetMore(bin);
            break;
        case DELETE:
            message = new Delete(bin);
            break;
        case KILL_CURSORS:
            message = new KillCursors(bin);
            break;
        }

        return message;
    } catch (final IOException ioe) {
        final MongoDbException error = new ConnectionLostException(ioe);

        // Not good. Close the connection.
        ctx.close();

        throw error;
    } finally {
        IOUtils.close(bin);
    }
}