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);
}
}
}
Aggregations