Example usage for io.netty.buffer ByteBuf release

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

Introduction

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

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:com.uber.tchannel.tracing.TracingPropagationTest.java

License:Open Source License

private static TraceResponse callDownstreamThriftAsync(String remainingEncodings) throws Exception {
    ThriftRequest<Example> request = new ThriftRequest.Builder<Example>("tchannel-name", "Behavior::asynctrace")
            .setTimeout(1, TimeUnit.MINUTES).setBody(new Example(remainingEncodings, 0)).build();

    TFuture<ThriftResponse<Example>> responsePromise = subChannel.send(request, tchannel.getHost(),
            tchannel.getListeningPort());

    ThriftResponse<Example> thriftResponse = responsePromise.get();
    assertNull(thriftResponse.getError());
    String json = thriftResponse.getBody(Example.class).getAString();
    thriftResponse.release();// ww  w .  j  a v a 2 s  . co m
    ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(json.length());
    byteBuf.writeBytes(json.getBytes());
    TraceResponse response = new JSONSerializer().decodeBody(byteBuf, TraceResponse.class);
    byteBuf.release();
    return response;
}

From source file:com.vethrfolnir.game.network.login.LoginServerClientHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buff = (ByteBuf) msg;

    int opcode = buff.readUnsignedByte();

    switch (opcode) {
    case 0xBB:// ww w .j  a  v a 2s  .  c  om
        ServerKill.read(serverClient, buff);
        break;
    case 0xA1:
        int newId = buff.readInt();
        RecievedAlternativeId.read(serverClient, buff, newId);
        break;
    default:
        log.warn("Unknown packet 0x" + PrintData.fillHex(opcode, 2) + ". Dump: "
                + PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
        break;
    }

    buff.release();
}

From source file:com.vethrfolnir.game.network.mu.MuChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buff = (msg instanceof ByteBuffer) ? ctx.alloc().buffer().writeBytes((ByteBuffer) msg)
            : (ByteBuf) msg;//ww w  .j  a v a2 s . com

    buff.readerIndex(2);

    int opcode = buff.readUnsignedByte();
    switch (opcode) { // double opcode
    case 0xf1:
    case 0xf3:
    case 0x0e:
    case 0x03:
        buff.readerIndex(buff.readerIndex() - 1);
        opcode = buff.readUnsignedShort(); // ex 0xF1_03
        break;
    default:
        break;
    }

    if (opcode == 0xe00) { // Time packet?
        buff.clear();
        buff.release();
        return;
    }

    ReadPacket packet = clientpackets.get(opcode);

    if (packet != null) {
        MuClient client = ctx.channel().attr(MuClient.ClientKey).get();
        //System.out.println("Got opcode: 0x"+PrintData.fillHex(opcode, 2)+ " packet = \n"+packet.getClass().getSimpleName());
        packet.read(client, buff);
    } else {
        log.warn("Unknown packet[opcode = 0x" + PrintData.fillHex(opcode, 2) + "]. Dump: ");
        log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
    }

    //log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));

    if (buff.refCnt() > 0) {
        //System.out.println("Handler Release when packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]");
        buff.release();
    }
}

From source file:com.vethrfolnir.game.network.mu.packets.MuReadPacket.java

License:Open Source License

protected String readS(ByteBuf buff, int max) {
    try {/* w w  w .  j  a  va  2 s  .  com*/
        ByteBuf copy = buff.readBytes(max);
        String str = new String(copy.array(), "ISO-8859-1");
        copy.release();
        return str.trim();
    } catch (UnsupportedEncodingException e) {
        log.warn("Failed reading string!", e);
    }

    return null;
}

From source file:com.vethrfolnir.login.network.game.GameChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buff = (ByteBuf) msg;

    int opcode = buff.readUnsignedByte();

    switch (opcode) {
    case 0x0A: // first registration
        ServerRegistration.read(null, buff, nameService, ctx);
        break;/*  w w  w  . ja  v a 2 s .  c o  m*/
    case 0x0B: {
        nameService.getServer(ctx.channel()).setOnlinePlayers(buff.readInt());
        ;
    }
    default:
        log.warn("Unknown packet[opcode = 0x" + PrintData.fillHex(opcode, 2) + "]");
        break;
    }
    buff.release();
}

From source file:com.vethrfolnir.login.network.mu.ClientChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buff = (ByteBuf) msg;

    switch (buff.getUnsignedByte(0)) {
    case 0xC1:/*from  www  .  ja  va2  s  .c  o  m*/
    case 0xC2:
    case 0xC3:
    case 0xC4:
        break;
    default:
        ctx.close();
        buff.release(); //TODO: maybe add a flood protector?
        log.warn("Client[" + ctx.channel() + "] is not a mu online client! Disconnecting!");
        return;
    }

    // we are not interested in the header and size;
    buff.readerIndex(2);

    int opcode = buff.readUnsignedShort();

    switch (opcode) {

    case 0xf4_03: { // Request Server information
        int serverId = buff.readUnsignedByte();
        ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN);

        WritePacket packet = SendServerInfo.StaticPacket;
        packet.write(null, buf, nameService, serverId);
        packet.markLength(buf);
        ;

        ctx.writeAndFlush(buf);
        break;
    }
    case 0xf4_06: { // Request Server list
        ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN);

        WritePacket packet = SendServerLists.StaticPacket;
        packet.write(null, buf, nameService);
        packet.markLength(buf);

        ctx.writeAndFlush(buf);
        break;
    }
    default:
        log.warn("Unkown packet[OPCODE = " + Integer.toHexString(opcode) + "] Dump: "
                + PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
        ctx.close();
        break;
    }
    buff.release();
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpEventStreamHandler.java

License:Open Source License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    ByteBuf rawEvent = (ByteBuf) super.decode(ctx, buffer);
    if (rawEvent == null) {
        return null;
    }/*from   w  ww  .  ja v  a2s . c  om*/
    String serializedEvent = rawEvent.toString(ServerSentEventConverter.ENCODING_CHARSET);
    rawEvent.release();
    ServerSentEvent event = ServerSentEventConverter.INSTANCE.deserialize(serializedEvent);
    EventStreamMessage message = new EventStreamMessage();
    message.event = event;
    return message;
}

From source file:com.whizzosoftware.hobson.dsc.api.codec.DSCFrameDecoder.java

License:Open Source License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    logger.trace("decode: {}", buffer.toString(CharsetUtil.UTF_8));

    ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);

    if (frame != null) {
        try {/*from   w  w  w.j a v a  2  s. c  om*/
            if (frame.readableBytes() >= 3) {
                String cmdId = new String(new byte[] { frame.getByte(0), frame.getByte(1), frame.getByte(2) });
                switch (cmdId) {
                case CodeRequired.ID:
                    return new CodeRequired();
                case CommandAcknowledge.ID:
                    return new CommandAcknowledge();
                case CommandError.ID:
                    return new CommandError();
                case LCDUpdate.ID:
                    int lineNumber = frame.getByte(3) - '0';
                    int columnNumber = Integer
                            .parseInt(new String(new byte[] { frame.getByte(4), frame.getByte(5) }));
                    int length = Integer
                            .parseInt(new String(new byte[] { frame.getByte(6), frame.getByte(7) }));
                    return new LCDUpdate(lineNumber, columnNumber,
                            frame.slice(8, length).toString(CharsetUtil.UTF_8));
                case LEDStatus.ID:
                    return new LEDStatus(LEDStatus.LEDType.forOrdinal(frame.getByte(3) - '0'),
                            LEDStatus.Status.forOrdinal(frame.getByte(4) - '0'));
                case SoftwareVersion.ID:
                    return new SoftwareVersion(frame.slice(3, 4).toString(CharsetUtil.UTF_8));
                case PartitionBusy.ID:
                    return new PartitionBusy(frame.getByte(3) - '0');
                case PartitionNotReady.ID:
                    return new PartitionNotReady(frame.getByte(3) - '0');
                case PartitionReady.ID:
                    return new PartitionReady(frame.getByte(3) - '0');
                case TroubleLEDOff.ID:
                    return new TroubleLEDOff(frame.getByte(3) - '0');
                case ZoneOpen.ID:
                    return new ZoneOpen(Integer.parseInt(
                            new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) })));
                case ZoneRestored.ID:
                    return new ZoneRestored(Integer.parseInt(
                            new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) })));
                case TimeDateBroadcast.ID:
                    return new TimeDateBroadcast(frame.slice(3, 10).toString(CharsetUtil.UTF_8));
                default:
                    logger.debug("Ignoring unknown command frame: {}", buffer.toString(CharsetUtil.UTF_8));
                    return null;
                }
            } else {
                throw new CorruptedFrameException("Frame should not be less than 3 bytes");
            }
        } finally {
            frame.release();
        }
    } else {
        return null;
    }
}

From source file:com.whizzosoftware.hobson.ssdp.SSDPInboundHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
    final DatagramPacket p = (io.netty.channel.socket.DatagramPacket) o;
    ByteBuf buf = p.content();
    byte[] b = new byte[buf.readableBytes()];
    buf.readBytes(b);// w  ww  . j  a va 2s .  com
    final String data = new String(b, 0, b.length, "UTF8");
    buf.release();
    logger.trace("Received data from {}: {}", p.sender().getHostString(), data);

    // publish the advertisement
    try {
        final SSDPPacket packet = SSDPPacket.createWithData(data);
        // ignore packets that originated from Hobson
        if (!p.sender().getAddress().equals(InetAddress.getLocalHost())) {
            if ("M-SEARCH".equals(packet.getMethod())) {
                context.executeInEventLoop(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            context.processDiscoveryRequest(p.sender(), packet);
                        } catch (Throwable e) {
                            logger.error("Error processing discovery packet", e);
                        }
                    }
                });
            } else if (packet.getUSN() != null && packet.getLocation() != null) {
                // execute this in the event loop so we can get on with processing UDP packets as
                // quickly as possible
                context.executeInEventLoop(new Runnable() {
                    @Override
                    public void run() {
                        context.publishDeviceAdvertisement(
                                new DeviceAdvertisement.Builder(packet.getUSN(), SSDPPacket.PROTOCOL_ID)
                                        .rawData(data).object(packet).build(),
                                false);
                    }
                });
            } else {
                logger.trace("Ignoring SSDP packet with USN {} and location: {}", packet.getUSN(),
                        packet.getLocation());
            }
        }
    } catch (Throwable e) {
        logger.error("Error creating SSDP packet", e);
    }
}

From source file:com.wx3.galacdecks.networking.HttpHandler.java

License:Open Source License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from   ww w .  j  av  a 2s  . co m*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}