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:ratpack.session.internal.DefaultSessionAdapter.java

License:Apache License

private void hydrate(ByteBuf data) {
    if (data.readableBytes() > 0) {
        try {//  w ww  .j a v  a  2 s .co m
            Data deserializedData = defaultSerializer.deserialize(Data.class, new ByteBufInputStream(data));
            this.strings.clear();
            this.strings.putAll(deserializedData.strings);
            this.objects.clear();
            this.objects.putAll(deserializedData.objects);
            sessionStatus.setDirty(false);
        } catch (Exception e) {
            throw Exceptions.uncheck(e);
        }
    }
}

From source file:se.sics.kompics.network.netty.serialization.AvroSerializer.java

private Object fromBinaryNoSchema(ByteBuf buf, boolean generated) {
    DatumReader refReader;// w w w . j  a v  a  2s .  c om
    if (generated) {
        refReader = new SpecificDatumReader();
    } else {
        refReader = new ReflectDatumReader();
    }
    try (ByteBufInputStream in = new ByteBufInputStream(buf);
            DataFileStream reader = new DataFileStream(in, refReader)) {
        return reader.next(); // there should only be one
    } catch (IOException ex) {
        LOG.error("Couldn't deserialise object.", ex);
        return null;
    }
}

From source file:se.sics.kompics.network.netty.serialization.AvroSerializer.java

private Object fromBinaryWithSchema(ByteBuf buf, SchemaEntry se, boolean generated) {
    DatumReader refReader;//from   ww  w  . j a  v  a2s.  c  o m
    if (generated) {
        refReader = new SpecificDatumReader(se.schema);
    } else {
        refReader = new ReflectDatumReader(se.schema);
    }
    try (ByteBufInputStream in = new ByteBufInputStream(buf);) {
        BinaryDecoder decoder = DecoderFactory.get().directBinaryDecoder(in, null);
        return refReader.read(null, decoder); // there should only be one
    } catch (IOException ex) {
        LOG.error("Couldn't deserialise object.", ex);
        return null;
    }
}

From source file:se.sics.kompics.network.netty.serialization.JavaSerializer.java

License:Open Source License

@Override
public Object fromBinary(ByteBuf buf, Optional<Class> hint) {
    // Ignore hint
    try {//from  w w w. j ava2  s  .co m
        Closer closer = Closer.create();
        try {
            ByteBufInputStream bbis = closer.register(new ByteBufInputStream(buf));
            CompactObjectInputStream cois = closer.register(new CompactObjectInputStream(bbis, resolver));
            return cois.readObject();
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException ex) {
        Serializers.LOG.error("JavaSerializer: Could not deserialize object", ex);
        return null;
    }
}

From source file:se.sics.nstream.hops.kafka.avro.AvroParser.java

License:Open Source License

public static GenericRecord blobToAvro(Schema schema, ByteBuf data) {
    int readPos = data.readerIndex();
    GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
    try (InputStream in = new ByteBufInputStream(data)) {
        BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
        try {//from ww w.j a  v  a2  s  .  c o  m
            GenericRecord record = reader.read(null, decoder);
            readPos = data.readerIndex() - decoder.inputStream().available();
            data.readerIndex(readPos);
            return record;
        } catch (EOFException ex) {
            data.readerIndex(readPos);
            return null;
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:therogue.storehouse.network.NetworkUtils.java

License:Open Source License

public static NBTTagCompound readNBTTagCompound(ByteBuf buf) {
    int i = buf.readerIndex();
    byte b0 = buf.readByte();

    if (b0 == 0) {
        return null;
    } else {//from   w  ww  . j  a  va  2  s  .  c o  m
        buf.readerIndex(i);

        try {
            return CompressedStreamTools.read(new ByteBufInputStream(buf), new NBTSizeTracker(2097152L));
        } catch (IOException ioexception) {
            throw new EncoderException(ioexception);
        }
    }
}

From source file:tk.jomp16.utils.DccFileSendNettyDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    try (ByteBufInputStream byteBufInputStream = new ByteBufInputStream(in);
            RandomAccessFile randomAccessFile = new RandomAccessFile(f, "rw")) {
        randomAccessFile.seek(position);

        byte[] inBuffer = new byte[in.readableBytes()];
        byte[] outBuffer = new byte[4];
        int bytesRead;

        while ((bytesRead = byteBufInputStream.read(inBuffer, 0, inBuffer.length)) != -1) {
            randomAccessFile.write(inBuffer, 0, bytesRead);

            position += bytesRead;/*from ww w  .  ja  v  a2 s  .  co m*/

            outBuffer[0] = (byte) (position >> 24 & 255);
            outBuffer[1] = (byte) (position >> 16 & 255);
            outBuffer[2] = (byte) (position >> 8 & 255);
            outBuffer[3] = (byte) (position & 255);

            ctx.channel().writeAndFlush(Unpooled.buffer(4).writeBytes(outBuffer));
        }
    }
}

From source file:vn.com.vng.gsmobile.casino.client.ClientHandler.java

License:Apache License

@SuppressWarnings({ "rawtypes" })
private void receiptFormServer(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    ByteBufInputStream bbi = new ByteBufInputStream(frame.content());
    byte c1 = bbi.readByte();
    byte c2 = bbi.readByte();
    byte c3 = bbi.readByte();
    byte c4 = bbi.readByte();
    if (c4 == 0) {
        int gzip = ((int) c3 & (int) 0x80) >> 7;
        int version = (int) c3 & (int) 0x7F;
        String sCMD = c1 + "_" + c2 + "_" + version;
        Map mService = (Map) Lib.getServiceConfig(false).get(sCMD);
        if (mService != null) {
            //1. Gii nn
            byte[] b = null;
            if (gzip == 1)
                b = GZip.decompress(IOUtils.toByteArray(bbi));
            else/*w ww .  j av a2 s .c  om*/
                b = IOUtils.toByteArray(bbi);
            //2. Gii m
            byte[] b1 = null;
            //            Object oSecKey = mService.get("server_seckey");
            //            if("1".equals(Const.SESSION_KEY) && "1".equals(oSecKey)){
            //               //Giai ma data request
            //               Session s = new Session(sUID);
            //               String sk = s.hget(Session.SECKEY);
            //               if(sk !=null){
            //                   b1 = XXTEA.decrypt(b, sk.getBytes());
            //               }
            //            }
            ByteBuffer bb = ByteBuffer.wrap(b1 == null ? b : b1);
            Object oData = null;
            Object oServer = mService.get("server");
            if (oServer != null) {
                Class<?> clsRequest = Class.forName(mService.get("server").toString());
                try {
                    oData = Lib.invoke(clsRequest, "getRootAs" + clsRequest.getSimpleName(),
                            new Class<?>[] { ByteBuffer.class }, new Object[] { bb });
                } catch (Exception e) {
                    oData = new String(b, Charset.forName("UTF-8"));
                }
            }
            Lib.getLogService().debug(Arrays.asList(uid, ctx.channel().id(), c1, c2, c3, c4, oData.toString(),
                    this.getClass().getSimpleName() + ".receiptFormServer"));
            Bot bot = Bot.list.get(uid);
            FlatBufferBuilder builder = new FlatBufferBuilder(0);
            Table data = null;
            Integer state = null;
            Integer turnIdx = null;
            Integer playIdx = null;
            Long battleId = null;
            Long roomId = null;
            CMD cmd = CMD.getCMD(c1, c2, (byte) version);
            switch (cmd) {
            case ROOM_WAIT:
                RoomResponse rs = (RoomResponse) oData;
                if (rs != null) {
                    builder.finish(CMDJoinGame.createCMDJoinGame(builder, uid, rs.room().id(),
                            JoinGameType.PLAY, builder.createString("trid"), 0));
                    data = CMDJoinGame.getRootAsCMDJoinGame(builder.dataBuffer());
                    bot.write(CMD.JOIN_ROOM, data);
                }
                break;
            case INVITE_ROOM:
                CMDInviteGame iv = (CMDInviteGame) oData;
                builder.finish(CMDJoinGame.createCMDJoinGame(builder, uid, iv.roomId(), JoinGameType.PLAY,
                        builder.createString("trid"), 0));
                data = CMDJoinGame.getRootAsCMDJoinGame(builder.dataBuffer());
                bot.write(CMD.JOIN_ROOM, data);
                break;
            case JOIN_ROOM:
                RoomResponse rs2 = (RoomResponse) oData;
                if (rs2 != null) {
                    bot.setRoomId(rs2.room().id());
                }
                break;
            case QUIT_ROOM:
                CMDQuitGame qg = (CMDQuitGame) oData;
                if (qg.state() == QuitState.QUIT_ACCEPT || qg.state() == QuitState.QUIT_NOT_ENOUGH_MONEY
                        || qg.state() == QuitState.QUIT_POOR_CONNECTION)
                    bot.setRoomId(null);
                break;
            case TLMN_UPDATE_BATTLE_INFO:
            case TLMN_BATTLE_INFO:
                GameTLMNInfo gif = (GameTLMNInfo) oData;
                roomId = gif.roomId();
                battleId = gif.gameId();
                state = gif.state();
                turnIdx = gif.turnIdx();
                playIdx = gif.playerIdx();
                if (state == GameRoomState.Finished) {
                    bot.setPlayerIdx(null);
                } else if (state == GameRoomState.Playing) {
                    for (int j = 0; j < gif.cardListLength(); j++) {
                        if (gif.cardList(j).playerId() == bot.getId()) {
                            bot.setPlayerIdx(j);
                            break;
                        }
                    }
                }

                //skip turn here
                if (bot.getPlayerIdx() == playIdx && state == GameRoomState.Playing) {
                    builder.finish(
                            CMDGameTLMNSkip.createCMDGameTLMNSkip(builder, roomId, battleId, turnIdx, playIdx));
                    data = CMDGameTLMNSkip.getRootAsCMDGameTLMNSkip(builder.dataBuffer());
                    bot.write(CMD.TLMN_SKIP_TURN, data);
                }
                break;
            case TLMN_UPDATE_BATTLE_INFO_TINY:
                CMDGameTLMNUpdate gup = (CMDGameTLMNUpdate) oData;
                roomId = gup.roomId();
                battleId = gup.gameId();
                state = gup.state();
                turnIdx = gup.nextTurnIdx();
                playIdx = gup.nextPlayerIdx();
                synchronized (bot) {
                    bot.wait(2000);
                }
                //skip turn here
                if (bot.getPlayerIdx() == playIdx && state == GameRoomState.Playing) {
                    builder.finish(
                            CMDGameTLMNSkip.createCMDGameTLMNSkip(builder, roomId, battleId, turnIdx, playIdx));
                    data = CMDGameTLMNSkip.getRootAsCMDGameTLMNSkip(builder.dataBuffer());
                    bot.write(CMD.TLMN_SKIP_TURN, data);
                }
                break;
            case CAO_BATTLE_INFO:
                Game3LaGameInfo gif3 = (Game3LaGameInfo) oData;
                roomId = gif3.roomId();
                battleId = gif3.gameId();
                state = gif3.state();
                if (state == GameRoomState.Finished) {
                    bot.setPlayerIdx(null);
                } else if (state == GameRoomState.Playing) {
                    for (int j = 0; j < gif3.cardListLength(); j++) {
                        if (gif3.cardList(j).playerId() == bot.getId()) {
                            bot.setPlayerIdx(j);
                            break;
                        }
                    }
                }
                if (state == GameRoomState.Playing) {
                    synchronized (bot) {
                        bot.wait(2000);
                    }
                    builder.finish(CMDGame3LaShowCard.createCMDGame3LaShowCard(builder, roomId, battleId,
                            bot.getPlayerIdx(),
                            CMDGame3LaShowCard.createShowedCardsVector(builder, new byte[] { 0, 1, 2 })));
                    data = CMDGameTLMNSkip.getRootAsCMDGameTLMNSkip(builder.dataBuffer());
                    bot.write(CMD.CAO_SHOW_CARDS, data);
                }
                break;
            default:
                break;
            }
        } else {
            Lib.getLogService()
                    .debug(Arrays.asList(uid, ctx.channel().id(), c1, c2, c3, c4,
                            Hex.encodeHexString(IOUtils.toString(bbi).getBytes()),
                            this.getClass().getSimpleName() + ".receiptFormServer"));
        }
    } else
        Lib.getLogService().debug(Arrays.asList(uid, ctx.channel().id(), c1, c2, c3, c4,
                Lib.getErrorMessage(c4), this.getClass().getSimpleName() + ".receiptFormServer"));
}

From source file:whitespell.net.websockets.socketio.parser.Decoder.java

License:Apache License

private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException {
    if (buffer.readableBytes() < 3) {
        throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8));
    }//from   www.j av  a  2s .  c o m
    PacketType type = getType(buffer);

    int readerIndex = buffer.readerIndex() + 1;
    // 'null' to avoid unnecessary StringBuilder creation
    boolean hasData = false;
    StringBuilder messageId = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (messageId == null) {
            messageId = new StringBuilder(4);
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        if (msg != (byte) '+') {
            messageId.append((char) msg);
        } else {
            hasData = true;
        }
    }
    Long id = null;
    if (messageId != null && messageId.length() > 0) {
        id = Long.valueOf(messageId.toString());
    }

    // 'null' to avoid unnecessary StringBuilder creation
    StringBuilder endpointBuffer = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (endpointBuffer == null) {
            endpointBuffer = new StringBuilder();
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        endpointBuffer.append((char) msg);
    }

    String endpoint = Namespace.DEFAULT_NAME;
    if (endpointBuffer != null && endpointBuffer.length() > 0) {
        endpoint = endpointBuffer.toString();
    }

    if (buffer.readableBytes() == readerIndex) {
        buffer.readerIndex(buffer.readableBytes());
    } else {
        readerIndex += 1;
        buffer.readerIndex(readerIndex);
    }

    Packet packet = new Packet(type);
    packet.setEndpoint(endpoint);
    if (id != null) {
        packet.setId(id);
        if (hasData) {
            packet.setAck(Packet.ACK_DATA);
        } else {
            packet.setAck(true);
        }
    }

    switch (type) {
    case ERROR: {
        if (!buffer.isReadable()) {
            break;
        }
        String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+");
        if (pieces.length > 0 && pieces[0].trim().length() > 0) {
            ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0]));
            packet.setReason(reason);
            if (pieces.length > 1) {
                ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1]));
                packet.setAdvice(advice);
            }
        }
        break;
    }

    case MESSAGE: {
        if (buffer.isReadable()) {
            packet.setData(buffer.toString(CharsetUtil.UTF_8));
        } else {
            packet.setData("");
        }
        break;
    }

    case EVENT: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        Event event = jsonSupport.readValue(in, Event.class);
        packet.setName(event.getName());
        if (event.getArgs() != null) {
            packet.setArgs(event.getArgs());
        }
        break;
    }

    case JSON: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        JsonObject obj = jsonSupport.readValue(in, JsonObject.class);
        if (obj != null) {
            packet.setData(obj.getObject());
        } else {
            in.reset();
            Object object = jsonSupport.readValue(in, Object.class);
            packet.setData(object);
        }
        break;
    }

    case CONNECT: {
        if (buffer.isReadable()) {
            packet.setQs(buffer.toString(CharsetUtil.UTF_8));
        }
        break;
    }

    case ACK: {
        if (!buffer.isReadable()) {
            break;
        }
        boolean validFormat = true;
        int plusIndex = -1;
        for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) {
            byte dataChar = buffer.getByte(i);
            if (!Character.isDigit(dataChar)) {
                if (dataChar == '+') {
                    plusIndex = i;
                    break;
                } else {
                    validFormat = false;
                    break;
                }
            }
        }
        if (!validFormat) {
            break;
        }

        if (plusIndex == -1) {
            packet.setAckId(parseLong(buffer));
            break;
        } else {
            packet.setAckId(parseLong(buffer, plusIndex));
            buffer.readerIndex(plusIndex + 1);

            ByteBufInputStream in = new ByteBufInputStream(buffer);
            AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId());
            AckArgs args = jsonSupport.readAckArgs(in, callback.getResultClass());
            packet.setArgs(args.getArgs());
        }
        break;
    }

    case DISCONNECT:
    case HEARTBEAT:
    case NOOP:
        break;
    }

    buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes());
    return packet;
}

From source file:ws.wamp.jawampa.transport.netty.WampDeserializationHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    if (readState != ReadState.Reading)
        return;/*  www  . j  a v  a  2s. c o  m*/

    ObjectMapper objectMapper = serialization.getObjectMapper();
    if (frame instanceof TextWebSocketFrame) {
        // Only want Text frames when text subprotocol
        if (!serialization.isText())
            throw new IllegalStateException("Received unexpected TextFrame");

        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;

        // If we receive an invalid frame on of the following functions will throw
        // This will lead Netty to closing the connection
        ArrayNode arr = objectMapper.readValue(new ByteBufInputStream(textFrame.content()), ArrayNode.class);

        if (logger.isDebugEnabled()) {
            logger.debug("Deserialized Wamp Message: {}", arr.toString());
        }

        WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
        out.add(recvdMessage);
    } else if (frame instanceof BinaryWebSocketFrame) {
        // Only want Binary frames when binary subprotocol
        if (serialization.isText())
            throw new IllegalStateException("Received unexpected BinaryFrame");

        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;

        // If we receive an invalid frame on of the following functions will throw
        // This will lead Netty to closing the connection
        ArrayNode arr = objectMapper.readValue(new ByteBufInputStream(binaryFrame.content()), ArrayNode.class);

        if (logger.isDebugEnabled()) {
            logger.debug("Deserialized Wamp Message: {}", arr.toString());
        }

        WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
        out.add(recvdMessage);
    } else if (frame instanceof PongWebSocketFrame) {
        // System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        // System.out.println("WebSocket Client received closing");
        readState = ReadState.Closed;
    }
}