Example usage for io.netty.buffer ByteBufOutputStream ByteBufOutputStream

List of usage examples for io.netty.buffer ByteBufOutputStream ByteBufOutputStream

Introduction

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

Prototype

public ByteBufOutputStream(ByteBuf buffer) 

Source Link

Document

Creates a new stream which writes data to the specified buffer .

Usage

From source file:com.heliosapm.webrpc.jsonservice.JSONResponse.java

License:Apache License

/**
 * Returns an OutputStream that writes directly to a channel buffer which will be flushed to the channel on send
 * @return a channel buffer OutputStream 
 *//* w  w w  .j a va2  s .co  m*/
public OutputStream getChannelOutputStream() {
    if (content != null) {
        throw new RuntimeException("Cannot start OutputStream. Content already set");
    }
    if (channelOutputStream == null) {
        channelOutputStream = new ByteBufOutputStream(BufferManager.getInstance().buffer(8096)) {
            final ByteBuf buf = this.buffer();
            boolean closed = false;

            @Override
            public void close() throws IOException {
                if (!closed) {
                    closed = true;
                    super.flush();
                    super.close();
                    channel.write(buf);
                }
            }

            public void flush() throws IOException {
                super.flush();
                super.close();
            }
        };
    }
    return channelOutputStream;
}

From source file:com.heliosapm.webrpc.jsonservice.JSONResponse.java

License:Apache License

/**
 * Discards written content from the output stream, discarding the content and creating a new output stream
 *//*from   ww w  .  j  a  va2 s.co  m*/
public void resetChannelOutputStream() {
    if (content != null) {
        throw new RuntimeException("Cannot reset OutputStream. Content already set");
    }
    if (channelOutputStream != null) {
        ByteBuf buff = channelOutputStream.buffer();
        try {
            channelOutputStream.flush();
        } catch (Exception ex) {
        }
        buff.resetWriterIndex();
        channelOutputStream = new ByteBufOutputStream(BufferManager.getInstance().buffer(8096)) {
            final ByteBuf buf = this.buffer();
            boolean closed = false;

            @Override
            public void close() throws IOException {
                if (!closed) {
                    closed = true;
                    super.flush();
                    super.close();
                    channel.write(buf);
                }
            }

            public void flush() throws IOException {
                super.flush();
                super.close();
            }
        };
        jsonGen = null;
        //         try {
        //            jsonGen = JSON.getFactory().createGenerator(channelOutputStream);
        //         } catch (IOException e) {
        //            throw new RuntimeException("Failed to create a new JsonGenerator after reset", e);
        //         }
    }
}

From source file:com.jfastnet.peers.netty.KryoNettyPeer.java

License:Apache License

public ByteBuf getByteBuf(Message message) {
    ByteBuf data = Unpooled.buffer();/*from w ww.  j  a  va2s . c o  m*/
    config.serialiser.serialiseWithStream(message, new ByteBufOutputStream(data));

    int length = data.writerIndex();
    log.trace("Message size of {} is {}", message, length);
    //      if (length > config.maximumUdpPacketSize) {
    //         log.error("Message {} exceeds maximum size of {}! Size is {} byte", new Object[]{message, config.maximumUdpPacketSize, length});
    //         return null;
    //      }
    return data.retain();
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

public static FMLProxyPacket createSyncAuroraPointPacket(EntityPlayer player) {
    ByteBufOutputStream stream = new ByteBufOutputStream(Unpooled.buffer());
    FMLProxyPacket packet = null;//from   w w w  . j  a v a 2s . com
    try {
        stream.writeInt(SYNC_AURORA_POINT_CODE);
        stream.writeInt(RewriteHelper.getAuroraPoint(player));

        packet = new FMLProxyPacket(stream.buffer(), REWRITE_CHANNEL);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return packet;
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

public static FMLProxyPacket createSyncSkillPacket(EntityPlayer player) {
    ByteBufOutputStream stream = new ByteBufOutputStream(Unpooled.buffer());
    FMLProxyPacket packet = null;//from   w w w  . j  a  v  a2  s  .com
    try {
        stream.writeInt(SYNC_SKILL_CODE);
        for (RewriteHelper.Skill i : RewriteHelper.SKILLS) {
            stream.writeBoolean(RewriteHelper.hasSkill(player, i.id));
        }

        packet = new FMLProxyPacket(stream.buffer(), REWRITE_CHANNEL);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return packet;
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

public static FMLProxyPacket createLearnSkillPacket(int skillId) {
    ByteBufOutputStream stream = new ByteBufOutputStream(Unpooled.buffer());
    FMLProxyPacket packet = null;//  ww w  .j  ava2  s .  co  m
    try {
        stream.writeInt(LEARN_SKILL_CODE);
        stream.writeInt(skillId);

        packet = new FMLProxyPacket(stream.buffer(), REWRITE_CHANNEL);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return packet;
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

public static FMLProxyPacket createUseSkillPacket() {
    ByteBufOutputStream stream = new ByteBufOutputStream(Unpooled.buffer());
    FMLProxyPacket packet = null;//from  w w w .  j  a  va  2s.  co m
    try {
        stream.writeInt(USE_SKILL_CODE);

        packet = new FMLProxyPacket(stream.buffer(), REWRITE_CHANNEL);
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return packet;
}

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

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf)
 *///from w  w  w  .java 2 s . c  o m
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    if (msg instanceof Element) {
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(out));
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;
        if (streamStart.doesIncludeXmlHeader()) {
            out.writeBytes("<?xml version='1.0' encoding='UTF-8'?>".getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes("<stream:stream ".getBytes(StandardCharsets.UTF_8));
        if (streamStart.getId() != null) {
            out.writeBytes(String.format("id=\"%s\" ", streamStart.getId()).getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getFrom() != null) {
            out.writeBytes(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getTo() != null) {
            out.writeBytes(String.format("to=\"%s\" ", streamStart.getTo().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">"
                        .getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof KixmppStreamEnd) {
        out.writeBytes("</stream:stream>".getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof String) {
        out.writeBytes(((String) msg).getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;

        out.writeBytes(buf, 0, buf.readableBytes());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sending: [{}]", out.toString(StandardCharsets.UTF_8));
    }
}

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  ww  w .ja v a 2 s . c om

    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

/**
 * Expose serializer for sharing serialization and unit testing.
 *
 * @param registry// w  w w. j a  v a  2  s  .c  o  m
 * @param buf
 * @return
 * @throws IOException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ByteBuf serializeToByteBuf(MessageRegistry registry, ByteBuf buf, Object msg) throws IOException {
    // write class id
    int classIdx = registry.getIdFromClass(msg.getClass());
    buf.writeInt(classIdx);

    // write serialized object
    Schema schema = RuntimeSchema.getSchema(msg.getClass());
    LinkedBuffer linkedBuffer = LinkedBuffer.allocate(1024);
    ProtostuffIOUtil.writeTo(new ByteBufOutputStream(buf), msg, schema, linkedBuffer);

    return buf;
}