The Cloud CMS Java Driver uses a thread local variable to store the authentication context it receives after connecting. This is perhaps unusual for folks who are coming from the JavaScript world but should be very familiar for anyone who works with common JavaScript frameworks such as Spring Framework or Spring Security.
When the authentication completes, the Java Driver constructs a "Driver" object that it stores into a thread local variable using the following call:
DriverContext.setDriver(driver);
The "driver" variable is scoped to the thread so that any calls you make on the same thread going forward will use this connection information. You can get the "driver" by using the same thread local static:
Driver driver = DriverContext.getDriver();
Hold on to that "driver" instance as it holds your access token, refresh token and other authentication state that the executing thread needs to know about.
To reuse the connection across multiple threads (which is a common scenario for web servers, application servers, Spring Framework singletons and many other places), you should make sure to call DriverContext.setDriver(driver) before any Cloud CMS related code is executed on the currently running thread.
Let's say that you have an init function that connects and finds the Branch to work against. You might store the Branch and then hand it back for any runtime threads that request it. Just do something like this:
private Branch branch; private Driver driver; public Branch acquireBranch() { // lazy load the branch (or handle this in an init function, up to you) if (branch == null) { branch = connectAndLoadBranch(); driver = DriverContext.getDriver(); } // set driver to thread local for current thread DriverContext.setDriver(driver); // hand back the branch return branch; }
If the "driver" threadlocal variable isn't set, you should receive an error when attempting to connect. If you application is multithreaded (such as an app running in Tomcat), then you'll need to do something similar to the code above.
Why is this necessary? One of the strengths of Java is its ability to work across multiple threads. Cloud CMS doesn't assume at a global level that all of your threads will represent the same authentication context. Indeed, you might have cases where many different users are logged in and you're managing lots of different "driver" variables for all of the logged in users authentication contexts. Thread local variables provide a nice and reliable way to scope the current thread to a given Cloud CMS authentication context. And it builds on one of the core strengths of Java.
Be sure to release your thread local variables at the end of the request. If you don't, they'll stick around on threads that may be used to service later requests. Frameworks like Spring offer handlers and interceptor patterns that are useful for handling this universally across all of your requests.