CE-936 - Add method withTemporaryContext

This commit is contained in:
2024-03-12 11:51:10 -05:00
parent d551ad71a6
commit 03f1fc1436

View File

@ -34,6 +34,7 @@ import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.lambdas.VoidVoidMethod;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
@ -54,6 +55,7 @@ public class QContext
private static ThreadLocal<Map<String, Serializable>> objectsThreadLocal = new ThreadLocal<>();
/*******************************************************************************
** private constructor - class is not meant to be instantiated.
*******************************************************************************/
@ -105,6 +107,25 @@ public class QContext
/*******************************************************************************
**
*******************************************************************************/
public static void withTemporaryContext(CapturedContext context, VoidVoidMethod method)
{
CapturedContext originalContext = QContext.capture();
try
{
QContext.init(context);
method.run();
}
finally
{
QContext.init(originalContext);
}
}
/*******************************************************************************
** Init a new thread with the context captured from a different thread. e.g.,
** when starting some async task.
@ -267,6 +288,7 @@ public class QContext
}
/*******************************************************************************
** get one named object from the Context for the current thread. may return null.
*******************************************************************************/
@ -280,6 +302,7 @@ public class QContext
}
/*******************************************************************************
** get one named object from the Context for the current thread, cast to the
** specified type if possible. if not found, or wrong type, empty is returned.