Search in sources :

Example 1 with Worker

use of rx.Scheduler.Worker 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)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)1 ByteBufOutputStream (io.netty.buffer.ByteBufOutputStream)1 IOException (java.io.IOException)1 JsonGenerationException (org.codehaus.jackson.JsonGenerationException)1 JsonGenerator (org.codehaus.jackson.JsonGenerator)1 Worker (rx.Scheduler.Worker)1 Subscriber (rx.Subscriber)1