dev.vality.woody.api.AbstractServiceBuilder Maven / Gradle / Ivy
package dev.vality.woody.api;
import dev.vality.woody.api.event.ServiceEvent;
import dev.vality.woody.api.event.ServiceEventListener;
import dev.vality.woody.api.proxy.ProxyFactory;
import dev.vality.woody.api.proxy.SingleTargetProvider;
import dev.vality.woody.api.proxy.tracer.*;
import java.util.concurrent.atomic.AtomicBoolean;
@SuppressWarnings("checkstyle:ClassTypeParameterName")
public abstract class AbstractServiceBuilder implements ServiceBuilder {
protected static final ServiceEventListener DEFAULT_EVENT_LISTENER = (ServiceEventListener) event -> {
};
private boolean allowObjectProxyOverriding = false;
private ServiceEventListener eventListener = DEFAULT_EVENT_LISTENER;
private final AtomicBoolean used = new AtomicBoolean(false);
@Override
public ServiceBuilder withEventListener(ServiceEventListener listener) {
this.eventListener = listener;
return this;
}
@Override
public Srv build(Class iface, T serviceHandler) {
if (!used.compareAndSet(false, true)) {
throw new IllegalStateException("Builder already used");
}
try {
T target = createProxyService(iface, serviceHandler);
return createProviderService(iface, target);
} catch (Exception e) {
throw new WoodyInstantiationException(e);
}
}
@Override
public ServiceEventListener getEventListener() {
return eventListener;
}
protected T createProxyService(Class iface, T handler) {
ProxyFactory proxyFactory = new ProxyFactory(createEventTracer(), allowObjectProxyOverriding);
return proxyFactory.getInstance(iface, new SingleTargetProvider(iface, handler));
}
protected MethodCallTracer createEventTracer() {
return new CompositeTracer(
TargetCallTracer.forServer(),
DeadlineTracer.forService(),
new EventTracer(getOnCallStartEventListener(),
getOnCallEndEventListener(),
getErrorListener()
));
}
public void setAllowObjectProxyOverriding(boolean allowObjectProxyOverriding) {
this.allowObjectProxyOverriding = allowObjectProxyOverriding;
}
protected abstract Runnable getErrorListener();
protected abstract Runnable getOnCallStartEventListener();
protected abstract Runnable getOnSendEventListener();
protected abstract Runnable getOnReceiveEventListener();
protected abstract Runnable getOnCallEndEventListener();
protected abstract Srv createProviderService(Class serviceInterface, T handler);
}