Search in sources :

Example 21 with ByteBufOutputStream

use of io.netty.buffer.ByteBufOutputStream in project WSPerfLab by Netflix-Skunkworks.

the class MockResponse method generateJson.

/**
     * 
     * @param id
     *            ID from client used to assert correct client/server interaction
     * @param delay
     *            How long to delay delivery to simulate server-side latency
     * @param itemSize
     *            Length of each item String.
     * @param numItems
     *            Number of items in response.
     * 
     * @return String json
     */
public static Observable<ByteBuf> generateJson(long id, int delay, int itemSize, int numItems) {
    return Observable.create((Subscriber<? super ByteBuf> subscriber) -> {
        Worker worker = Schedulers.computation().createWorker();
        subscriber.add(worker);
        worker.schedule(() -> {
            try {
                ByteBuf buffer = Unpooled.buffer();
                ByteBufOutputStream jsonAsBytes = new ByteBufOutputStream(buffer);
                JsonGenerator json = jsonFactory.createJsonGenerator(jsonAsBytes);
                json.writeStartObject();
                // manipulate the ID such that we can know the response is from the server (client will know the logic)
                long responseKey = getResponseKey(id);
                json.writeNumberField("responseKey", responseKey);
                json.writeNumberField("delay", delay);
                if (itemSize > MAX_ITEM_LENGTH) {
                    throw new IllegalArgumentException("itemSize can not be larger than: " + MAX_ITEM_LENGTH);
                }
                json.writeNumberField("itemSize", itemSize);
                json.writeNumberField("numItems", numItems);
                json.writeArrayFieldStart("items");
                for (int i = 0; i < numItems; i++) {
                    json.writeString(RAW_ITEM_LONG.substring(0, itemSize));
                }
                json.writeEndArray();
                json.writeEndObject();
                json.close();
                subscriber.onNext(buffer);
                subscriber.onCompleted();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        }, delay, TimeUnit.MILLISECONDS);
    });
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) Subscriber(rx.Subscriber) Worker(rx.Scheduler.Worker) JsonGenerator(org.codehaus.jackson.JsonGenerator) ByteBuf(io.netty.buffer.ByteBuf) JsonGenerationException(org.codehaus.jackson.JsonGenerationException) IOException(java.io.IOException)

Example 22 with ByteBufOutputStream

use of io.netty.buffer.ByteBufOutputStream in project ratpack by ratpack.

the class HealthCheckResultsRenderer method render.

@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Override
public void render(Context ctx, HealthCheckResults healthCheckResults) throws Exception {
    ByteBuf buffer = byteBufAllocator.buffer();
    boolean first = true;
    boolean unhealthy = false;
    try {
        try (Writer writer = new OutputStreamWriter(new BufferedOutputStream(new ByteBufOutputStream(buffer)))) {
            for (Map.Entry<String, HealthCheck.Result> entry : healthCheckResults.getResults().entrySet()) {
                if (first) {
                    first = false;
                } else {
                    writer.write("\n");
                }
                String name = entry.getKey();
                HealthCheck.Result result = entry.getValue();
                unhealthy = unhealthy || !result.isHealthy();
                writer.append(name).append(" : ").append(result.isHealthy() ? "HEALTHY" : "UNHEALTHY");
                String message = result.getMessage();
                if (message != null) {
                    writer.append(" [").append(message).append("]");
                }
                Throwable error = result.getError();
                if (error != null) {
                    writer.append(" [").append(error.toString()).append("]");
                }
            }
        }
    } catch (Exception e) {
        buffer.release();
        throw e;
    }
    ctx.getResponse().contentTypeIfNotSet(HttpHeaderConstants.PLAIN_TEXT_UTF8).status(unhealthy ? 503 : 200).send(buffer);
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) HealthCheck(ratpack.health.HealthCheck) ByteBuf(io.netty.buffer.ByteBuf) OutputStreamWriter(java.io.OutputStreamWriter) BufferedOutputStream(java.io.BufferedOutputStream) Map(java.util.Map) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 23 with ByteBufOutputStream

use of io.netty.buffer.ByteBufOutputStream in project ratpack by ratpack.

the class ErrorPageRenderer method render.

protected void render(Context context, String pageTitle, Consumer<? super BodyWriter> body) {
    ByteBuf buffer = context.get(ByteBufAllocator.class).buffer();
    OutputStream out = new ByteBufOutputStream(buffer);
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(out, CharsetUtil.encoder(CharsetUtil.UTF_8)));
    BodyWriter writer = new BodyWriter(printWriter);
    writer.println("<!DOCTYPE html>").println("<html>").println("<head>").print("  <title>").escape(pageTitle).println("</title>").println("    <style type=\"text/css\">").println(style).println("    </style>").println("</head>").println("<body>").println("  <header>").println("    <div class=\"logo\">").println("      <div class=\"martini\">").println("        <h1>Ratpack</h1>").println("      </div>").println("      <p>Development error page</p>").println("    </div>").println("  </header>");
    body.accept(writer);
    writer.println("<footer>").println("  <a href=\"http://www.ratpack.io\">Ratpack.io</a>").println("</footer>").println("</body>").println("</html>");
    printWriter.close();
    context.getResponse().send(HttpHeaderConstants.HTML_UTF_8, buffer);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBuf(io.netty.buffer.ByteBuf)

Example 24 with ByteBufOutputStream

use of io.netty.buffer.ByteBufOutputStream in project netty-socketio by mrniko.

the class EncoderHandler method sendError.

private void sendError(HttpErrorMessage errorMsg, ChannelHandlerContext ctx, ChannelPromise promise) throws IOException {
    final ByteBuf encBuf = encoder.allocateBuffer(ctx.alloc());
    ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
    encoder.getJsonSupport().writeValue(out, errorMsg.getData());
    sendMessage(errorMsg, ctx.channel(), encBuf, "application/json", promise, HttpResponseStatus.BAD_REQUEST);
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBuf(io.netty.buffer.ByteBuf)

Example 25 with ByteBufOutputStream

use of io.netty.buffer.ByteBufOutputStream in project Railcraft by Railcraft.

the class PacketBuilder method sendGuiWidgetPacket.

public void sendGuiWidgetPacket(IContainerListener listener, int windowId, Widget widget) {
    if (listener instanceof EntityPlayerMP && widget.hasServerSyncData(listener)) {
        ByteBuf byteBuf = Unpooled.buffer();
        try (ByteBufOutputStream out = new ByteBufOutputStream(byteBuf);
            RailcraftOutputStream data = new RailcraftOutputStream(out)) {
            widget.writeServerSyncData(listener, data);
            PacketGuiWidget pkt = new PacketGuiWidget(windowId, widget, byteBuf.array());
            PacketDispatcher.sendToPlayer(pkt, (EntityPlayerMP) listener);
        } catch (IOException ex) {
            if (Game.DEVELOPMENT_ENVIRONMENT)
                throw new RuntimeException(ex);
        }
    }
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ByteBufOutputStream (io.netty.buffer.ByteBufOutputStream)26 ByteBuf (io.netty.buffer.ByteBuf)21 IOException (java.io.IOException)7 ObjectOutputStream (java.io.ObjectOutputStream)7 OutputStream (java.io.OutputStream)5 OutputStreamWriter (java.io.OutputStreamWriter)4 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)3 Writer (java.io.Writer)3 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)2 ObjectInputStream (java.io.ObjectInputStream)2 Test (org.junit.Test)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 CodedOutputStream (com.google.protobuf.CodedOutputStream)1 Writable (groovy.lang.Writable)1 Template (groovy.text.Template)1 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)1 ChannelId (io.netty.channel.ChannelId)1 ChannelPromise (io.netty.channel.ChannelPromise)1