Example usage for io.netty.buffer ByteBuf copy

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

Introduction

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

Prototype

public abstract ByteBuf copy();

Source Link

Document

Returns a copy of this buffer's readable bytes.

Usage

From source file:com.savageboy74.savagetech.handler.packets.PacketPipeline.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {
    ByteBuf buffer = Unpooled.buffer();
    Class<? extends AbstractPacket> apClass = msg.getClass();

    if (!this.packets.contains(apClass)) {
        throw new NullPointerException(Strings.Packets.NOT_REGISTERED + apClass.getCanonicalName());
    }/*from w ww . java  2 s . c  o m*/

    byte discriminator = (byte) this.packets.indexOf(apClass);
    buffer.writeByte(discriminator);
    msg.encodeInto(ctx, buffer);

    FMLProxyPacket packet = new FMLProxyPacket(buffer.copy(),
            ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
    out.add(packet);

}

From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("RCVD: {}", ByteUtil.createString(in));
    }//  w  w  w.  j a va  2 s  .co  m

    ByteBuf data;

    // if there was data left from the last decode call, create a composite ByteBuf that contains both
    // previous and new data
    if (previousBuf != null) {
        CompositeByteBuf cbuf = Unpooled.compositeBuffer(2);
        cbuf.addComponent(previousBuf.copy());
        cbuf.addComponent(in);
        cbuf.writerIndex(previousBuf.readableBytes() + in.readableBytes());
        data = cbuf;
        // release the data from the previous decode call
        previousBuf.release();
        previousBuf = null;
    } else {
        data = in;
    }

    while (data.isReadable()) {
        // check for single ACK/NAK/CAN
        if (data.readableBytes() == 1 && isSingleByteFrame(data, data.readerIndex())) {
            out.add(createSingleByteFrame(data));
        } else {
            boolean foundFrame = false;
            // search for a valid frame in the data
            for (int searchStartIx = data.readerIndex(); searchStartIx < data.readerIndex()
                    + data.readableBytes(); searchStartIx++) {
                if (data.getByte(searchStartIx) == DataFrame.START_OF_FRAME) {
                    int frameEndIx = scanForFrame(data, searchStartIx);
                    if (frameEndIx > 0) {
                        if (searchStartIx > data.readerIndex() && isSingleByteFrame(data, searchStartIx - 1)) {
                            data.readerIndex(searchStartIx - 1);
                            out.add(createSingleByteFrame(data));
                        } else if (searchStartIx > data.readerIndex()) {
                            data.readerIndex(searchStartIx);
                        }
                        DataFrame df = createDataFrame(data);
                        if (df != null) {
                            out.add(df);
                            data.readByte(); // discard checksum
                            foundFrame = true;
                        } else {
                            logger.debug("Unable to determine frame type");
                        }
                    }
                }
            }
            if (!foundFrame) {
                previousBuf = data.copy();
                break;
            }
        }
    }

    // make sure we read from the input ByteBuf so Netty doesn't throw an exception
    in.readBytes(in.readableBytes());

    logger.trace("Done processing received data: {}", out);
}

From source file:com.yahoo.pulsar.common.compression.CommandsTest.java

License:Apache License

private int computeChecksum(MessageMetadata msgMetadata, ByteBuf compressedPayload) throws IOException {
    int metadataSize = msgMetadata.getSerializedSize();
    int metadataFrameSize = 4 + metadataSize;
    ByteBuf metaPayloadFrame = PooledByteBufAllocator.DEFAULT.buffer(metadataFrameSize, metadataFrameSize);
    ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(metaPayloadFrame);
    metaPayloadFrame.writeInt(metadataSize);
    msgMetadata.writeTo(outStream);/*from   w  w w  .j a va2 s.co m*/
    ByteBuf payload = compressedPayload.copy();
    ByteBuf metaPayloadBuf = DoubleByteBuf.get(metaPayloadFrame, payload);
    int computedChecksum = Crc32cChecksum.computeChecksum(metaPayloadBuf);
    outStream.recycle();
    metaPayloadBuf.release();
    return computedChecksum;
}

From source file:de.jackwhite20.comix.handler.HandshakeHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out)
        throws Exception {
    ByteBuf copy = byteBuf.copy();

    Protocol.readVarInt(byteBuf);/*w ww .  j  a v a2  s.c o m*/

    int packetId = Protocol.readVarInt(byteBuf);

    if (packetId == 0) {
        if (protocolMode == ProtocolState.HANDSHAKE) {
            Protocol.readVarInt(byteBuf);
            Protocol.readString(byteBuf);
            byteBuf.readUnsignedShort();
            protocolMode = ProtocolState.valueOf((byte) Protocol.readVarInt(byteBuf));
        }

        if (protocolMode == ProtocolState.STATUS) {
            ByteBuf responseBuffer = Unpooled.buffer();
            String response = Comix.getInstance().getStatusResponseString();
            response = response.replace("%online%", "" + Comix.getInstance().getClientsOnline()); // Replace online count
            Protocol.writeVarInt(3 + response.length(), responseBuffer); // Size
            Protocol.writeVarInt(0, responseBuffer); // Packet id
            Protocol.writeString(response, responseBuffer); // Data as json string
            channelHandlerContext.writeAndFlush(responseBuffer);

            // Sending Pong instant because otherwise the pong will not receive properly!
            ByteBuf pongBuffer = Unpooled.buffer();
            Protocol.writeVarInt(9, pongBuffer);
            Protocol.writeVarInt(1, pongBuffer);
            pongBuffer.writeLong(0);
            channelHandlerContext.writeAndFlush(pongBuffer);

            channelHandlerContext.close();
        }

        if (protocolMode == ProtocolState.LOGIN) {
            if (byteBuf.readableBytes() == 0) {
                upstreamHandler.connectDownstream(copy);

                downstreamInitialized = true;

                out.add(copy.retain());

                return;
            }

            String name = Protocol.readString(byteBuf);

            //TODO: Improve
            if (Comix.getInstance().getComixConfig().isMaintenance()) {
                if (Comix.getInstance().isWhitelistEnabled()) {
                    if (!Comix.getInstance().isWhitelisted(name)) {
                        kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage());
                    }
                } else {
                    kick(channelHandlerContext,
                            Comix.getInstance().getComixConfig().getMaintenanceKickMessage());
                }

                channelHandlerContext.close();
                return;
            } else if (Comix.getInstance().isWhitelistEnabled() && !Comix.getInstance().isWhitelisted(name)) {
                kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage());

                channelHandlerContext.close();
                return;
            }

            if (!downstreamInitialized)
                upstreamHandler.connectDownstream(copy);
            else
                upstreamHandler.addInitialPacket(copy);

            ComixClient comixClient = new ComixClient(name, upstreamHandler.getDownstreamHandler(),
                    upstreamHandler);
            Comix.getInstance().addClient(comixClient);
            upstreamHandler.setClient(comixClient);

            channelHandlerContext.channel().pipeline().remove(this);

            Comix.getLogger().log(Level.INFO, "Handshake", "Player logged in: " + name);

            out.add(copy.retain());
        }
    }
}

From source file:divconq.ctp.stream.UngzipStream.java

License:Open Source License

@Override
public ReturnOption handle(FileDescriptor file, ByteBuf data) {
    if (file == FileDescriptor.FINAL)
        return this.downstream.handle(file, data);

    if (this.ufile == null)
        this.initializeFileValues(file);

    // inflate the payload into 1 or more outgoing buffers set in a queue
    ByteBuf in = data;//from  w  ww .  ja va2s . c  o  m

    if (in != null) {
        ByteBuf rem = this.remnant;

        ByteBuf src = ((rem != null) && rem.isReadable()) ? Unpooled.copiedBuffer(rem, in) : in;

        this.inflate(src);

        // if there are any unread bytes here we need to store them and combine with the next "handle"
        // this would be rare since the header and footer are small, but it is possible and should be handled
        // file content has its own "in progress" buffer so no need to worry about that
        this.remnant = src.isReadable() ? src.copy() : null; // TODO wrap or slice here? we need copy above

        if (in != null)
            in.release();

        if (rem != null)
            rem.release();

        if (OperationContext.get().getTaskRun().isKilled())
            return ReturnOption.DONE;
    }

    // write all buffers in the queue
    while (this.outlist.size() > 0) {
        ReturnOption ret = this.nextMessage();

        if (ret != ReturnOption.CONTINUE)
            return ret;
    }

    // if we reached done and we wrote all the buffers, then send the EOF marker if not already
    if ((this.gzipState == GzipState.DONE) && !this.eofsent)
        return this.nextMessage();

    // otherwise we need more data
    return ReturnOption.CONTINUE;
}

From source file:divconq.http.multipart.AbstractDiskHttpData.java

License:Apache License

@Override
public void addContent(ByteBuf buffer, boolean last) throws IOException {
    if (buffer != null) {
        try {// ww w .  j  a  va2  s.c  o  m
            int localsize = buffer.readableBytes();
            checkSize(size + localsize);
            if (definedSize > 0 && definedSize < size + localsize) {
                throw new IOException("Out of size: " + (size + localsize) + " > " + definedSize);
            }
            ByteBuffer byteBuffer = buffer.nioBufferCount() == 1 ? buffer.nioBuffer()
                    : buffer.copy().nioBuffer();
            int written = 0;
            if (file == null) {
                file = tempFile();
            }
            if (fileChannel == null) {
                FileOutputStream outputStream = new FileOutputStream(file);
                fileChannel = outputStream.getChannel();
            }
            while (written < localsize) {
                written += fileChannel.write(byteBuffer);
            }
            size += localsize;
            buffer.readerIndex(buffer.readerIndex() + written);
        } finally {
            // Release the buffer as it was retained before and we not need a reference to it at all
            // See https://github.com/netty/netty/issues/1516
            buffer.release();
        }
    }
    if (last) {
        if (file == null) {
            file = tempFile();
        }
        if (fileChannel == null) {
            FileOutputStream outputStream = new FileOutputStream(file);
            fileChannel = outputStream.getChannel();
        }
        fileChannel.force(false);
        fileChannel.close();
        fileChannel = null;
        setCompleted();
    } else {
        if (buffer == null) {
            throw new NullPointerException("buffer");
        }
    }
}

From source file:divconq.http.multipart.DiskAttribute.java

License:Apache License

@Override
public Attribute copy() {
    DiskAttribute attr = new DiskAttribute(getName());
    attr.setCharset(getCharset());// w w w  . j  a  va 2  s  . c om
    ByteBuf content = content();
    if (content != null) {
        try {
            attr.setContent(content.copy());
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
    return attr;
}

From source file:divconq.http.multipart.DiskFileUpload.java

License:Apache License

@Override
public FileUpload copy() {
    DiskFileUpload upload = new DiskFileUpload(getName(), getFilename(), getContentType(),
            getContentTransferEncoding(), getCharset(), size);
    ByteBuf buf = content();
    if (buf != null) {
        try {// w  w w  .j a  v  a 2s.c  o  m
            upload.setContent(buf.copy());
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
    return upload;
}

From source file:divconq.http.multipart.HttpPostMultipartRequestDecoder.java

License:Apache License

/**
 * Initialized the internals from a new chunk
 *
 * @param content/*  w ww. jav  a 2  s  . c  om*/
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostMultipartRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}

From source file:divconq.http.multipart.HttpPostStandardRequestDecoder.java

License:Apache License

/**
 * Initialized the internals from a new chunk
 *
 * @param content/* w ww .j a v  a  2  s .  c o  m*/
 *            the new received chunk
 * @throws ErrorDataDecoderException
 *             if there is a problem with the charset decoding or other
 *             errors
 */
@Override
public HttpPostStandardRequestDecoder offer(HttpContent content) {
    checkDestroyed();

    // Maybe we should better not copy here for performance reasons but this will need
    // more care by the caller to release the content in a correct manner later
    // So maybe something to optimize on a later stage
    ByteBuf buf = content.content();
    if (undecodedChunk == null) {
        undecodedChunk = buf.copy();
    } else {
        undecodedChunk.writeBytes(buf);
    }
    if (content instanceof LastHttpContent) {
        isLastChunk = true;
    }
    parseBody();
    if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
        undecodedChunk.discardReadBytes();
    }
    return this;
}