Search in sources :

Example 1 with ReadBytesEvent

use of org.ballerinalang.nativeimpl.io.events.bytes.ReadBytesEvent in project ballerina by ballerina-lang.

the class IOUtils method read.

/**
 * <p>
 * Reads bytes from a channel and will obtain the response.
 * </p>
 * <p>
 * This operation will be blocking.
 * </p>
 *
 * @param channel channel the bytes should be read from.
 * @param content byte [] which will hold the content which is read.
 * @param context context obtained from the native function.
 * @return the number of bytes read.
 * @throws InterruptedException errors which occur if the thread is interrupted.
 * @throws ExecutionException   errors which occur during execution.
 */
private static int read(Channel channel, byte[] content, EventContext context) throws InterruptedException, ExecutionException {
    ReadBytesEvent event = new ReadBytesEvent(channel, content, context);
    CompletableFuture<EventResult> future = EventManager.getInstance().publish(event);
    EventResult eventResponse = future.get();
    int numberOfBytesRead = (Integer) eventResponse.getResponse();
    Throwable error = ((EventContext) eventResponse.getContext()).getError();
    if (null != error) {
        throw new ExecutionException(error);
    }
    return numberOfBytesRead;
}
Also used : EventContext(org.ballerinalang.nativeimpl.io.events.EventContext) ReadBytesEvent(org.ballerinalang.nativeimpl.io.events.bytes.ReadBytesEvent) EventResult(org.ballerinalang.nativeimpl.io.events.EventResult) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with ReadBytesEvent

use of org.ballerinalang.nativeimpl.io.events.bytes.ReadBytesEvent in project ballerina by ballerina-lang.

the class IOUtils method read.

/**
 * <p>
 * Reads bytes asynchronously and trigger the callback.
 * </p>
 *
 * @param channel  the channel which the bytes should be read from.
 * @param content  the byte[] which will holds the content which will be read.
 * @param context  context which will be obtained from the native function call.
 * @param function the callback function which will be triggered.
 */
public static void read(Channel channel, byte[] content, EventContext context, Function<EventResult, EventResult> function) {
    ReadBytesEvent event = new ReadBytesEvent(channel, content, context);
    CompletableFuture<EventResult> future = EventManager.getInstance().publish(event);
    future.thenApply(function);
}
Also used : ReadBytesEvent(org.ballerinalang.nativeimpl.io.events.bytes.ReadBytesEvent) EventResult(org.ballerinalang.nativeimpl.io.events.EventResult)

Aggregations

EventResult (org.ballerinalang.nativeimpl.io.events.EventResult)2 ReadBytesEvent (org.ballerinalang.nativeimpl.io.events.bytes.ReadBytesEvent)2 ExecutionException (java.util.concurrent.ExecutionException)1 EventContext (org.ballerinalang.nativeimpl.io.events.EventContext)1