Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Last active January 14, 2019 15:54
Show Gist options
  • Save HaloFour/0d5e0e0df75cba405e9e0407993cbe1b to your computer and use it in GitHub Desktop.
Save HaloFour/0d5e0e0df75cba405e9e0407993cbe1b to your computer and use it in GitHub Desktop.
Java Money API
package com.comcast.money.japi;
import com.comcast.money.core.Money$;
import com.comcast.money.core.Note;
import com.comcast.money.core.Result;
import com.comcast.money.core.StringNote;
import com.comcast.money.core.Tracer;
public class JMoneyTracer {
private static Tracer tracer() {
return Money$.MODULE$.tracer();
}
public static TraceSpan startSpan(String spanName) {
Tracer tracer = tracer();
tracer.startSpan(spanName);
return new TraceSpan() {
private boolean result = false;
private boolean stopped = false;
@Override public void succeeded() {
result = true;
}
@Override public <T> T succeeded(T value) {
result = true;
return value;
}
@Override public void failed() {
result = false;
}
@Override public void close() {
if (!stopped) {
stopped = true;
tracer.stopSpan(result ? Result.success() : Result.failed());
}
}
};
}
public <T, E extends Exception> T trace(String spanName, CheckedCallable<T, E> action) throws E {
try (TraceSpan span = startSpan(spanName)) {
return span.succeeded(action.call());
}
}
public <E extends Exception> void trace(String spanName, CheckedRunnable<E> action) throws E {
try (TracedSpan span = startSpan(spanName)) {
action.run();
span.succeeded();
}
}
}
public interface TraceSpan extends AutoCloseable {
@Override void close();
void succeeded();
<T> T succeeded(T value);
void failed();
}
@FunctionalInterface
public interface CheckedCallable<V, E extends Exception> {
V call() throws E;
}
@FunctionalInterface
public interface CheckedRunnable<E extends Exception> {
void run() throws E;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment