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:mods.railcraft.common.carts.EntityCartTank.java

License:Open Source License

@Override
public void writeSpawnData(ByteBuf data) {
    try {// w ww.  j av  a2 s.  c o m
        DataOutputStream byteStream = new DataOutputStream(new ByteBufOutputStream(data));
        DataTools.writeItemStack(getFilterItem(), byteStream);
    } catch (IOException ex) {
    }
}

From source file:mods.railcraft.common.carts.EntityLocomotive.java

License:Open Source License

@Override
public void writeSpawnData(ByteBuf data) {
    try {//from w ww  .  java  2  s .  c o m
        DataOutputStream byteStream = new DataOutputStream(new ByteBufOutputStream(data));
        byteStream.writeUTF(func_95999_t() != null ? func_95999_t() : "");
        byteStream.writeUTF(model);
    } catch (IOException ex) {
    }
}

From source file:name.osipov.alexey.server.ServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
            return;
        }//from  w w w  .ja  va 2 s  .  c om

        //String passkey = req.headers().get("passkey");

        // in case of large output this buffer will demand memory
        // writing directly to channel maybe more efficient...
        ByteBufOutputStream bufstream = new ByteBufOutputStream(Unpooled.buffer());
        JsonGenerator json = new JsonFactory().createGenerator(bufstream);
        json.writeStartObject();

        HttpResponseStatus status = HttpResponseStatus.INTERNAL_SERVER_ERROR;

        switch (req.getUri()) {
        case "/register": {
            User u = users.Register();
            json.writeNumberField("id", u.getId());
            json.writeBinaryField("key", u.getKey().asBinary());
            status = HttpResponseStatus.OK;
        }
            break;

        case "/statistics": {
            String hashed_key_base64 = req.headers().get("key");
            byte[] hashed_key = Base64.decodeBase64(hashed_key_base64);
            long salt = System.currentTimeMillis() / 1000 / 30;
            User u = users.getBySaltedHash(hashed_key, salt);
            if (u != null) {
                u.requestHappen();
                json.writeNumberField("id", u.getId());
                json.writeNumberField("requests", u.getRequests());
                status = HttpResponseStatus.OK;
            } else
                status = HttpResponseStatus.UNAUTHORIZED;
        }
            break;
        }

        json.writeEndObject();
        json.close();

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                bufstream.buffer());
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

        if (!HttpHeaders.isKeepAlive(req)) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:nats.codec.ClientFrameEncoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, ClientFrame frame, ByteBuf out) throws Exception {
    LOGGER.trace("Encoding '{}'", frame);

    if (frame instanceof ClientConnectFrame) {
        final ClientConnectFrame connectFrame = (ClientConnectFrame) frame;
        out.writeBytes(CMD_CONNECT);/*from ww  w  . j  a  va2s.c o m*/
        out.writeByte(' ');
        mapper.writeValue(new ByteBufOutputStream(out), connectFrame.getBody());
        out.writeBytes(ByteBufUtil.CRLF);
    } else if (frame instanceof ClientPingFrame) {
        out.writeBytes(PING);
    } else if (frame instanceof ClientPongFrame) {
        out.writeBytes(PONG);
    } else if (frame instanceof ClientPublishFrame) {
        final ClientPublishFrame message = (ClientPublishFrame) frame;
        out.writeBytes(CMD_PUBLISH);
        out.writeByte(' ');

        out.writeBytes(message.getSubject().getBytes(UTF8));
        out.writeByte(' ');

        final String replyTo = message.getReplyTo();
        if (replyTo != null) {
            out.writeBytes(replyTo.getBytes(UTF8));
            out.writeByte(' ');
        }

        final byte[] bodyBytes = message.getBody().getBytes(UTF8);
        ByteBufUtil.writeIntegerAsString(out, bodyBytes.length);
        out.writeBytes(ByteBufUtil.CRLF);
        out.writeBytes(bodyBytes);
        out.writeBytes(ByteBufUtil.CRLF);
    } else if (frame instanceof ClientSubscribeFrame) {
        final ClientSubscribeFrame message = (ClientSubscribeFrame) frame;
        out.writeBytes(CMD_SUBSCRIBE);
        out.writeByte(' ');
        out.writeBytes(message.getSubject().getBytes(UTF8));
        out.writeByte(' ');
        final String queueGroup = message.getQueueGroup();
        if (queueGroup != null) {
            out.writeBytes(queueGroup.getBytes(UTF8));
            out.writeByte(' ');
        }
        out.writeBytes(message.getId().getBytes(UTF8));
        out.writeBytes(ByteBufUtil.CRLF);
    } else if (frame instanceof ClientUnsubscribeFrame) {
        final ClientUnsubscribeFrame message = (ClientUnsubscribeFrame) frame;
        out.writeBytes(CMD_UNSUBSCRIBE);
        out.writeByte(' ');
        out.writeBytes(message.getId().getBytes(UTF8));
        final Integer maxMessages = message.getMaxMessages();
        if (maxMessages != null) {
            out.writeByte(' ');
            ByteBufUtil.writeIntegerAsString(out, maxMessages);
        }
        out.writeBytes(ByteBufUtil.CRLF);
    } else {
        throw new NatsException("Unable to encode client message of type " + frame.getClass().getName());
    }
}

From source file:net.mcsproject.daemon.network.PacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, ByteBuf byteBuf)
        throws Exception {
    byte id = packetRegistry.getIdByPacket(packet.getClass());

    byteBuf.writeByte(id);/*from   w w  w .j  a v a2 s .c om*/
    packet.write(new ByteBufOutputStream(byteBuf));
}

From source file:net.minecrell.quartz.status.QuartzFavicon.java

License:MIT License

private static String encode(BufferedImage favicon) throws IOException {
    checkArgument(favicon.getWidth() == 64, "favicon must be 64 pixels wide");
    checkArgument(favicon.getHeight() == 64, "favicon must be 64 pixels high");

    ByteBuf buf = Unpooled.buffer();/* w w w.j a  va 2  s.c  o m*/
    try {
        ImageIO.write(favicon, "PNG", new ByteBufOutputStream(buf));
        ByteBuf base64 = Base64.encode(buf);
        try {
            return FAVICON_PREFIX + base64.toString(Charsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}

From source file:org.apache.bookkeeper.common.coder.VarIntCoder.java

License:Apache License

@Override
public void encode(Integer value, ByteBuf buf) {
    checkNotNull(value, "Can not encode a null integer value");
    checkNotNull(buf, "Can not encode into a null output buffer");

    ByteBufOutputStream output = new ByteBufOutputStream(buf);

    try {//  w  w  w.  j a v  a 2  s  .co  m
        VarInt.encode(value.intValue(), output);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to encode integer '" + value + "' into the provided buffer", e);
    }
}

From source file:org.apache.bookkeeper.statelib.impl.kv.KVUtils.java

License:Apache License

static ByteBuf newCommandBuf(Command cmd) throws IOException {
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(cmd.getSerializedSize());
    try {//from  ww w .ja  v a 2 s .c  o m
        cmd.writeTo(new ByteBufOutputStream(buf));
    } catch (IOException e) {
        buf.release();
        throw e;
    }
    return buf;
}

From source file:org.apache.bookkeeper.statelib.impl.mvcc.MVCCUtils.java

License:Apache License

public static ByteBuf newLogRecordBuf(Command command) {
    ByteBuf buf = Unpooled.buffer(command.getSerializedSize());
    try {/*from w  ww.  j  av a  2 s. c  om*/
        command.writeTo(new ByteBufOutputStream(buf));
    } catch (IOException e) {
        throw new StateStoreRuntimeException("Invalid command : " + command, e);
    }
    return buf;
}

From source file:org.apache.drill.exec.rpc.RpcEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, OutboundRpcMessage msg, List<Object> out) throws Exception {
    if (RpcConstants.EXTRA_DEBUGGING) {
        logger.debug("Rpc Encoder called with msg {}", msg);
    }/*  w  ww . j  a v  a 2 s . com*/

    if (!ctx.channel().isOpen()) {
        //output.add(ctx.alloc().buffer(0));
        logger.debug("Channel closed, skipping encode.");
        msg.release();
        return;
    }

    try {
        if (RpcConstants.EXTRA_DEBUGGING) {
            logger.debug("Encoding outbound message {}", msg);
        }
        // first we build the RpcHeader
        RpcHeader header = RpcHeader.newBuilder() //
                .setMode(msg.mode) //
                .setCoordinationId(msg.coordinationId) //
                .setRpcType(msg.rpcType).build();

        // figure out the full length
        int headerLength = header.getSerializedSize();
        int protoBodyLength = msg.pBody.getSerializedSize();
        int rawBodyLength = msg.getRawBodySize();
        int fullLength = //
                HEADER_TAG_LENGTH + getRawVarintSize(headerLength) + headerLength + //
                        PROTOBUF_BODY_TAG_LENGTH + getRawVarintSize(protoBodyLength) + protoBodyLength; //

        if (rawBodyLength > 0) {
            fullLength += (RAW_BODY_TAG_LENGTH + getRawVarintSize(rawBodyLength) + rawBodyLength);
        }

        ByteBuf buf = ctx.alloc().buffer();
        OutputStream os = new ByteBufOutputStream(buf);
        CodedOutputStream cos = CodedOutputStream.newInstance(os);

        // write full length first (this is length delimited stream).
        cos.writeRawVarint32(fullLength);

        // write header
        cos.writeRawVarint32(HEADER_TAG);
        cos.writeRawVarint32(headerLength);
        header.writeTo(cos);

        // write protobuf body length and body
        cos.writeRawVarint32(PROTOBUF_BODY_TAG);
        cos.writeRawVarint32(protoBodyLength);
        msg.pBody.writeTo(cos);

        // if exists, write data body and tag.
        if (msg.getRawBodySize() > 0) {
            if (RpcConstants.EXTRA_DEBUGGING) {
                logger.debug("Writing raw body of size {}", msg.getRawBodySize());
            }

            cos.writeRawVarint32(RAW_BODY_TAG);
            cos.writeRawVarint32(rawBodyLength);
            cos.flush(); // need to flush so that dbody goes after if cos is caching.

            CompositeByteBuf cbb = new CompositeByteBuf(buf.alloc(), true, msg.dBodies.length + 1);
            cbb.addComponent(buf);
            int bufLength = buf.readableBytes();
            for (ByteBuf b : msg.dBodies) {
                cbb.addComponent(b);
                bufLength += b.readableBytes();
            }
            cbb.writerIndex(bufLength);
            out.add(cbb);
        } else {
            cos.flush();
            out.add(buf);
        }

        if (RpcConstants.SOME_DEBUGGING) {
            logger.debug("Wrote message length {}:{} bytes (head:body).  Message: " + msg,
                    getRawVarintSize(fullLength), fullLength);
        }
        if (RpcConstants.EXTRA_DEBUGGING) {
            logger.debug("Sent message.  Ending writer index was {}.", buf.writerIndex());
        }
    } finally {
        // make sure to release Rpc Messages underlying byte buffers.
        //msg.release();
    }
}