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:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryRequestEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, SourceServerRequest request, List<Object> out)
        throws Exception {
    SourceRequestPacket packet = request.getMessage();
    byte[] deconstructedPacket = builder.deconstruct(packet);
    if (deconstructedPacket != null && deconstructedPacket.length > 0) {
        ByteBuf buffer = ctx.alloc().buffer(deconstructedPacket.length).writeBytes(deconstructedPacket);
        out.add(new DatagramPacket(buffer, request.recipient()));
    }//from  w  w w. j  a v  a  2s. c  o m
}

From source file:com.ibasco.agql.protocols.valve.steam.master.handlers.MasterServerRequestEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, MasterServerRequest request, List<Object> out)
        throws Exception {
    MasterServerRequestPacket packet = request.getMessage();
    byte[] deconstructedPacket = builder.deconstruct(packet);
    if (deconstructedPacket != null && deconstructedPacket.length > 0) {
        ByteBuf buffer = ctx.alloc().buffer(deconstructedPacket.length).writeBytes(deconstructedPacket);
        out.add(new DatagramPacket(buffer, request.recipient()));
    }//from  w ww. j a v  a 2s. com
}

From source file:com.kael.surf.net.codec.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Extract the sub-region of the specified buffer.
 * <p>/*from   w  w w . ja  v a2s. c  o  m*/
 * If you are sure that the frame and its content are not accessed after
 * the current {@link #decode(ChannelHandlerContext, ByteBuf)}
 * call returns, you can even avoid memory copy by returning the sliced
 * sub-region (i.e. <tt>return buffer.slice(index, length)</tt>).
 * It's often useful when you convert the extracted frame into an object.
 * Refer to the source code of {@link ObjectDecoder} to see how this method
 * is overridden to avoid memory copy.
 */
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
    ByteBuf frame = ctx.alloc().buffer(length);
    frame.writeBytes(buffer, index, length);
    return frame;
}

From source file:com.king.platform.net.http.integration.HttpPostWithInputStreamBody.java

License:Apache License

@Test
public void postBodyCustomHttpBody() throws Exception {
    final AtomicReference<byte[]> bodyContent = new AtomicReference<>();
    integrationServer.addServlet(new HttpServlet() {
        @Override/*from w  w w. j a v a2  s .c o  m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            byte[] body = readPostBody(req);
            bodyContent.set(body);

            resp.getWriter().write(okBody);
            resp.getWriter().flush();
        }
    }, "/testOk");

    BlockingHttpCallback httpCallback = new BlockingHttpCallback();
    httpClient.createPost("http://localhost:" + port + "/testOk").content(new HttpBody() {
        @Override
        public long getContentLength() {
            return content.length;
        }

        @Override
        public String getContentType() {
            return "application/binary";
        }

        @Override
        public Charset getCharacterEncoding() {
            return StandardCharsets.ISO_8859_1;
        }

        @Override
        public ChannelFuture writeContent(final ChannelHandlerContext ctx, boolean isSecure)
                throws IOException {
            final ChannelProgressivePromise promise = ctx.newProgressivePromise();
            promise.setProgress(0, content.length);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int index = 0;
                    int length = 1024;
                    while (true) {
                        ByteBuf byteBuf = ctx.alloc().buffer(length).writeBytes(content, index, length);
                        ctx.writeAndFlush(byteBuf).awaitUninterruptibly();
                        index += length;
                        if (index >= content.length) {
                            break;
                        }

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ignored) {
                        }

                        promise.setProgress(index, content.length);
                    }

                    promise.setSuccess();
                }
            }).start();

            return promise;
        }
    }).build().withHttpCallback(httpCallback).execute();

    httpCallback.waitForCompletion();

    assertArrayEquals(content, bodyContent.get());
    assertEquals(200, httpCallback.getStatusCode());
}

From source file:com.king.platform.net.http.netty.request.ByteArrayHttpBody.java

License:Apache License

@Override
public ChannelFuture writeContent(ChannelHandlerContext ctx) {
    ByteBuf byteBuf = ctx.alloc().buffer(content.length).writeBytes(content);
    return ctx.write(byteBuf, ctx.newProgressivePromise());
}

From source file:com.kixeye.kixmpp.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = null;//from w  w w.j av  a 2  s . c o m

    if (msg instanceof Element) {
        Element element = (Element) msg;

        if (element.getNamespace() == null || element.getNamespace() == Namespace.NO_NAMESPACE) {
            if ("stream".equals(element.getNamespacePrefix())) {
                element.setNamespace(Namespace.getNamespace("http://etherx.jabber.org/streams"));
            } else {
                element.setNamespace(Namespace.getNamespace("jabber:client"));

                IteratorIterable<Content> descendants = element.getDescendants();

                while (descendants.hasNext()) {
                    Content content = descendants.next();

                    if (content instanceof Element) {
                        Element descendantElement = (Element) content;
                        if (descendantElement.getNamespace() == null
                                || descendantElement.getNamespace() == Namespace.NO_NAMESPACE) {
                            descendantElement.setNamespace(element.getNamespace());
                        }
                    }
                }
            }
        }

        ByteBuf binaryData = ctx.alloc().buffer();
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(binaryData));

        frame = new TextWebSocketFrame(binaryData);
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;

        StringWriter writer = new StringWriter();

        if (streamStart.doesIncludeXmlHeader()) {
            writer.append("<?xml version='1.0' encoding='UTF-8'?>");
        }
        writer.append("<stream:stream ");
        if (streamStart.getId() != null) {
            writer.append(String.format("id=\"%s\" ", streamStart.getId()));
        }
        if (streamStart.getFrom() != null) {
            writer.append(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid()));
        }
        if (streamStart.getTo() != null) {
            writer.append(String.format("to=\"%s\" ", streamStart.getTo()));
        }
        writer.append(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">");

        frame = new TextWebSocketFrame(writer.toString());
    } else if (msg instanceof KixmppStreamEnd) {
        frame = new TextWebSocketFrame("</stream:stream>");
    } else if (msg instanceof String) {
        frame = new TextWebSocketFrame((String) msg);
    } else if (msg instanceof ByteBuf) {
        frame = new TextWebSocketFrame((ByteBuf) msg);
    }

    if (frame != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Sending: [{}]", frame.content().toString(StandardCharsets.UTF_8));
        }

        out.add(frame);
    }
}

From source file:com.kixeye.kixmpp.p2p.serialization.ProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof ByteBuf) {
        // already serialized so just pass through
        ByteBuf buf = (ByteBuf) msg;//from  w w  w. j a v a  2 s .c om
        out.add(buf.retain());
    } else {
        // serialize
        ByteBuf buf = ctx.alloc().buffer();
        serializeToByteBuf(registry, buf, msg);
        out.add(buf);
    }
}

From source file:com.l2jmobius.commons.network.codecs.LengthFieldBasedFrameEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
    final ByteBuf buf = ctx.alloc().buffer(2);
    final short length = (short) (msg.readableBytes() + 2);
    buf.writeShort(buf.order() != ByteOrder.LITTLE_ENDIAN ? Short.reverseBytes(length) : length);
    out.add(buf);/* ww  w  . j  a va2 s  .  co m*/
    out.add(msg.retain());
}

From source file:com.lambdaworks.redis.ProtectedModeTests.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {

    server = new MockTcpServer();

    server.addHandler(() -> {/* w w  w.j av a  2 s . c  o  m*/
        return new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {

                String message = getMessage();
                ByteBuf buffer = ctx.alloc().buffer(message.length() + 3);
                buffer.writeBytes("-".getBytes());
                buffer.writeBytes(message.getBytes());
                buffer.writeByte('\r').writeByte('\n');

                ctx.writeAndFlush(buffer).addListener(future -> {
                    ctx.close();
                });
            }
        };
    });

    server.initialize(TestSettings.nonexistentPort());

    client = RedisClient.create(TestClientResources.get(),
            RedisURI.create(TestSettings.host(), TestSettings.nonexistentPort()));
}

From source file:com.lambdaworks.redis.protocol.CommandEncoder.java

License:Apache License

@Override
protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, Object msg, boolean preferDirect) throws Exception {

    if (msg instanceof Collection) {

        if (preferDirect) {
            return ctx.alloc().ioBuffer(((Collection) msg).size() * 16);
        } else {/*  ww  w .  jav a  2s  .  c  o  m*/
            return ctx.alloc().heapBuffer(((Collection) msg).size() * 16);
        }
    }

    if (preferDirect) {
        return ctx.alloc().ioBuffer();
    } else {
        return ctx.alloc().heapBuffer();
    }
}