Interface ContextService


public interface ContextService
The ContextService provides methods for creating dynamic proxy objects (as defined by java.lang.reflect.Proxy). ContextService also creates proxy objects for functional interfaces (such as Function) that can be used as completion stage actions. Proxy objects run with the addition of context typically associated with applications executing in a Jakarta™ EE environment. Examples of such context are classloading, namespace, security, etc.

The proxy objects follow the same rules as defined for the java.lang.reflect.Proxy class with the following additions:

  • The proxy instance will retain the context of the creator's thread.
  • The proxy instance will implement all of the interfaces specified on the createContextualProxy methods.
  • The object to have a proxy instance created for should not be a component managed by the Jakarta EE Product Provider, such as a web component or a Jakarta Enterprise Bean.
  • All interface method invocations on a proxy instance run in the creator's context with the exception of hashCode, equals, toString and all other methods declared in Object.
  • The proxy instance must implement Serializable if the proxied object instance is serializable.
  • The proxied object instance must implement Serializable if the proxy instance is serialized.
  • Execution properties can be stored with the proxy instance. Custom property keys must not begin with "jakarta.enterprise.concurrent.".
  • Execution properties are to be used for controlling how various contextual information is retrieved and applied to the thread. Although application components can store arbitrary property keys and values, it is not recommended. Jakarta EE product providers may impose limits to the size of the keys and values.

For example, to contextualize a single completion stage action such that it is able to access the namespace of the application component,

 contextSvc = InitialContext.doLookup("java:comp/DefaultContextService");
 stage2 = stage1.thenApply(contextSvc.contextualFunction(i -> {
     DataSource ds = InitialContext.doLookup("java:comp/env/dsRef");
     try (Connection con = ds.getConnection()) {
         PreparedStatement stmt = con.prepareStatement(sql);
         stmt.setInt(1, i);
         ResultSet result = stmt.executeQuery();
         return result.next() ? result.getInt(1) : 0;
     }
 }));
 

Since:
1.0