Example usage for io.netty.buffer ByteBuf readableBytes

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

Introduction

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

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:com.flowpowered.network.processor.simple.SimpleMessageProcessor.java

License:MIT License

@Override
public final synchronized ByteBuf processOutbound(ChannelHandlerContext ctx, final ByteBuf input,
        ByteBuf buffer) {/*from ww  w.  j  a  v a  2 s.co  m*/
    int remaining;
    while ((remaining = input.readableBytes()) > 0) {
        int clamped = Math.min(remaining, capacity);
        input.readBytes(encodingByteBuffer, 0, clamped);
        writeEncode(encodingByteBuffer, clamped);
        int read;
        while ((read = readEncode(encodingByteBuffer)) > 0) {
            buffer.writeBytes(encodingByteBuffer, 0, read);
        }
    }
    return buffer;
}

From source file:com.flowpowered.network.processor.simple.SimpleMessageProcessor.java

License:MIT License

@Override
public final synchronized ByteBuf processInbound(ChannelHandlerContext ctx, final ByteBuf input,
        ByteBuf buffer) {//w  ww . j av a 2 s.c  o m
    int remaining;
    while ((remaining = input.readableBytes()) > 0) {
        int clamped = Math.min(remaining, capacity);
        input.readBytes(decodingByteBuffer, 0, clamped);
        writeDecode(decodingByteBuffer, clamped);
        int read;
        while ((read = readDecode(decodingByteBuffer)) > 0) {
            buffer.writeBytes(decodingByteBuffer, 0, read);
        }
    }
    return buffer;
}

From source file:com.flowpowered.networking.pipeline.MessageProcessorDecoderTest.java

License:MIT License

@Test
public void test() throws Exception {
    // Preprocessor basically is split into two parts
    // Part 1 is just a direct copy
    // Part 2 negates all bytes before copying
    final AtomicReference<MessageProcessor> processor = new AtomicReference<>();
    MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) {
        @Override/* w w w.  j a  va  2  s  . c o m*/
        protected MessageProcessor getProcessor() {
            return processor.get();
        }
    };

    // Set up a fake ChannelHandlerContext
    FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup();
    AtomicReference<ByteBuf> ref = new AtomicReference<>();
    fake.setReference(ref);
    LinkedList<byte[]> outputList = new LinkedList<byte[]>();

    Random r = new Random();

    // Get some random bytes for data
    byte[] input = new byte[LENGTH];
    r.nextBytes(input);

    boolean breakOccured = false;
    int position = 0;

    for (int i = 0; i < input.length;) {
        // Simulate real data read
        int burstSize = r.nextInt(512);
        // With a 1/10 chance of having an extra-large burst
        if (r.nextInt(10) == 0) {
            burstSize *= 10;
        }

        // Final burst needs to be clamped
        if (i + burstSize > input.length) {
            burstSize = input.length - i;
        }

        // And we can't negate in the middle of a burst
        if (i + burstSize > BREAK && !breakOccured) {
            burstSize = BREAK - i;
        }

        // Write info to a new ByteBuf
        final ByteBuf buf = Unpooled.buffer(burstSize);
        buf.retain();
        buf.writeBytes(input, i, burstSize);
        i += burstSize;

        // Fake a read
        processorDecoder.channelRead(fake, buf);

        final ByteBuf returned = ref.get();

        while (returned != null && true) {
            int packetSize = r.nextInt(128) + 1;
            if (r.nextInt(10) == 0) {
                packetSize *= 20;
            }

            if (packetSize > returned.readableBytes()) {
                packetSize = returned.readableBytes();
            }
            if (position + packetSize > BREAK && !breakOccured) {
                packetSize = BREAK - position;
            }
            if (position + packetSize > LENGTH) {
                packetSize = LENGTH - position;
            }

            if (packetSize == 0) {
                break;
            }

            byte[] array = new byte[packetSize];

            returned.readBytes(array);
            position += packetSize;

            if (position == BREAK) {
                processor.set(new NegatingProcessor(512));
                breakOccured = true;
            }
            outputList.add(array);
        }
    }

    // Get the output data and combine into one array
    byte[] output = new byte[LENGTH];
    int i = 0;
    for (byte[] array : outputList) {
        for (int j = 0; j < array.length; j++) {
            output[i++] = array[j];
        }
    }

    for (i = 0; i < input.length; i++) {
        byte expected = i < BREAK ? input[i] : (byte) ~input[i];
        if (output[i] != expected) {
            for (int j = Math.max(0, i - 10); j <= i + 10; j++) {
                System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j])
                        + " " + Integer.toBinaryString(output[j]));
            }
        }

        if (i < BREAK) {
            assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got "
                    + output[i] + ". Break is: " + BREAK, output[i] == input[i]);
        } else {
            assertTrue(
                    "Input/Output mismatch at position " + i + ", after the processor change. Expected "
                            + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK,
                    output[i] == (byte) ~input[i]);
        }
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) {
    int processed = data.readableBytes() + padding;
    if (endOfStream) {
        sendResponse(ctx, streamId, data.retain());
    }//from w w  w  . j  ava2  s .  co m
    return processed;
}

From source file:com.flysoloing.learning.network.netty.portunification.PortUnificationServerHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        return;//from  www. ja v  a 2s  . co  m
    }

    if (isSsl(in)) {
        enableSsl(ctx);
    } else {
        final int magic1 = in.getUnsignedByte(in.readerIndex());
        final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
        if (isGzip(magic1, magic2)) {
            enableGzip(ctx);
        } else if (isHttp(magic1, magic2)) {
            switchToHttp(ctx);
        } else if (isFactorial(magic1)) {
            switchToFactorial(ctx);
        } else {
            // Unknown protocol; discard everything and close the connection.
            in.clear();
            ctx.close();
        }
    }
}

From source file:com.foilen.smalltools.net.commander.channel.CommanderDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    logger.debug("Trying to decode a message. Readable bytes {}", in.readableBytes());

    // classNameSize:int
    int len = in.readInt();

    // className:String
    String className = in.readBytes(len).toString(CharsetTools.UTF_8);

    // jsonContentSize:int
    len = in.readInt();//from w  w  w  .j  a v a  2  s .  c om

    // jsonContent:String
    String jsonContent = in.readBytes(len).toString(CharsetTools.UTF_8);

    // Add the JSON runnable to the list
    logger.debug("Decoding class {} with json {}", className, jsonContent);

    out.add(JsonTools.readFromString(jsonContent, Class.forName(className)));
    logger.debug("Completely got a {}", className);
}

From source file:com.friz.audio.network.AudioSessionContext.java

License:Open Source License

public void writeResponse(HttpVersion version, ByteBuf container) {
    HttpResponse response = new DefaultHttpResponse(version, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, container.readableBytes());

    channel.write(response);//  www .ja  v a  2  s  . c  o m
    channel.write(container);
    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
}

From source file:com.friz.audio.network.AudioSessionContext.java

License:Open Source License

/**
 * Processes the file requests.// w  w  w .  jav a 2s. c  o  m
 * @throws IOException The exception thrown if an i/o error occurs.
 */
public void processFileQueue() {
    FileRequestEvent request;
    synchronized (fileQueue) {
        request = fileQueue.pop();
        if (fileQueue.isEmpty()) {
            idle = true;
        } else {
            service.addAudioContext(this);
            idle = false;
        }
    }
    if (request != null) {
        int type = request.getType();
        int file = request.getFile();
        int crc = request.getCrc();
        int version = request.getVersion();
        HttpVersion http = request.getHttp();

        ByteBuf buf = Unpooled.buffer();
        if (type == 255 && file == 255) {
            buf = Unpooled.wrappedBuffer(server.getCache().getChecksum());
        } else {
            if (server.getCache().getReferenceTable(type).getEntry(file).getCrc() != crc
                    || server.getCache().getReferenceTable(type).getEntry(file).getVersion() != version) {
                writeResponse(http, buf);
                return;
            }

            try {
                buf = Unpooled.wrappedBuffer(server.getCache().getStore().read(type, file));
                if (type != 255)
                    buf = buf.slice(0, buf.readableBytes() - 2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        writeResponse(http, buf);
    }
}

From source file:com.friz.game.network.codec.LoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    int type = buf.readUnsignedByte();
    int size = buf.readUnsignedShort();

    int major = buf.readInt();
    int minor = buf.readInt();
    boolean dropped = buf.readBoolean();

    int rsaSize = buf.readUnsignedShort();
    byte[] rsa = new byte[rsaSize];
    buf.readBytes(rsa);/*from www.  ja v  a2s  .  co m*/

    ByteBuf rsaBuf = Unpooled.wrappedBuffer(
            new BigInteger(rsa).modPow(Constants.LOGIN_EXPONENT, Constants.LOGIN_MODULUS).toByteArray());
    int rsaMagic = rsaBuf.readUnsignedByte();

    int[] key = new int[4];
    for (int i = 0; i < key.length; i++)
        key[i] = rsaBuf.readInt();

    int block = rsaBuf.readUnsignedByte();

    if (block == 1 || block == 3) {
        int code = rsaBuf.readUnsignedMedium();
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 1);
    } else if (block == 0) {
        int trusted = rsaBuf.readInt();
    } else if (block == 2) {
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 4);
    }

    String password = BufferUtils.getString(rsaBuf);

    long serverKey = rsaBuf.readLong();
    long clientKey = rsaBuf.readLong();

    byte[] xtea = new byte[buf.readableBytes()];
    buf.readBytes(xtea);
    ByteBuf xteaBuf = Unpooled.wrappedBuffer(new XTEA(xtea).decrypt(key).toByteArray());

    String username = "";
    boolean asString = xteaBuf.readBoolean();
    if (asString)
        username = BufferUtils.getString(xteaBuf);
    else
        username = BufferUtils.getBase37(xteaBuf);

    int display = xteaBuf.readUnsignedByte();
    int width = xteaBuf.readUnsignedShort();
    int height = xteaBuf.readUnsignedShort();

    int multisample = xteaBuf.readByte();

    byte[] uid = new byte[24];
    for (int i = 0; i < uid.length; i++)
        uid[i] = xteaBuf.readByte();

    String token = BufferUtils.getString(xteaBuf);

    int prefSize = xteaBuf.readUnsignedByte();
    int prefVersion = xteaBuf.readUnsignedByte();
    int aPref = xteaBuf.readUnsignedByte();
    int antiAliasing = xteaBuf.readUnsignedByte();
    int aPref1 = xteaBuf.readUnsignedByte();
    int bloom = xteaBuf.readUnsignedByte();
    int brightness = xteaBuf.readUnsignedByte();
    int buildArea = xteaBuf.readUnsignedByte();
    int aPref2 = xteaBuf.readUnsignedByte();
    int flickeringEffects = xteaBuf.readUnsignedByte();
    int fog = xteaBuf.readUnsignedByte();
    int groundBlending = xteaBuf.readUnsignedByte();
    int groundDecoration = xteaBuf.readUnsignedByte();
    int idleAnimations = xteaBuf.readUnsignedByte();
    int lighting = xteaBuf.readUnsignedByte();
    int sceneryShadows = xteaBuf.readUnsignedByte();
    int aPref3 = xteaBuf.readUnsignedByte();
    int nullPref = xteaBuf.readUnsignedByte();
    int orthoMode = xteaBuf.readUnsignedByte();
    int particles = xteaBuf.readUnsignedByte();
    int removeRoofs = xteaBuf.readUnsignedByte();
    int maxScreenSize = xteaBuf.readUnsignedByte();
    int skyboxes = xteaBuf.readUnsignedByte();
    int mobShadows = xteaBuf.readUnsignedByte();
    int textures = xteaBuf.readUnsignedByte();
    int desiredToolkit = xteaBuf.readUnsignedByte();
    int nullPref1 = xteaBuf.readUnsignedByte();
    int water = xteaBuf.readUnsignedByte();
    int screenSize = xteaBuf.readUnsignedByte();
    int customCursors = xteaBuf.readUnsignedByte();
    int graphics = xteaBuf.readUnsignedByte();
    int cpu = xteaBuf.readUnsignedByte();
    int aPref4 = xteaBuf.readUnsignedByte();
    int safeMode = xteaBuf.readUnsignedByte();
    int aPref5 = xteaBuf.readUnsignedByte();
    int aPref6 = xteaBuf.readUnsignedByte();
    int aPref7 = xteaBuf.readUnsignedByte();
    int soundEffectsVolume = xteaBuf.readUnsignedByte();
    int areaSoundsVolume = xteaBuf.readUnsignedByte();
    int voiceOverVolume = xteaBuf.readUnsignedByte();
    int musicVolume = xteaBuf.readUnsignedByte();
    int themeMusicVolume = xteaBuf.readUnsignedByte();
    int steroSound = xteaBuf.readUnsignedByte();

    int infoVersion = xteaBuf.readUnsignedByte();
    int osType = xteaBuf.readUnsignedByte();
    boolean arch64 = xteaBuf.readBoolean();
    int versionType = xteaBuf.readUnsignedByte();
    int vendorType = xteaBuf.readUnsignedByte();
    int jMajor = xteaBuf.readUnsignedByte();
    int jMinor = xteaBuf.readUnsignedByte();
    int jPatch = xteaBuf.readUnsignedByte();
    boolean falseBool = xteaBuf.readBoolean();
    int heapSize = xteaBuf.readUnsignedShort();
    int pocessorCount = xteaBuf.readUnsignedByte();
    int cpuPhyscialMemory = xteaBuf.readUnsignedMedium();
    int cpuClock = xteaBuf.readUnsignedShort();
    String gpuName = BufferUtils.getJagString(xteaBuf);
    String aString = BufferUtils.getJagString(xteaBuf);
    String dxVersion = BufferUtils.getJagString(xteaBuf);
    String aString1 = BufferUtils.getJagString(xteaBuf);
    int gpuDriverMonth = xteaBuf.readUnsignedByte();
    int gpuDriverYear = xteaBuf.readUnsignedShort();
    String cpuType = BufferUtils.getJagString(xteaBuf);
    String cpuName = BufferUtils.getJagString(xteaBuf);
    int cpuThreads = xteaBuf.readUnsignedByte();
    int anInt = xteaBuf.readUnsignedByte();
    int anInt1 = xteaBuf.readInt();
    int anInt2 = xteaBuf.readInt();
    int anInt3 = xteaBuf.readInt();
    int anInt4 = xteaBuf.readInt();
    String aString2 = BufferUtils.getString(xteaBuf);

    int anInt5 = xteaBuf.readInt();
    int anInt6 = xteaBuf.readInt();
    int anInt7 = xteaBuf.readInt();
    String aString3 = BufferUtils.getString(xteaBuf);

    boolean hasAdditional = xteaBuf.readBoolean();
    String additionalInfo = "";
    if (hasAdditional)
        additionalInfo = BufferUtils.getString(xteaBuf);

    int anInt8 = xteaBuf.readUnsignedByte();
    int anInt9 = xteaBuf.readUnsignedByte();
    int anInt10 = xteaBuf.readUnsignedByte();
    int anInt11 = xteaBuf.readInt();
    String aString4 = BufferUtils.getString(xteaBuf);

    boolean newWorld = xteaBuf.readBoolean();
    int lobbyId = xteaBuf.readUnsignedShort();

    int[] checksums = new int[(xteaBuf.readableBytes() / 4) + 1];
    for (int i = 0; i < checksums.length; i++) {
        if (i == 32)
            checksums[i] = -1;
        else
            checksums[i] = xteaBuf.readInt();
    }
}

From source file:com.friz.lobby.network.codec.LobbyInitDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    if (!buf.isReadable())
        return;/*  w  w w  .  java2 s  . c o m*/

    out.add(new LobbyInitRequestEvent(buf.readUnsignedByte()));

    if (buf.isReadable())
        out.add(new RecycleEvent(buf.readBytes(buf.readableBytes())));
}