Example usage for io.netty.buffer ByteBufOutputStream buffer

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

Introduction

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

Prototype

ByteBuf buffer

To view the source code for io.netty.buffer ByteBufOutputStream buffer.

Click Source Link

Usage

From source file:com.heliosapm.streams.metrichub.RequestBuilder.java

License:Apache License

public ByteBuf merge(final JsonGenerator jg, final List<TSMeta> metas) {
    merges++;/*from  www .  j a v  a 2 s.  co  m*/
    final ByteBufOutputStream os = (ByteBufOutputStream) jg.getOutputTarget();
    final ByteBuf buff = os.buffer();
    //System.err.println("MetaBatch:" + metas.size() + ", Merges:" + merges);
    try {
        int cnt = 0;
        for (final TSMeta tsMeta : metas) {
            if (tsMeta == null)
                continue;
            jg.writeStartObject(); // start of query
            jg.writeStringField("aggregator", aggregator.name().toLowerCase());
            if (rateOptions != null) {
                jg.writeStringField("rate", "true"); // FIXME
            }
            if (downSampling != null) {
                jg.writeStringField("downsample", downSampling);
            }

            jg.writeArrayFieldStart("tsuids");
            jg.writeString(tsMeta.getTSUID());
            jg.writeEndArray(); // end of tsuids
            jg.writeEndObject(); // end of query
            cnt++;
        } // end of TSMetas
        log.info("Wrote {} TSDUID Queries", cnt);
        jg.writeEndArray(); // end of queries array
        jg.writeEndObject(); // end of request
        jg.flush();
        os.flush();
        jg.close();
        os.close();
        log.info("TSDB Request:\n{}", buff.toString(UTF8));
        return buff;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

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;// ww w . j  av  a 2  s. c o  m
    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  ww. j av  a2  s.  c  o  m*/
    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;//w  w w  . j  av  a  2  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 av a  2s.  com
    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:de.sanandrew.mods.claysoldiers.network.packet.PacketSendEffectNBT.java

License:Creative Commons License

@Override
public void writeData(ByteBufOutputStream stream, Tuple dataTuple) throws IOException {
    @SuppressWarnings("unchecked")
    Triplet<Integer, Byte, NBTTagCompound> data = (Triplet) dataTuple;

    stream.writeInt(data.getValue0());//from   www .j  a v  a  2s.  c o m
    stream.writeByte(data.getValue1());
    ByteBufUtils.writeTag(stream.buffer(), data.getValue2());
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/* w  ww  .ja  v a  2  s .  co  m*/
    }
    if (request.getUri().equals("/server")) {
        context.fireChannelRead(request);
        return;
    }

    if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().add("Access-Control-Allow-Origin", "*");
        response.headers().add("Access-Control-Allow-Methods", "POST");
        if (request.getMethod() == OPTIONS) {
            response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
        }
        sendHttpResponse(context, request, response);
    }

    if (request.getMethod() != GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // TODO: send browserified page
    if (request.getUri().equals("/")) {
        request.setUri("/index.html");
    }

    InputStream stream = null;
    /*
    if (request.getUri().startsWith("/resources/")) {
    File file = new File(
            plugin.getResourceDir(),
            request.getUri().substring("/resources/".length())
    );
    stream = new FileInputStream(file);
    } else {
    */
    stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri());
    if (stream == null) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    }
    ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer());
    copyStream(stream, out);
    stream.close();
    out.close();

    ByteBuf buffer = out.buffer();
    if (request.getUri().equals("/index.html")) {
        String page = buffer.toString(CharsetUtil.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    if (request.getUri().startsWith("/resources/")) {
        response.headers().add("Access-Control-Allow-Origin", "*");
    }

    String ext = request.getUri().substring(request.getUri().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);
    setContentLength(response, response.content().readableBytes());
    sendHttpResponse(context, request, response);

}

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   www . j a va2s . co  m*/

        //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:org.apache.qpid.jms.provider.amqp.message.AmqpJmsBytesMessageFacadeTest.java

License:Apache License

private OutputStream substituteMockOutputStream(AmqpJmsBytesMessageFacade bytesMessage)
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    ByteBufOutputStream mock = Mockito.mock(ByteBufOutputStream.class);
    Mockito.when(mock.buffer()).thenReturn(Unpooled.EMPTY_BUFFER);

    Field oshField = bytesMessage.getClass().getDeclaredField("bytesOut");
    oshField.setAccessible(true);/*from w ww.j ava  2  s  . co  m*/
    oshField.set(bytesMessage, mock);

    return mock;
}

From source file:org.msgpack.rpc.loop.netty.NettyTcpClientTransport.java

License:Apache License

@Override
protected void resetPendingBuffer(ByteBufOutputStream b) {
    b.buffer().clear();

}