com.gs.api.accelrx.context.ServiceContextProvider Maven / Gradle / Ivy
The newest version!
package com.gs.api.accelrx.context;
import com.google.common.annotations.VisibleForTesting;
import io.reactiverse.reactivecontexts.core.ContextProvider;
import io.vertx.rxjava3.core.Context;
import io.vertx.rxjava3.core.Vertx;
import java.util.Objects;
public class ServiceContextProvider implements ContextProvider {
private static final ThreadLocal threadInstance = new ThreadLocal<>();
private static final ServiceContextProvider instance = new ServiceContextProvider();
public static void install() {
io.reactiverse.reactivecontexts.core.Context.load();
}
public static ServiceContext getFromContext() {
final var serviceContext = getFromContextInternal();
return Objects.requireNonNull(serviceContext, () -> {
return "ServiceContext missing. Are you sure this ran on correct Vertx Context? Current Thread is " + Thread.currentThread().getName();
});
}
public static void putInContext(ServiceContext svcContext) {
instance.restore(svcContext);
}
@Override
public ServiceContext install(ServiceContext state) {
ServiceContext previous = capture();
restore(state);
return previous;
}
@Override
public void restore(ServiceContext previousState) {
Context context = Vertx.currentContext();
if (context != null) {
if (previousState == null) {
context.removeLocal(ServiceContext.CTX_KEY);
} else {
context.putLocal(ServiceContext.CTX_KEY, previousState);
}
} else {
if (previousState == null) {
threadInstance.remove();
} else {
threadInstance.set(previousState);
}
}
}
@Override
public ServiceContext capture() {
final var context = Vertx.currentContext();
if (context != null) {
return context.getLocal(ServiceContext.CTX_KEY);
} else {
return threadInstance.get();
}
}
@VisibleForTesting
static ServiceContext getFromContextInternal() {
return instance.capture();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy