Java 类io.netty.buffer.ByteBufOutputStream 实例源码

项目:JRediClients    文件:KryoCodec.java   
@Override
public ByteBuf encode(Object in) throws IOException {
    Kryo kryo = null;
    ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
    try {
        ByteBufOutputStream baos = new ByteBufOutputStream(out);
        Output output = new Output(baos);
        kryo = kryoPool.get();
        kryo.writeClassAndObject(output, in);
        output.close();
        return baos.buffer();
    } catch (Exception e) {
        out.release();
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RedissonKryoCodecException(e);
    } finally {
        if (kryo != null) {
            kryoPool.yield(kryo);
        }
    }
}
项目:xrpc    文件:Example.java   
private static FullHttpResponse getDino(XrpcRequest request, List<Dino> dinos) {
  try {
    DinoGetRequest getRequest =
        DinoGetRequest.parseFrom(CodedInputStream.newInstance(request.getData().nioBuffer()));
    Optional<Dino> dinoOptional =
        dinos.stream().filter(xs -> xs.getName().equals(getRequest.getName())).findFirst();

    if (dinoOptional.isPresent()) {
      DinoGetReply getReply = DinoGetReply.newBuilder().setDino(dinoOptional.get()).build();
      ByteBuf resp = request.getByteBuf();
      resp.ensureWritable(CodedOutputStream.computeMessageSizeNoTag(getReply), true);
      getReply.writeTo(new ByteBufOutputStream(resp));

      return Recipes.newResponse(
          HttpResponseStatus.OK,
          request.getByteBuf().writeBytes(resp),
          Recipes.ContentType.Application_Octet_Stream);
    }

  } catch (IOException e) {
    return Recipes.newResponseBadRequest("Malformed GetDino Request: " + e.getMessage());
  }

  return Recipes.newResponseOk("Dino not Found");
}
项目:DecompiledMinecraft    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }
}
项目:DecompiledMinecraft    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }
}
项目:rskj    文件:JsonRpcWeb3ServerHandler.java   
private HttpResponse processRequest(FullHttpRequest request) throws JsonProcessingException {
    HttpResponse response;
    ByteBuf responseContent = Unpooled.buffer();
    HttpResponseStatus responseStatus = HttpResponseStatus.OK;
    try (ByteBufOutputStream os = new ByteBufOutputStream(responseContent);
         ByteBufInputStream is = new ByteBufInputStream(request.content().retain())){
        int result = jsonRpcServer.handleRequest(is, os);
        responseStatus = HttpResponseStatus.valueOf(DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result));
    } catch (Exception e) {
        LOGGER.error("Unexpected error", e);
        responseContent = buildErrorContent(JSON_RPC_SERVER_ERROR_HIGH_CODE, HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase());
        responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    } finally {
        response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            responseStatus,
            responseContent
        );
    }
    return response;
}
项目:BaseClient    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }
}
项目:BaseClient    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }
}
项目:RakNetty    文件:GameWrapperPacket.java   
@Override
public void write(RakNetByteBuf out) {
    super.write(out);

    RakNetOutputStream os = new RakNetOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ByteBufOutputStream(out))));
    RakNetByteBuf payload = RakNetByteBuf.buffer();
    body.write(payload);
    try {
        int bodySize = payload.readableBytes();
        byte[] bytes = new byte[bodySize];
        payload.readBytes(bytes);
        os.writeUnsignedVarInt(bodySize);
        os.write(bytes);
    } catch (Exception ignored) {
    } finally {
        payload.release();
    }
}
项目:fresco_floodlight    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:Backmemed    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }

    return this;
}
项目:CustomWorldGen    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }

    return this;
}
项目:SDN-Multicast    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:arscheduler    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:CrystalMod    文件:ByteBufUtils.java   
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag)
{
    if (tag == null)
    {
        buf.writeByte(0);
        return;
    }

    try
    {
        CompressedStreamTools.write(tag, new ByteBufOutputStream(buf));
    }
    catch (IOException ioexception)
    {
        ModLogger.error("IOException while trying to write a NBTTagCompound to ByteBuf");
        throw new EncoderException(ioexception);
    }
}
项目:twill    文件:TrackerService.java   
private void writeResourceReport(Channel channel) {
  ByteBuf content = Unpooled.buffer();
  Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8);
  try {
    reportAdapter.toJson(resourceReport.get(), writer);
    writer.close();
  } catch (IOException e) {
    LOG.error("error writing resource report", e);
    writeAndClose(channel, new DefaultFullHttpResponse(
      HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
      Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8)));
    return;
  }

  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  HttpUtil.setContentLength(response, content.readableBytes());
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
  channel.writeAndFlush(response);
}
项目:floodlight1.2-delay    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:blockbuster    文件:PacketFrames.java   
@Override
public void toBytes(ByteBuf buf)
{
    ByteBufOutputStream output = new ByteBufOutputStream(buf);

    try
    {
        output.writeUTF(this.filename);
        output.writeInt(this.frames.size());

        for (Frame frame : this.frames)
        {
            frame.toBytes(output);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
项目:HeliosStreams    文件:JSONOps.java   
/**
 * Serializes the passed object to the passed byte buffer or a new one if the passed one is null
 * @param object The object to serialize
 * @param buff The buffer to write to, or null to create a new one
 * @return the written buffer
 */
public static ByteBuf serialize(final Object object, final ByteBuf buff) {
    if (object == null) throw new IllegalArgumentException("Object was null");
    final ByteBuf _buff = buff==null ? byteBufAllocator.buffer() : buff;
    final OutputStream os = new ByteBufOutputStream(_buff);
    try {
        serialize(object, os);
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    } finally {
        try { os.close(); } catch (Exception x) {/* No Op */}
    }
    return _buff;
}
项目:HeliosStreams    文件:JSONOps.java   
/**
 * Serializes the passed object to an off-heap buffer and returns an InputStream to read it back
 * @param obj The object to serialize
 * @return an InputStream to read back the JSON serialized object 
 */
public static InputStream serializeOffHeapLoopBack(final Object obj) {
    if(obj==null) throw new IllegalArgumentException("The passed object was null");
    final ByteBuf cb = byteBufAllocator.buffer();
    final OutputStream os = new ByteBufOutputStream(cb);

    try {
        serialize(obj, os);
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    }

    return new ByteBufInputStream(cb) {
        @Override
        public void close() throws IOException {                
            super.close();
            try { cb.release(); } catch (Exception x) {/* No Op */}
        }
    };
}
项目:HeliosStreams    文件:JSONOps.java   
/**
 * Serializes the passed object to the passed byte buffer or a new one if the passed one is null
 * @param object The object to serialize
 * @param buff The buffer to write to, or null to create a new one
 * @return the written buffer
 */
public static ByteBuf serialize(final Object object, final ByteBuf buff) {
    if (object == null) throw new IllegalArgumentException("Object was null");
    final ByteBuf _buff = buff==null ? byteBufAllocator.buffer() : buff;
    final OutputStream os = new ByteBufOutputStream(_buff);
    try {
        serialize(object, os);
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    } finally {
        try { os.close(); } catch (Exception x) {/* No Op */}
    }
    return _buff;
}
项目:HeliosStreams    文件:JSONOps.java   
/**
 * Serializes and gzips the passed object to the passed byte buffer or a new one if the passed one is null
 * @param object The object to serialize
 * @param buff The buffer to write to, or null to create a new one
 * @return the written buffer
 */
public static ByteBuf serializeAndGzip(final Object object, final ByteBuf buff) {
    if (object == null) throw new IllegalArgumentException("Object was null");
    final ByteBuf _buff = buff==null ? byteBufAllocator.buffer() : buff;

    final OutputStream os = new ByteBufOutputStream(_buff);

    try {
        final GZIPOutputStream gos = new GZIPOutputStream(os);
        serialize(object, gos);
        gos.finish();
        gos.flush();
        gos.close();
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    } finally {
        try { os.close(); } catch (Exception x) {/* No Op */}
    }
    return _buff;
}
项目:HeliosStreams    文件:JSONOps.java   
/**
 * Serializes the passed object to an off-heap buffer and returns an InputStream to read it back
 * @param obj The object to serialize
 * @return an InputStream to read back the JSON serialized object 
 */
public static InputStream serializeOffHeapLoopBack(final Object obj) {
    if(obj==null) throw new IllegalArgumentException("The passed object was null");
    final ByteBuf cb = byteBufAllocator.buffer();
    final OutputStream os = new ByteBufOutputStream(cb);

    try {
        serialize(obj, os);
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    }

    return new ByteBufInputStream(cb) {
        @Override
        public void close() throws IOException {                
            super.close();
            try { cb.release(); } catch (Exception x) {/* No Op */}
        }
    };
}
项目:floodlight-hardware    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:ACAMPController    文件:ThriftFrameEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out)
        throws Exception {

    int lengthIndex = out.writerIndex();
    // length field, will be filled in later.
    out.writeInt(0);

    int startIndex = out.writerIndex();
    ByteBufOutputStream os = new ByteBufOutputStream(out);
    TCompactProtocol thriftProtocol =
            new TCompactProtocol(new TIOStreamTransport(os));
    msg.write(thriftProtocol);
    os.close();
    int endIndex = out.writerIndex();

    // update the length field
    int length = endIndex - startIndex;
    out.setInt(lengthIndex, length);
}
项目:jlogstash-input-plugin    文件:CompressedBatchEncoder.java   
@Override
protected ByteBuf getPayload(ChannelHandlerContext ctx, Batch batch) throws IOException {
    ByteBuf payload = super.getPayload(ctx, batch);

    Deflater deflater = new Deflater();
    ByteBufOutputStream output = new ByteBufOutputStream(ctx.alloc().buffer());
    DeflaterOutputStream outputDeflater = new DeflaterOutputStream(output, deflater);

    byte[] chunk = new byte[payload.readableBytes()];
    payload.readBytes(chunk);
    outputDeflater.write(chunk);
    outputDeflater.close();

    ByteBuf content = ctx.alloc().buffer();
    content.writeByte(batch.getProtocol());
    content.writeByte('C');


    content.writeInt(output.writtenBytes());
    content.writeBytes(output.buffer());

    return content;
}
项目:intellij-ce-playground    文件:SocketLock.java   
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
  ByteBuf buffer = context.alloc().ioBuffer(1024);
  boolean success = false;
  try {
    ByteBufOutputStream out = new ByteBufOutputStream(buffer);
    for (String path : myLockedPaths) out.writeUTF(path);
    out.writeUTF(PATHS_EOT_RESPONSE);
    out.close();
    success = true;
  }
  finally {
    if (!success) {
      buffer.release();
    }
  }
  context.writeAndFlush(buffer);
}
项目:LanternServer    文件:LanternFavicon.java   
/**
 * Encodes the buffered image into the encoded favicon string.
 * 
 * @param image the buffered image
 * @return the favicon string
 */
private static String encode(BufferedImage image) throws IOException {
    checkArgument(image.getWidth() == 64, "favicon must be 64 pixels wide");
    checkArgument(image.getHeight() == 64, "favicon must be 64 pixels high");

    ByteBuf buf = Unpooled.buffer();

    try {
        ImageIO.write(image, "PNG", new ByteBufOutputStream(buf));
        ByteBuf base64 = Base64.encode(buf);

        try {
            return FAVICON_PREFIX + base64.toString(StandardCharsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}
项目:CivCraft    文件:MessageTechTreeUpdate.java   
@Override
public void toBytes(ByteBuf buf) {
    CivLog.info("toBytes(), side == " + FMLCommonHandler.instance().getEffectiveSide());
    ByteBuf b = Unpooled.buffer();
    NBTTagCompound nbt = new NBTTagCompound();
    TechTree.currentTree.save(nbt);
    try {
        CompressedStreamTools.writeCompressed(nbt, new ByteBufOutputStream(b));
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    int i = b.readableBytes();
    buf.writeInt(i);
    buf.writeBytes(b);
}
项目:netty4.0.27Learn    文件:CompatibleObjectEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS);
    ObjectOutputStream oos = oosAttr.get();
    if (oos == null) {
        oos = newObjectOutputStream(new ByteBufOutputStream(out));
        ObjectOutputStream newOos = oosAttr.setIfAbsent(oos);
        if (newOos != null) {
            oos = newOos;
        }
    }

    synchronized (oos) {
        if (resetInterval != 0) {
            // Resetting will prevent OOM on the receiving side.
            writtenObjects ++;
            if (writtenObjects % resetInterval == 0) {
                oos.reset();
            }
        }

        oos.writeObject(msg);
        oos.flush();
    }
}
项目:DistributedLog4j    文件:Log4jAppenderHandler.java   
@Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof DatagramPacket){
            ctx.write(msg, promise);
            return;
        }

        ByteBuf buf = ctx.alloc().heapBuffer();
//      int startIdx = buf.writerIndex();

        ByteBufOutputStream bout = new ByteBufOutputStream(buf);
//      bout.write(LENGTH_PLACEHOLDER);
        ObjectOutputStream oout = new CompactObjectOutputStream(bout);
        oout.writeObject(msg);
        oout.flush();
        oout.close();
//      int endIdx = buf.writerIndex();

//      buf.setInt(startIdx, endIdx - startIdx - 4);
        Object data = new DatagramPacket(buf, new InetSocketAddress("255.255.255.255", port));
        ctx.write(data, promise);
    }
项目:DistributedLog4j    文件:Log4jAppenderHandler.java   
@Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof DatagramPacket){
            ctx.write(msg, promise);
            return;
        }

        ByteBuf buf = ctx.alloc().heapBuffer();
//      int startIdx = buf.writerIndex();

        ByteBufOutputStream bout = new ByteBufOutputStream(buf);
//      bout.write(LENGTH_PLACEHOLDER);
        ObjectOutputStream oout = new CompactObjectOutputStream(bout);
        oout.writeObject(msg);
        oout.flush();
        oout.close();
//      int endIdx = buf.writerIndex();

//      buf.setInt(startIdx, endIdx - startIdx - 4);
        Object data = new DatagramPacket(buf, multicastAddress);
        ctx.write(data, promise);
    }
项目:Prismarine    文件:MinecraftServer.java   
private void a(ServerPing serverping) {
    File file = this.d("server-icon.png");

    if (file.isFile()) {
        ByteBuf bytebuf = Unpooled.buffer();

        try {
            BufferedImage bufferedimage = ImageIO.read(file);

            Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
            Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
            ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf));
            ByteBuf bytebuf1 = Base64.encode(bytebuf);

            serverping.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
        } catch (Exception exception) {
            MinecraftServer.LOGGER.error("Couldn\'t load server icon", exception);
        } finally {
            bytebuf.release();
        }
    }

}
项目:armeria    文件:ArmeriaMessageFramer.java   
private ByteBuf writeCompressed(ByteBuf message) throws IOException {
    CompositeByteBuf compressed = alloc.compositeBuffer();
    try (OutputStream compressingStream = compressor.compress(new ByteBufOutputStream(compressed))) {
        compressingStream.write(ByteBufUtil.getBytes(message));
    } finally {
        message.release();
    }

    int numCompressedBytes = compressed.readableBytes();
    if (maxOutboundMessageSize >= 0 && numCompressedBytes > maxOutboundMessageSize) {
        compressed.release();
        throw Status.RESOURCE_EXHAUSTED
                .withDescription(
                        String.format(
                                "message too large %d > %d", numCompressedBytes, maxOutboundMessageSize))
                .asRuntimeException();
    }

    ByteBuf header = alloc.buffer(HEADER_LENGTH);
    header.writeByte(COMPRESSED);
    header.writeInt(numCompressedBytes);
    compressed.addComponent(true, 0, header);

    return compressed;
}
项目:jetstream    文件:KryoObjectEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    KryoContext kryoContext = kryoContextHolder.get();
    Kryo kryo = kryoContext.getKryo();
    Output output = kryoContext.getOut();
    output.clear();
    ByteBufOutputStream bout = new ByteBufOutputStream(out);
    int startIdx = out.writerIndex();
    bout.write(LENGTH_PLACEHOLDER);
    output.setOutputStream(bout);
    output.writeByte(StreamMessageDecoder.KRYO_STREAM_VERSION);
    kryo.writeClassAndObject(output, msg);
    output.flush();
    bout.flush();
    bout.close();
    output.close();

    int endIdx = out.writerIndex();

    out.setInt(startIdx, endIdx - startIdx - 4);
}
项目:Resilience-Client-Source    文件:MinecraftServer.java   
private void func_147138_a(ServerStatusResponse p_147138_1_)
{
    File var2 = this.getFile("server-icon.png");

    if (var2.isFile())
    {
        ByteBuf var3 = Unpooled.buffer();

        try
        {
            BufferedImage var4 = ImageIO.read(var2);
            Validate.validState(var4.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
            Validate.validState(var4.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
            ImageIO.write(var4, "PNG", new ByteBufOutputStream(var3));
            ByteBuf var5 = Base64.encode(var3);
            p_147138_1_.func_151320_a("data:image/png;base64," + var5.toString(Charsets.UTF_8));
        }
        catch (Exception var6)
        {
            logger.error("Couldn\'t load server icon", var6);
        }
    }
}
项目:netty4study    文件:CompatibleObjectEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS);
    ObjectOutputStream oos = oosAttr.get();
    if (oos == null) {
        oos = newObjectOutputStream(new ByteBufOutputStream(out));
        ObjectOutputStream newOos = oosAttr.setIfAbsent(oos);
        if (newOos != null) {
            oos = newOos;
        }
    }

    synchronized (oos) {
        if (resetInterval != 0) {
            // Resetting will prevent OOM on the receiving side.
            writtenObjects ++;
            if (writtenObjects % resetInterval == 0) {
                oos.reset();
            }
        }

        oos.writeObject(msg);
        oos.flush();
    }
}
项目:mongowp    文件:NettyBsonDocumentWriter.java   
@Override
public Void visit(BsonBinary value, ByteBuf arg) {
  NonIoByteSource byteSource = value.getByteSource();

  UnsignedInteger unsignedSize;
  unsignedSize = UnsignedInteger.valueOf(byteSource.size());

  arg.writeInt(unsignedSize.intValue()).writeByte(value.getNumericSubType());

  try (OutputStream os = new ByteBufOutputStream(arg)) {
    value.getByteSource().copyTo(os);
  } catch (IOException ex) {
    throw new AssertionError("Unexpected IOException", ex);
  }
  return null;
}
项目:olingo-odata4    文件:ODataNettyHandlerImpl.java   
/** 
 * Copy OData content to netty content
 * @param input
 * @param response
 */
static void copyContent(final ReadableByteChannel input, final HttpResponse response) {
  WritableByteChannel output = null;
  try {
    ByteBuffer inBuffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);
    output = Channels.newChannel(new ByteBufOutputStream(((HttpContent)response).content()));
    while (input.read(inBuffer) > 0) {
      inBuffer.flip();
      output.write(inBuffer);
      inBuffer.clear();
    }
  } catch (IOException e) {
    throw new ODataRuntimeException("Error on reading request content", e);
  } finally {
    closeStream(input);
    closeStream(output);
  }
}
项目:enderutilities    文件:ByteBufUtilsEU.java   
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag)
{
    if (tag == null)
    {
        buf.writeByte(0);
        return;
    }

    try
    {
        CompressedStreamTools.write(tag, new ByteBufOutputStream(buf));
    }
    catch (IOException ioexception)
    {
        EnderUtilities.logger.error("IOException while trying to write a NBTTagCompound to ByteBuf");
        throw new EncoderException(ioexception);
    }
}
项目:ExpandedRailsMod    文件:PacketBuffer.java   
/**
 * Writes a compressed NBTTagCompound to this buffer
 */
public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt)
{
    if (nbt == null)
    {
        this.writeByte(0);
    }
    else
    {
        try
        {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));
        }
        catch (IOException ioexception)
        {
            throw new EncoderException(ioexception);
        }
    }

    return this;
}