Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:spark.network.netty.FileClientHandler.java

License:Apache License

@Override
public ByteBuf newInboundBuffer(ChannelHandlerContext ctx) {
    // Use direct buffer if possible.
    return ctx.alloc().ioBuffer();
}

From source file:tk.jomp16.irc.netty.NettyEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception {
    if (msg.length() == 0) {
        return;//from ww w . j  a v a  2s.com
    }

    log.debug(msg);

    out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg + "\n"), charset));
}

From source file:tp.MyJZLibDecoder.java

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

    if (!in.isReadable()) {
        return;/*from  ww  w . j av  a 2  s.  c  om*/
    }

    try {
        // Configure input.
        int inputLength = in.readableBytes();
        //totalBytes += inputLength;
        z.avail_in = inputLength;
        if (in.hasArray()) {
            z.next_in = in.array();
            z.next_in_index = in.arrayOffset() + in.readerIndex();
        } else {
            byte[] array = new byte[inputLength];
            in.getBytes(in.readerIndex(), array);
            z.next_in = array;
            z.next_in_index = 0;
        }
        int oldNextInIndex = z.next_in_index;

        // Configure output.
        int maxOutputLength = inputLength << 1;
        ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength);

        try {
            loop: for (;;) {
                z.avail_out = maxOutputLength;
                decompressed.ensureWritable(maxOutputLength);
                z.next_out = decompressed.array();
                z.next_out_index = decompressed.arrayOffset() + decompressed.writerIndex();
                int oldNextOutIndex = z.next_out_index;

                // Decompress 'in' into 'out'
                int resultCode = z.inflate(JZlib.Z_SYNC_FLUSH);
                int outputLength = z.next_out_index - oldNextOutIndex;
                if (outputLength > 0) {
                    decompressed.writerIndex(decompressed.writerIndex() + outputLength);
                }

                switch (resultCode) {
                case JZlib.Z_NEED_DICT:
                    if (dictionary == null) {
                        ZlibUtil.fail(z, "decompression failure", resultCode);
                    } else {
                        resultCode = z.inflateSetDictionary(dictionary, dictionary.length);
                        if (resultCode != JZlib.Z_OK) {
                            ZlibUtil.fail(z, "failed to set the dictionary", resultCode);
                        }
                    }
                    break;
                case JZlib.Z_STREAM_END:
                    finished = true; // Do not decode anymore.
                    z.inflateEnd();
                    break loop;
                case JZlib.Z_OK:
                    break;
                case JZlib.Z_BUF_ERROR:
                    if (z.avail_in <= 0) {
                        //ZlibUtil.fail(z, "decompression failure [Z_BUF_ERROR] ", resultCode);
                        break loop;

                    }
                    break;
                default:
                    ZlibUtil.fail(z, "decompression failure", resultCode);
                }
            }
        } finally {
            in.skipBytes(z.next_in_index - oldNextInIndex);

            //System.err.println("[recived][numBytes] = "+inputLength);
            if (decompressed.isReadable()) {
                out.add(decompressed);
            } else {
                decompressed.release();
            }

        }
    } finally {
        // Deference the external references explicitly to tell the VM that
        // the allocated byte arrays are temporary so that the call stack
        // can be utilized.
        // I'm not sure if the modern VMs do this optimization though.
        z.next_in = null;
        z.next_out = null;
    }
}

From source file:tp.MyJZLibEncoder.java

private ChannelFuture finishEncode(final ChannelHandlerContext ctx, ChannelPromise promise) {
    if (!finished.compareAndSet(false, true)) {
        promise.setSuccess();/* w ww  .  j  a v  a  2  s.co  m*/
        return promise;
    }

    ByteBuf footer = ctx.alloc().buffer();
    synchronized (deflater) {
        deflater.finish();
        while (!deflater.finished()) {
            int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length);
            footer.writeBytes(encodeBuf, 0, numBytes);
        }
        if (gzip) {
            int crcValue = (int) crc.getValue();
            int uncBytes = deflater.getTotalIn();
            footer.writeByte(crcValue);
            footer.writeByte(crcValue >>> 8);
            footer.writeByte(crcValue >>> 16);
            footer.writeByte(crcValue >>> 24);
            footer.writeByte(uncBytes);
            footer.writeByte(uncBytes >>> 8);
            footer.writeByte(uncBytes >>> 16);
            footer.writeByte(uncBytes >>> 24);
        }
        deflater.end();
    }

    return ctx.writeAndFlush(footer, promise);
}

From source file:uk.ac.lancs.stopcock.netty.OpenFlowEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Container container, List<Object> objects)
        throws Exception {
    /* Construct a ByteBuf with the expected size of the output OpenFlow packet. */
    ByteBuf output = channelHandlerContext.alloc().buffer(container.getHeader().getLength());

    /* Write the binary data blob. */
    output.writeBytes(container.getData());

    /* Add back to the Netty pipeline. */
    objects.add(output);//from   w  w  w  . j  a va 2  s .c  o  m
}

From source file:uk.co.thinkofdeath.prismarine.network.CipherCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    byte[] data;/*from  ww w  .ja v  a2  s  .c om*/
    int offset = 0;
    int dataSize = in.readableBytes();
    if (!in.isDirect()) {
        data = in.array();
        offset = in.arrayOffset();
        in.skipBytes(in.readableBytes());
    } else {
        if (deDataBuffer.length < dataSize) {
            deDataBuffer = new byte[dataSize];
        }
        in.readBytes(deDataBuffer, 0, dataSize);
        data = deDataBuffer;
    }

    int size = cipherDecrypt.getOutputSize(dataSize);
    ByteBuf buf = ctx.alloc().heapBuffer(size);
    buf.writerIndex(cipherDecrypt.update(data, offset, dataSize, buf.array(), buf.arrayOffset()));
    out.add(buf);
}

From source file:uk.co.thinkofdeath.prismarine.network.CompressionCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    MCByteBuf buf = new MCByteBuf(in);
    int size = buf.readVarInt();
    if (size == 0) {
        out.add(buf.readBytes(buf.readableBytes()));
    } else {/*  ww w . j a v a 2 s  .  co m*/
        CompressionInfo ci = info.get();
        if (ci.decompBuffer.length < in.readableBytes()) {
            ci.decompBuffer = new byte[in.readableBytes()];
        }
        int count = in.readableBytes();
        in.readBytes(ci.decompBuffer, 0, count);
        ci.inflater.setInput(ci.decompBuffer, 0, count);

        // Use heap buffers so we can just access the internal array
        ByteBuf oBuf = ctx.alloc().heapBuffer(size);
        oBuf.writerIndex(ci.inflater.inflate(oBuf.array(), oBuf.arrayOffset(), size));
        out.add(oBuf);
        ci.inflater.reset();
    }
}

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.ChunkEndPoint.java

License:Apache License

@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, context.alloc().buffer());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Allow-Methods", "POST");
    if (request.getMethod() == OPTIONS) {
        response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
    }/*from   www .  j  av a2 s . c o m*/

    if (request.getMethod() == POST) {
        String[] args = request.content().toString(Charsets.UTF_8).split(":");
        ByteBuf out = response.content();
        if (plugin.getChunkManager(plugin.getTargetWorld()).getChunkBytes(Integer.parseInt(args[0]),
                Integer.parseInt(args[1]), out)) {
            response.headers().add("Content-Encoding", "gzip");
        } else {
            out.writeBytes(new byte[1]);
        }
    }
    sendHttpResponse(context, request, response);
}

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.InternalWebServer.java

License:Apache License

@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception {
    if (request.getMethod() != HttpMethod.GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED));
        return;//from  w  ww  .ja  v a2 s. c om
    }
    String modified = request.headers().get(IF_MODIFIED_SINCE);
    if (modified != null && !modified.isEmpty()) {
        Date modifiedDate = format.parse(modified);

        if (modifiedDate.equals(plugin.getStartUpDate())) {
            sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED));
            return;
        }
    }

    String path = uri.getPath();
    if (path.equals("/")) {
        path = "/index.html";
    }

    ByteBuf buffer;
    try (InputStream stream = this.getClass().getClassLoader().getResourceAsStream("www" + path)) {
        if (stream == null) {
            sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
            return;
        }
        ByteBufOutputStream out = new ByteBufOutputStream(context.alloc().buffer());
        IOUtils.copy(stream, out);
        buffer = out.buffer();
        out.close();
    }

    if (path.equals("/index.html")) {
        String page = buffer.toString(Charsets.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(plugin.getConfiguration().getPort()));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);

    response.headers().set(DATE, format.format(new Date()));
    response.headers().set(LAST_MODIFIED, format.format(plugin.getStartUpDate()));

    String ext = path.substring(path.lastIndexOf('.') + 1);
    String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain";
    if (type.startsWith("text/")) {
        type += "; charset=UTF-8";
    }
    response.headers().set(CONTENT_TYPE, type);
    sendHttpResponse(context, request, response);
}

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.PacketEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Packet<ServerPacketHandler> msg, List<Object> out)
        throws Exception {
    ByteBuf buf = ctx.alloc().buffer();
    buf.writeByte(Packets.getServerPacketId(msg));
    msg.write(new ByteBufPacketStream(buf));
    out.add(new BinaryWebSocketFrame(buf));
}