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:ratpack.sse.internal.ServerSentEventEncoder.java

License:Apache License

public ByteBuf encode(Event<?> event, ByteBufAllocator bufferAllocator) throws Exception {
    ByteBuf buffer = bufferAllocator.buffer();

    OutputStream outputStream = new ByteBufOutputStream(buffer);
    Writer writer = new OutputStreamWriter(outputStream, UTF_8);

    String eventType = event.getEvent();
    if (eventType != null) {
        outputStream.write(EVENT_TYPE_PREFIX);
        writer.append(eventType).flush();
        outputStream.write(NEWLINE);/*from ww  w . ja v a 2s .  com*/
    }

    String eventData = event.getData();
    if (eventData != null) {
        outputStream.write(EVENT_DATA_PREFIX);
        for (Character character : Lists.charactersOf(eventData)) {
            if (character == '\n') {
                outputStream.write(NEWLINE);
                outputStream.write(EVENT_DATA_PREFIX);
            } else {
                writer.append(character).flush();
            }
        }
        outputStream.write(NEWLINE);
    }

    String eventId = event.getId();
    if (eventId != null) {
        outputStream.write(EVENT_ID_PREFIX);
        writer.append(eventId).flush();
        outputStream.write(NEWLINE);
    }

    outputStream.write(NEWLINE);
    writer.flush();
    writer.close();
    return buffer;
}

From source file:se.sics.kompics.network.netty.serialization.AvroSerializer.java

private void toBinaryWithSchema(Object o, SchemaEntry se, ByteBuf buf) {
    BitBuffer flags;/*from   www .j  ava 2s  .  c  o m*/
    if (se.generated) {
        flags = BitBuffer.create(true, true); // with schema and generated
    } else {
        flags = BitBuffer.create(true, false); // with schema but not generated
    }
    byte[] flagsB = flags.finalise();
    buf.writeBytes(flagsB);
    buf.writeInt(se.id);
    try (ByteBufOutputStream out = new ByteBufOutputStream(buf);) {
        BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null);
        DatumWriter writer;
        if (se.generated) {
            writer = new SpecificDatumWriter(se.schema);
        } else {
            writer = new ReflectDatumWriter(se.schema);
        }
        writer.write(o, encoder);
        encoder.flush();
    } catch (IOException ex) {
        LOG.error("Couldn't serialise object.", ex);
    }
}

From source file:se.sics.kompics.network.netty.serialization.AvroSerializer.java

private void toBinaryNoSchema(Object o, Class type, ByteBuf buf) {
    LOG.info(/*from   ww w.j  a  v  a2 s.  com*/
            "Prepending schema to object of type {}. This is not efficient. It's recommended to register the class instead.",
            type);
    Schema s;
    BitBuffer flags;
    DatumWriter refWriter;
    if (o instanceof GenericContainer) {
        GenericContainer ag = (GenericContainer) o;
        s = ag.getSchema();
        flags = BitBuffer.create(false, true); // no schema and generated
        refWriter = new SpecificDatumWriter(s);
    } else {
        s = rData.getSchema(type);
        flags = BitBuffer.create(false, false); // no schema and not generated
        refWriter = new ReflectDatumWriter(s);
    }
    byte[] flagsB = flags.finalise();
    buf.writeBytes(flagsB);
    try (ByteBufOutputStream out = new ByteBufOutputStream(buf);
            DataFileWriter writer = new DataFileWriter(refWriter).create(s, out);) {
        writer.append(o);
        writer.flush();
    } catch (IOException ex) {
        LOG.error("Couldn't serialise object.", ex);
    }
}

From source file:se.sics.kompics.network.netty.serialization.JavaSerializer.java

License:Open Source License

@Override
public void toBinary(Object o, ByteBuf buf) {
    try {//w  w  w .  j  av  a2  s.c  om
        Closer closer = Closer.create(); // TODO: Convert to try-with-resources once Java6 is faded out
        try {
            ByteBufOutputStream bout = closer.register(new ByteBufOutputStream(buf));
            ObjectOutputStream oout = closer.register(new CompactObjectOutputStream(bout));
            oout.writeObject(o);
            oout.flush();
        } catch (Throwable e) { // must catch Throwable
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException ex) {
        Serializers.LOG.error("JavaSerializer: Could not Serialize object of type " + o.getClass(), ex);
    }
}

From source file:se.sics.nstream.hops.kafka.avro.AvroParser.java

License:Open Source License

public static byte[] nAvroToBlob(Schema schema, int nrMsgs, Random rand) {
    ByteBuf buf = Unpooled.buffer();//  w  w w  . j  a v a2  s .c  om
    OutputStream out = new ByteBufOutputStream(buf);
    GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
    BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
    GenericRecordBuilder grb;

    for (int i = 0; i < nrMsgs; i++) {
        grb = new GenericRecordBuilder(schema);
        for (Schema.Field field : schema.getFields()) {
            //TODO Alex - I assume each field is a string
            grb.set(field, "val" + (1000 + rand.nextInt(1000)));
        }
        try {
            writer.write(grb.build(), encoder);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
    try {
        encoder.flush();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    byte[] result = new byte[buf.writerIndex()];
    buf.readBytes(result);
    return result;
}

From source file:therogue.storehouse.network.NetworkUtils.java

License:Open Source License

public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound nbt) {
    if (nbt == null) {
        buf.writeByte(0);/*from w ww .  jav  a2s  . c o m*/
    } else {
        try {
            CompressedStreamTools.write(nbt, new ByteBufOutputStream(buf));
        } catch (IOException ioexception) {
            throw new EncoderException(ioexception);
        }
    }
}

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;// w  w w.j a  v  a  2s.  c  o m
    }
    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.ResourcesServer.java

License:Apache License

@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception {
    File file = new File(plugin.getResourceDir(), uri.getPath().substring("/resources/".length()));
    if (!file.exists()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;/*  w  w  w. j ava2s  .  c o m*/
    }

    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;
        }
    }

    ByteBuf buffer;
    try (InputStream stream = new FileInputStream(file)) {
        ByteBufOutputStream out = new ByteBufOutputStream(context.alloc().buffer());
        IOUtils.copy(stream, out);
        buffer = out.buffer();
        out.close();
    }

    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()));

    if (uri.getPath().startsWith("/resources/assets")) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, 1);
        response.headers().set(EXPIRES, format.format(calendar.getTime()));
        response.headers().set(CACHE_CONTROL, "public, max-age=2592000");
    }

    String path = uri.getPath();
    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);
    response.headers().add("Access-Control-Allow-Origin", "*");
    sendHttpResponse(context, request, response);
}

From source file:uk.co.thinkofdeath.thinkcraft.bukkit.world.ChunkManager.java

License:Apache License

private void gzipChunk(ChunkSnapshot chunk, ByteBuf out) {
    int mask = 0;
    int count = 0;
    for (int i = 0; i < 16; i++) {
        if (!chunk.isSectionEmpty(i)) {
            mask |= 1 << i;//from ww w .j a v a 2  s  .  c om
            count++;
        }
    }
    ByteBuf data = allocator.buffer(16 * 16 * 16 * 4 * count + 3 + 256);
    data.writeByte(1); // The chunk exists
    data.writeShort(mask);
    int offset = 0;
    int blockDataOffset = 16 * 16 * 16 * 2 * count;
    int skyDataOffset = blockDataOffset + 16 * 16 * 16 * count;
    for (int i = 0; i < 16; i++) {
        if (!chunk.isSectionEmpty(i)) {
            for (int oy = 0; oy < 16; oy++) {
                for (int oz = 0; oz < 16; oz++) {
                    for (int ox = 0; ox < 16; ox++) {
                        int y = oy + (i << 4);
                        int id = chunk.getBlockTypeId(ox, y, oz);
                        int dValue = chunk.getBlockData(ox, y, oz);
                        data.setShort((offset << 1) + 3, (id << 4) | dValue);

                        data.setByte(blockDataOffset + offset + 3, chunk.getBlockEmittedLight(ox, y, oz));
                        data.setByte(skyDataOffset + offset + 3, chunk.getBlockSkyLight(ox, y, oz));

                        offset++;
                    }
                }
            }
        }
    }
    for (int x = 0; x < 16; x++) {
        for (int z = 0; z < 16; z++) {
            data.setByte(skyDataOffset + offset + 3 + x + z * 16, ThinkBiome.bukkitToId(chunk.getBiome(x, z)));
        }
    }
    data.writerIndex(data.capacity());
    try {
        GZIPOutputStream gzip = new GZIPOutputStream(new ByteBufOutputStream(out));
        byte[] bytes = new byte[data.readableBytes()];
        data.readBytes(bytes);
        gzip.write(bytes);
        gzip.close();
    } catch (IOException e) {
        throw new RuntimeException();
    } finally {
        data.release();
    }
}

From source file:whitespell.net.websockets.socketio.parser.Encoder.java

License:Apache License

public int encodePacket(Packet packet, ByteBuf buffer) throws IOException {
    ByteBufOutputStream out = new ByteBufOutputStream(buffer);
    int start = buffer.writerIndex();
    int type = packet.getType().getValue();
    buffer.writeByte(toChar(type));//from   w  w  w  .j a va 2  s  .  c  o m
    buffer.writeByte(Packet.SEPARATOR);

    Long id = packet.getId();
    String endpoint = packet.getEndpoint();
    Object ack = packet.getAck();

    if (Packet.ACK_DATA.equals(ack)) {
        buffer.writeBytes(toChars(id));
        buffer.writeByte('+');
    } else {
        if (id != null) {
            buffer.writeBytes(toChars(id));
        }
    }
    buffer.writeByte(Packet.SEPARATOR);

    if (endpoint != null) {
        buffer.writeBytes(endpoint.getBytes());
    }

    switch (packet.getType()) {

    case MESSAGE:
        if (packet.getData() != null) {
            buffer.writeByte(Packet.SEPARATOR);
            byte[] data = packet.getData().toString().getBytes();
            buffer.writeBytes(data);
        }
        break;

    case EVENT:
        List<?> args = packet.getArgs();
        if (args.isEmpty()) {
            args = null;
        }
        buffer.writeByte(Packet.SEPARATOR);
        Event event = new Event(packet.getName(), args);
        jsonSupport.writeValue(out, event);
        break;

    case JSON:
        buffer.writeByte(Packet.SEPARATOR);
        jsonSupport.writeValue(out, packet.getData());
        break;

    case CONNECT:
        if (packet.getQs() != null) {
            buffer.writeByte(Packet.SEPARATOR);
            byte[] qsData = packet.getQs().toString().getBytes();
            buffer.writeBytes(qsData);
        }
        break;

    case ACK:
        if (packet.getAckId() != null || !packet.getArgs().isEmpty()) {
            buffer.writeByte(Packet.SEPARATOR);
        }
        if (packet.getAckId() != null) {
            byte[] ackIdData = toChars(packet.getAckId());
            buffer.writeBytes(ackIdData);
        }
        if (!packet.getArgs().isEmpty()) {
            buffer.writeByte('+');
            jsonSupport.writeValue(out, packet.getArgs());
        }
        break;

    case ERROR:
        if (packet.getReason() != null || packet.getAdvice() != null) {
            buffer.writeByte(Packet.SEPARATOR);
        }
        if (packet.getReason() != null) {
            int reasonCode = packet.getReason().getValue();
            buffer.writeByte(toChar(reasonCode));
        }
        if (packet.getAdvice() != null) {
            int adviceCode = packet.getAdvice().getValue();
            buffer.writeByte('+');
            buffer.writeByte(toChar(adviceCode));
        }
        break;
    }
    return charsScanner.getLength(buffer, start);
}