Search in sources :

Example 1 with CheckedFunction

use of org.mule.runtime.core.api.util.func.CheckedFunction in project mule by mulesoft.

the class StreamingUtils method withCursoredEvent.

/**
 * Executes the given function {@code f} considering that the given {@code event} might have a {@link CursorProvider} as
 * payload. In that case, this method obtains a cursor from the provider and executes the function.
 * <p>
 * Closing the opened cursor, handling exceptions and return values are all taken care of by this utility method.
 *
 * @param event an {@link CoreEvent}
 * @param f     the function to execute
 * @return the output {@link CoreEvent}
 * @throws MuleException
 */
public static CoreEvent withCursoredEvent(CoreEvent event, CheckedFunction<CoreEvent, CoreEvent> f) throws MuleException {
    if (event.getMessage().getPayload() == null) {
        return event;
    }
    Reference<Throwable> exception = new Reference<>();
    CheckedFunction<CoreEvent, CoreEvent> function = new CheckedFunction<CoreEvent, CoreEvent>() {

        @Override
        public CoreEvent applyChecked(CoreEvent event) throws Throwable {
            return f.apply(event);
        }

        @Override
        public CoreEvent handleException(Throwable throwable) {
            exception.set(unwrap(throwable));
            return null;
        }
    };
    Object payload = event.getMessage().getPayload().getValue();
    CursorProvider cursorProvider = null;
    Cursor cursor = null;
    try {
        if (payload instanceof CursorProvider) {
            cursorProvider = (CursorProvider) payload;
            cursor = cursorProvider.openCursor();
            event = replacePayload(event, cursor);
        }
        CoreEvent value = function.apply(event);
        if (value == null) {
            handlePossibleException(exception);
        } else if (value.getMessage().getPayload().getValue() == cursor) {
            value = replacePayload(value, cursorProvider);
        }
        return value;
    } finally {
        if (cursor != null) {
            closeQuietly(cursor);
        }
    }
}
Also used : CursorProvider(org.mule.runtime.api.streaming.CursorProvider) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Reference(org.mule.runtime.api.util.Reference) Cursor(org.mule.runtime.api.streaming.Cursor) CheckedFunction(org.mule.runtime.core.api.util.func.CheckedFunction)

Aggregations

Cursor (org.mule.runtime.api.streaming.Cursor)1 CursorProvider (org.mule.runtime.api.streaming.CursorProvider)1 Reference (org.mule.runtime.api.util.Reference)1 CoreEvent (org.mule.runtime.core.api.event.CoreEvent)1 CheckedFunction (org.mule.runtime.core.api.util.func.CheckedFunction)1