Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, September 7, 2015

Apache Tamaya - the new Configuration API

It was quite s long time since I have blogged here, but now it is definitive time to reactivate this blog and get in contact with all interested people on the configuration topic.

History

After JavaOne 2014, when the configuration topic was cancelled from the EE8 list, David Blevins and others proposed to start an Apache project for several reasons:
  • let focus people with experience in the topic to identify a common feature set
  • implement the ideas as part of an Apache project to provide the ideas using a free nd redistributable licence
  • use a common proven organisation also capable of generating successful adoption.This was when Apache Tamaya was put to incubation. Following we had several discussions, hangouts, mails. As a result Apache Tamaya is now available as a first release 0.1-incubating, ready to be used.
Also to be mentioned is that also Mark Struberg and Gerhard Petracek, the guys behind Deltaspike, joined this project and actively contributed to it. Given that I think it is worth to have a deeper look at the project. This is what this blog is all about.

The Apache Tamaya Project

Like a Java Specification Request

Apache Tamaya is built-up similarly to a Java Specification Request (JSR). It as an API that defines the artifacts user's typically interact with and it provides a reference implementation that implements the API so it can be used for real world projects. The reason for doing so are the following:
  1. Separating an API from the implementation gives you a very clear and clean view on the problem. You must isolate the essence of your problem and omit all kind of over-specific aspects. If done in a good way, this leads to a simple and well comprehensive API, which at the same time is powerful enough to support at least most of all other requirements (e.g. using extension points or hooks for plugin in adapted or additional functionality (aka service provider interfaces/SPIs).
  2. The API may be more independent than the reference implementation regarding its compatibility requirements. As an example the Java 7 based API of Apache Tamaya in fact is also compatible Java 6 and Java ME platforms.
  3. You can start with a minimal set of functionality on the API and extending it step-by-step as needed. Very extension must be checked, if it is really necessary or if the requirement not also can be implemented using the existing API/SPI. This ensures your API is really focusing on the minimal aspects thefore getting lean and clear.
  4. Last but not least, somehow corresponding to the previous point, adding new functionality does not interfere with the basic API/implementation, making it very easy to add new functionality. The Apache Tamaya project also contains quite a few of so called extensions that only depend on the API, so the project has already proven being able to cover this aspect very efficiently.
The only difference to a JSR is the current lack of a Technical Compatibility Kit (TCK) that ensures that different implementations of the API are compatible with a common set of rules. Similarly we do not have something like a "specification" (but we have a very extensive documentation, somehow quite similar to a specification, also covering many of the aspects/discussions done during the evaluation phase for the Java EE JSR 2 years ago).

Compatibility

Apache Tamaya currently supports both Java 7 and Java 8. Reasons behind is that there is still plenty of code, especially in the enterprise context, running on Java 7. And we wanted people to be able to use Apache Tamaya also before they move to the Java 8 platform. Said that the API can be added to your maven build quite easily:

<dependency>
  <groupId>org.apache.tamaya</groupId>
  <artifactId>tamaya-java7-api</artifactId>
  <version>0.1-incubating</version>
</dependency>

Or, when with Java 8:

<dependency>
  <groupId>org.apache.tamaya</groupId>
  <artifactId>tamaya-api</artifactId>
  <version>0.1-incubating</version>
</dependency>

Similarly the implementation (called core), can be added similarly:

Compatible with Java 7 and beyond:

<dependency>
  <groupId>org.apache.tamaya</groupId>
  <artifactId>tamaya-java7-core</artifactId>
  <version>0.1-incubating</version>
</dependency>

Compatible  with Java 8:

<dependency>
  <groupId>org.apache.tamaya</groupId>
  <artifactId>tamaya-core</artifactId>
  <version>0.1-incubating</version>
</dependency>

The Main Concepts

Configuration Abstraction and Access 

One of the main objectives is to define an abstraction for configuration and define a common way of accessing it using simple Java code. So the first thing is to define a model for configuration:

public interface Configuration {

  default String get(String key) {...}
  default <T> T get(String key, Class<T> type) {...}
  default Configuration with(ConfigOperator operator) {...}
  default <T> T query(ConfigQuery<T> query) {...}

  <T> T get(String key, TypeLiteral<T> type);
  Map<String, String> getProperties();

  // not available for Java 7
  default Optional<String> getOptional(String key) {...}
  default <T> Optional<T> getOptional(String key,
                                      Class<T> type) {...}
  default <T> Optional<T> getOptional(String key,
                                      TypeLiteral<T> type) {...}
  default Optional<Boolean> getBoolean(String key) {...}
  default OptionalInt getInteger(String key) {...}
  default OptionalLong getLong(String key) {...}
  default OptionalDouble getDouble(String key) {...}
}

So looking at this interface some important key decisions can be identified:
  • Configuration entries are accessed using String keys.
  • Configuration values are basically modelled as Strings
  • Typed access is supported as well using Class or TypeLiteral.
  • Configuration can be accessed key by key or by accessing the full properties map (getProperties). Hereby there is a constraint that the returned map may not contain all entries that would also be available when accessing them individually. Reason is that some configuration sources may not be able to list all the entries (aka being scannable). Refer also the SPI part, when the PropertySource interface is discussed, for further details.
  • The methods with, query define so called functional extension points, allowing additional functionality being added as operators/queries that can be applied on a configuration.
  • Finally, only defined in the API version depending on Java 8, are all the methods returning Optional values. These add support for the new Optional artifact introduced with Java 8. Similarly all the default methods were replaced in the Java 7 variant with corresponding abstract base implementations shipped with the reference implementation.
Instances of Configuration can be accessed from a ConfigurationProvider singleton:

Configuration config = ConfigurationProvider.getConfiguration();

Hereby  always a valid instance must be returned. It is not required that always the same instance is returned. Especially when running in a contextual environment, such as Java EE, each context may return different configurations, also reflecting the configuration resources deployed in the different Java EE artifacts. Similarly also OSGI based environments have their own classloader hierarchies, that may require isolation of configuration along the classloader bounderies.

Functional Extension Points

In the previous section we already mentioned the methods with and query. These take as argument a ConfigurationOperator or a ConfigurationQuery<T>, which are defined as follows:

@FunctionalInterface
public interface ConfigOperator {
    Configuration operate(Configuration config);
}

@FunctionalInterface
public interface ConfigQuery<T> {
    T query(Configuration config);
}

So basically ConfigOperator acts as a mapping that derives a Configuration from another Configuration, whereas a ConfigurationQuery<T> can return any kind of result. Both constructs allow adding functionality in multiple ways without having to deal with it on the Configuration interface, e.g. aspects like:

  • Filtering of configuration for specific use cases, e.g. recombining entries, or removing entries out of scope for a certain use case
  • Masking of entries or sections for security reasons
  • Creating typed objects based on configuration
  • Statistical details on a given configuration, e.g. the defined sections
  • Configuration validation and documentation
  • Conversion of configuration, e.g. to a JSON representation
  • and much more.

For running examples you may consider having a look at the tamaya-functions extension module, which already implements quite a few of aspects.


A minimalistic Example

To clarify things a bit more let's create a small example, which just uses the base mechanism provided with Tamaya's core implementation. Let's assume we build a small node, that a micro-service performing a simple compound interest rate calculation (I will omit the financial details how this is achieved here). Such a calculation basically is defined as:

We assume that the interest rate is something that is configured for this component, so in our component we simply add the following code:

BigDecimal interestRate = ConfigurationProvider.getConfiguration()
                .get("com.mycomp.ratecalculator.rate",
                     BigDecimal.class);

When using Java 8 we could also easily combine it with a default value:

BigDecimal interestRate = ConfigurationProvider.getConfiguration()
                .getOptional("com.mycomp.ratecalculator.rate",
                             BigDecimal.class)
                .orElse(BigDecimal.of(0.05d));

Given that we can easily implement our business logic, also using the JSR 354 type (see http://javamoney.org):

public class MyRateCalculator implements RateCalculator{

  private BigDecimal interestRate = ConfigurationProvider
                .getConfiguration()
                .getOptional("com.mycomp.ratecalculator.rate",
                             BigDecimal.
class)
                .orElse(BigDecimal.of(0.05d));

  public MonetaryAmount calcRate(MonetaryAmount amt, int periods){
   ...
  }

}

Now given you have built your logic in a similar way you have multiple benefits:
  • You can deploy your calculator as part of a Desktop application.
  • You can deploy your calculator as part of a Java EE application.
  • You can deploy your calculator in an OSGI container.
  • You can deploy your calculator easily as a standalone micro-service (with an appropriate API, e.g. REST).



Making Tamaya Support Optional

Basically you can even use the Tamaya optional module to integrate with Tamaya only as an optional dependency. This extension module is a very simple module, adding basically only one class to your dependency path, which

  • Ensures Tamaya API is on your classpath
  • Optionally checks if a Configuration is accessible from a given context.
  • Delegates Configuration request to Tamaya, or - if not availalbe - to a delegate passed from your logic, when creating the delegate:
import org.apache.tamaya.ext.optional.OptionalConfiguration;

private BigDecimal interestRate = 
              Optional.ofNullable(
                 OptionalConfiguration
.of(
                    (k) -> MyConfigMechanism.get(k)
                              
// String get(String key);
                 )
                .get("com.mycomp.ratecalculator.rate",
                             BigDecimal.
class))
                .orElse(BigDecimal.of(0.05d));

This allows you to support Tamya Configuration, but you can still use your own default configuration logic as default, if Tamaya is not loaded in your target environment.


What else?

From an API perspective there is not much more needed. The TypeLiteral class used before is the same, which is also known well from Java EE (CDI) and the only other artifact not mentioned is the ConfigException class. Of course, this functionality per se is very minimalistic, but it exactly does, what it is supposed to: it provides a minimalistic access API for configuration. And why we think this is so important? Here is why
  1. Everybody writing components typically writes some configuration logic, but everybody does it different: different formats, locations, key schemes, overridings etc. Also Apache Tamaya neither wants to define what you configure, or where your configuration is located and how it can be overridden. But we define a common API for accessing the configuration.
  2. Given that components from different teams can be more easily integrated within a project, but also within a concrete enterprise context, since all components refer to the same configuration mechanism.
  3. Even better, when using Tamaya overriding rules of configuration can be more or less ignored, since the mechanisms of Tamaya (I will present the corresponding SPI in the next blog here) already provide these mechanisms, so they can be adapted as needed.
  4. Similarly the formats used for configuration and also the fact that configuration may be locally stored in the file system or be remotely distributed is not of importance anymore.
This per se should render Apache Tamaya to very interesting and crucial piece of any application or module architecture. Additionally its SPI brings additional benefits, especially within bigger entprise contexts. We will look at the SPI  and the extensions in the next blog posts here. So stay tuned!

As always comments are welcome. If anybody out there is also thinking of contributing to the project please get in contact with us under dev@tamaya.incubator.apache.org.

And of course, help us spreading words writing tweets, blogs, adopting it, using it, loving it! 

Want to hear more?

Want to know more about Apache Tamaya? Visit our project site or even better join and see us at 






Sunday, September 28, 2014

Configuration for the Java Platform

Configuration for the Java Platform

Outcome from the last EC Meeting

Last week the EC meeting @Twitter HQ discussed a proposal for a new JSR for Configuration targeting application configuration. Since this topic affects not only Java EE, it was proposed as a SE JSR. Discussions were open and constructive. I try to summarize the outcome here:
  • One idea was, that we should do an OSS project out of it. I do not think this makes sense, there are already a few of them, all with reasonable maturity. So it should be finally time to standardize how things are configured in the Java eco-system.
  • Others said we should have a look at what was already done in the ME area. But also after having a look at JSR 36 (CDC 1.0) noch JSR 218 (CDC 1.1), I don't see anything relevant there. Perhaps someone can give me a hint here ;)
  • Others thought we should create an OpenJDK project. I tend also to disagree with that due to several reasons:
    • Developing a JSR that is targeting the JDK directly is much more complicated and my experience from JSR 354 shows that without having Oracle heavily pushing things it might be a high risk to go that way.
    • I think community involvement is much easier to achieve doing a "normal" JSR. We can setup a GitHub repo and start working on it. The OpenJDK tool chain is not that easy to use and know how about is not as widely available. Most of all it is much more difficult to get OpenJDK commit rights, than join a OSS project.
    • With Jigsaw coming hopefully in Java 9, I expect we get a module system. So it would be pretty easy to add configuration as a Java module once Jigsaw is there. This makes it much more easy again, to focus on the configuration usability aspects and realize Java integration as Jogsaw module later.
    • As well waiting for Jigsaw means that no SE JSR can be done for several year. IMO this makes no sense. Nevertheless I agree that the configuration mechanisms proposed must be compatible with Jigsaw.
    • Finally this JSR tries to focus on application configuration. This also includes relatively early configuration. But we definitively do not want to be part of the Java early loading code. We saw it quite good, how bad design can get and what kind of unwanted side effects can occur, when infrastructure required by low level Java boot processes is messed up with common user functionality. As an example try to load a class using Class.forName(String) during the loading process of the java.util.logging.LogManager (you have to subclass the LogManager and configure it as a system property).
  • Also Redhat, SouJava, LJC, iJUG and others were not seen to be sufficient that we should file the JSR already. There is some probability that it could be voted down, especially, when Oracle is not on board. We definitively have to talk with Oracle people here during Java One!
  • Finally feedback was that our JSR proposal should be more precise though no exact details were given, what should be fixed. Nevertheless have a look yourself at XXXX and help us to improve the filing.
So summarizing, adding configuration to the Java eco-system is definitively a Hercules task. OK, it was expected that it will not be easy ;) But good news is, we still we have a chance to get it on track, but we definitively need more support and work to be done. So if you are interested in the topic, write about it, tweet it, advertise it and help to improve our proposal. Communicate your interest, especially to EC members, that we have a unique chance here to improve the overall Java platform and we should not miss it. Especially support by more companies, including Oracle itself, in the EC would be important...
As always feedback is welcome and comments will not be restricted, also when you don't agree on my thoughts here.

Sunday, September 14, 2014

Integrating Configuration with CDI 2.0

Integrating Configuration with CDI

Most of you are aware that the original initiative of standardizing of configuration for Java EE deployment aspects was stopped lately. But looking at the topic of configuration we have multiple aspects:

  1. Deployment configuration in Java EE configuring a deployment into a Java EE server, including things like configuration of EJBs, transactions, datasources, servlets and filters etc. You can basically see this part as a replacement or improvement over the scattered file configurations as of today (web.xml, ejb.jar.xml, ...).
  2. Configuration of aspects that basically are not related to the Java EE platform, but related to the use cases and logic implemented. We call it application configuration. Since dependencies from a configuration mechanism should be minimized, IMO inversion of control is my preferred design concept to be used to "configure" a component, so CDI is the one that matches best.
  3. If we leave Java EE and imagine our solution built up on Spring, JavaFX, OSGI or other technologies, configuration gets even more generic. In many cases, though the existence of JSR 330, we can not rely on IoC/Dependency Injection to be present, so we need also to provide some kind of SE API, e.g. as outlined in previous blogs here.
Now given the current situation, I suggest point 1 is not in scope anymore for Java EE 8. Nevertheless there is still much we can do:
  • Leverage CDI so it is configuration aware
  • Standardize configuration as a global and unified concept in a SE JSR.
In this blog I would like to focus on what would be possible extensions to CDI to support application configuration effectively. 

Usage Perspective: Injecting Configured Values

As a starting point lets just inject String properties, e.g. as follows

public class MyBean {

  @Configured
  private String myProperty;

}

This is the simplest case, it will request for a configuration entry, with the same name as the field, so it looks for "myProperty". Now in many cases we probably want to have a different configuration key to be used for the lookup:

 @Configured("com.apple.myconfig.myProperty")
 private String myProperty;

Now what should happen, if configuration is not present? I suggest, without any default value, it should be managed like a deployment error. So we also want to be able to pass a default value here:

 @Configured(value="com.apple.myconfig.myProperty",
                     defaultValue="256")
 private String myProperty;

Obviously the configured value above is a number. So I would expect the runtime system is capable of injecting it also as number:

 @Configured(value="com.apple.myconfig.myProperty", 
                     defaultValue="256")
 private int myProperty;

Fine so far. Looking at Spring and other frameworks, you may also want to configure more complex things, e.g. injecting a Collection type:

 @Configured(value="com.apple.myconfig.myList", 
                     defaultValue="['a','b','c']")
 private List<String> MyList;

Since configuration is basically data added to a system externally it must also  be validatable, so we could add bean validation annotations on it:

  @Configured(value="com.apple.myconfig.myProperty", 
                     defaultValue="256")
 @Min(5)
 @Max(200)
 private int myProperty;

Basically looking at the code above it looks quite the same as what you can do with CDI already as of now. This makes sens since basically you simply do nothing different than injecting values. Similarly you want to separate different configurations in a system, may by qualifying them:

  @Configured(value="com.apple.myconfig.myProperty", 
                     defaultValue="256")
 @SystemConfig // Qualifier annotation
 private int myProperty

Finally default values also could support EL expressions:

 @Configured(value="com.myComp.stage", 
                     defaultValue="${environment.stage")
 @NotNull
 private Stage stage

Advanced Use Cases

Multiple Configuration Keys
In some cases there is a need to read out information from several configuration locations, hereby defining an order of precedence between several keys. That can be easily achieved by allowing an array of configuration keys to be defined within the annotation:

 public class MyBean {
  @Configured("myProperty", my.myconfig.myProperty")
  private int myProperty
  ...
 }

Configuration Root Keys
When organizing configuration in a hierarchical tree, a component typically reads several keys out of one sub-path, often called configuration area. Instead of having to retype the area all the time (which is error prone), it can be added as a default on class level, so the following example would lookup configuration with keys a.b.c.myProperty, a.b.c.num:

  @ConfigArea("a.b.c")
 public class MyBean {
  @Configured
  private int myProperty;
  @Configured("num")
  private int myProperty2;
  ...
 }

Configuration Filtering
Similarly you want to add sometimes a filter (operator) converting the configured String value to another String value (e.g. decrypting an encrypted password):

 @ConfiguredProperty(value={"users.admin.myPwd"},                      filter=foo.bar.MyPwdConverter.class)
 private String password;


Custom Adapter
Or you want to override/provide the converter to be used for type conversion from String to the required target type:

 @Configuredured(value={"users.admin.myAmount"},                      converter=foo.bar.MyAmountConverter.class)
 private MonetaryAmount amount;


Listening to Configuration Changes
Several times we want to be aware if configuration values change. Basically we could simply listen for PropertyChangeEvent instances: 

public class MyBean {

  @Configured
  private String myProperty;


  /**
   * Event sent, whenever a configured property is
   * changed (reinjected).
   * @param evt the event describing the changed property
   */
  void configChanged(@ConfigChange PropertyChangeEvent evt){
    ...
  }
}

This would allow to get informed on configuration changes easily, but would not imply any internal know how, how configuration is managed.

Alternate: Constraint Injected Types to simple Type only

The above though clearly separated has a couple of intersection with CDI. So it might be an option to reduce the configurable types to only the following:
  1. All primitive types such as boolean, byte, char, short, int, long, float, double.
  2. The corresponding wrapper types such as Boolean, Character, Byte, Short, Integer, Long, Float, Double, but also Number.
  3. Additionally: String, BigDecimal, BigInteger.
This would result in a fairly simple configuration mechanism. Additional features can then be added on top of that using CDI mechanisms, e.g. factory or producer classes that provide corresponding more complex instances that can be injected in other places:

 public class NameListProvider{
   @Configured
   private String configuredList;

   @Produces @NamedList @Dependent
   public List<String> getNamedList(){
      List<String> result = new ArrayList<>();
      parseList(result);
      return result;
   }
   
   private void parseList(List<String> list){ ... }
 }

A possible disadvantage of this solution is that the conversions are not inherently reusable and therefore similar conversions may be duplicated multiple times on a system. 

CDI Perspective: How can configuration features be realized

Basic Mechanism

As a starting point let us elaborate the runtime requirements configured beans/properties should have. I would suggest something like the following:
  1. Configured properties are based on String values only and managed by the configuration system only and not related to CDI.
  2. They can be converted to any non String based type, but conversion will be performed by the configuration subsystem. Especially configured objects do not support injection of any dependencies.
  3. Configured properties can be qualified. 
  4. Configured values are injected during the initialization of the CDI bean. It is the responsibility of the configuration system to determine the correct value, e.g. depenending on the current runtime context, or whatever is required to determine the correct configured value. The CDI container only provides the glue mechanism so configuration can be injected at the right locations.
  5. Any configured values are always injected with @Dependent scope. Adding any other scope annotation is handled as a deployment error.

Realization Variants

When we look at the possible implementation requirements and the possible way, how this can be implemented using CDI, there are different possible options, how concerns can be separated between CDI and a configuration subsystem:

Extending CDI
In this scenario CDI would be extended. meaning, that CDI itself defines the required annotations such as @Configured, @ConfigChange and also provides an SPI interface that can be registered (e.g. with java.util.ServiceLoader) for accessing configuration values. One important key aspect is that CDI should not know how configuration is managed. Basically configuration can be as simple as a .properties file in the classpath. In other cases it may be multilayered, dynamic system that even may run external to the current VM. So we need some very general abstraction to decouple CDI from this complexities. A minimalistic variant of such an SPI interface could look as follows:

 public interface ConfigAccessor{
   <T> T getConfiguredValue(Field f, Object instance,
                            Class<T> type,
                            Annotation... qualifiers,

                            ConfigChangeListener l);
   void addConfigChangeListener(ConfigChangeListener l);
   void removeConfigChangeListener(ConfigChangeListener l);
 }
Nevertheless this variant would have significant drawbacks:
  • It is questionable, if such an SPI should really be part of CDI.
  • Also CDI would probably not bring a configuration implementation with it (or only a very minimalistic one). 
An advantage of doing so, would be that the basic mapping between configuration and the CDI injection mechanisms is well defined. Nevertheless let's further see if we have other options.

Generalizing Producers
Looking at the examples we could also think about if the mechanisms shown could be generalized. Basically configuration injection is similar to satisfying dependencies using an external bean provider. Basically this what producers are built for. So basically we could also let CDI to the injection work...

 public class MyBean {

  @Inject @Configured
  private String myProperty;
  ...
 }

...and add an according producer bean for injecting configuration and hereby defining @Configured as CDI qualifier:


 @ApplicationScoped
 public class ConfigProducer{
   @Produces @Configured @Dependent
   public String getStringConfig(){...}
   @Produces @Configured @Dependent
   public Integer getStringConfig(){...}
   @Produces @Configured @Dependent
   public Boolean getStringConfig(){...}
   ...
 }
Nevertheless, if we could define that a producer will provide instances for any kind of injection targets with a certain qualifier, this would definitively allow us to inject all kind of configured values. To achieve this I added an additional flag (ProducerType) to the @Produces annotation to tell the CDI container that this producer should be used to delegate object production to any kind of target types qualified with @Configured :

 @ApplicationScoped
 public class ConfigProducer{

   @Produces(ProducerType.ALL) @Configured @Dependent
   public Object getConfiguredValue(InjectionTarget<?> tgt){...}
 }

Clearly also this variant has drawbacks: 

  • It is not type-safe.
  • Producers may easily have intersections with other producers and more easily lead to deployment errors.

Using Portable Extensions
Finally simply implementing a portable extension is not only enough, it provides also the most portable and powerful mechanism. Even the current CDI 1.1 is fully sufficient to implement a configuration feature seamlessly:
  • The extension listens to the ProcessInjectionTarget event. This will be called for every bean.
  • The extension could then check for @Configured (or @ConfigChange) annotations and could adapt the InjectionTarget, so it can intercept the injection process, when the bean is initalized. This allows to populate the bean created with the configuration values as needed (as dependent scope).
  • Similarly the extension manages the injected beans (using weak references), which want to listen for configuration changes. Similarly if the underlying configuration changes, it can reinject the according properties and call according methods on the bean annotated with @ConfigChange to inform the bean about the configuration change.
  • If the configuration subsystem wants to publish further CDI events should be solely in the responsibility of the configuration system used.
As an additional advantage also CDI itself could be configured using the same extension mechanism (see below).

Configuring CDI

Going down the layers CDI itself should be made externally configurable. Hereby one may say we already have beans.xml and  annotations. The problem is that both of these concepts are bound to compile or package time mechanisms. A bundled ear or war archive cannot be changed without opening it, changing it and recreating it with changes included. But this is a thing configuration exactly wants to prevent. Configuration therefore may be provided in a way and with mechanisms that is not controlled by the component to be configured. As a consequence we need a dynamic way for connecting configuration logic with the CDI subsystem that is capable of
  • be available and accessible during deployment/initialization time of the CDI container.
  • be dynamic, so depending on the current valid configuration for a given setup the right values are returned.
Basically this can be achieved most easily by an service provider interface (SPI) defined by CDI. E.g. CDI could add a CDIConfiguration interface as illustrated below that can be configured using the java.util.ServiceLoader.

 public interface CDIConfiguration{
   Collection<Class<? extends Extension>> getExtensions();
   Collection<Class<?>> getAlternativeBeans();
   Collection<Class<?>> getAlternativeStereotypes();
   List<Class<?>> getInterceptors();
   List<Class<?>> getDecorators();
   Collection<String> getScanExcludes();
 }

The problem with this proposal is that adding/enabling things is easy, but disabling things is more complex. But wait! Fortunately CDI comes with a much more powerful concept: CDI extensions, which gives you full access for modifying the CDI metamodel. With that we can
  • Register beans or deadactivate (veto) beans and alternatives.
  • Add, Adapt, Remove injection points
  • Adding or removing interceptors, decorators.
  • Add/remove interceptors, decorators on individual beans
  • ...
So basically CDI extensions already enables us to control CDI. The only thing missing is to define a configuration model, that reflects the different things we want to made configurable. Since we are using a simple Map<String,String> based model, we could e.g. define the following:

// Adding/defining things
javax.enterpise.inject.beans.alternativeClasses=class1,class2,class3
javax.enterpise.inject.beans.alternativeStereotypes=class1,class2,class3
javax.enterpise.inject.beans.interceptors=class1,class2,class3
javax.enterpise.inject.beans.decorators=class1,class2,class3
javax.enterpise.inject.beans=class1,class2,class3
javax.enterpise.inject.beans.scanExcludes=path1;path2
javax.enterpise.inject.extensions=class1,class2,class3

// Removing/deactivating things
javax.enterpise.inject.beans.alternativeClasses.vetoed=class1,class2,class3
javax.enterpise.inject.beans.alternativeStereotypes.vetoed=class1,class2,class3
javax.enterpise.inject.beans.interceptors.vetoed=class1,class2,class3
javax.enterpise.inject.beans.decorators.vetoed=class1,class2,class3
javax.enterpise.inject.beans.vetoed=class1,class2,class3
javax.enterpise.inject.beans.scanExcludes.vetoed=path1;path2
javax.enterpise.inject.extensions.vetoed=class1,class2,class3

This configuration basically would enable to configure everything you can do with beans.xml. But we can also think of additional features, e.g.:

// Adding interceptors to a bean
javax.enterpise.inject.bean:myBeanClass.intercetors=class1

// Adding interceptors to a method on a bean
javax.enterpise.inject.bean:myBeanClass#myMethodName(class).intercetors=class1

// Remove an interceptors from a bean
javax.enterpise.inject.bean:myBeanClass.intercetors.vetoed=class1

// Remove an interceptor from a method on a bean
javax.enterpise.inject.bean:myBeanClass#myMethodName(class).intercetors.vetoed=class1

...

Outlook

The most important outcome for me is that adding application configuration support to CDI does not require CDI to be adapted in any way. CDI already as of now is flexible enough so it can fully support configuration injection, including advanced use cases. This is basically a consequence of the very powerful SPI provided by CDI that allows to adapt the metamodel in a very flexible way. Unfortunately, given the EE configuration initiative seems to be stuck there is only little probability that also all other EE JSRs follow this example and provide similar SPIs, so they can be easily configured without the deployment of xml deployment descriptors. Nevertheless if they do (or would be accordingly enhanced during EE8 work, we could add configuration support in wide areas nevertheless.

As a consequence a standardization initiative as SE standalone JSR would probably be a good variant for starting defining configuration aspects in Java and therefore make corresponding code more interoperable. Such a SE JSR could start very small in a first release, so it could be finished as well within the EE8 timeline. That would enable applications not only to benefit from EE8 in a couple of years, but also having a configuration mechanism in place that is powerful enough to cover many of the aspects in daily live, except those of deployment configuration of the application servers. Such a JSR could define a simple APIs covering the following
  • an API that models configuration and the current runtime environment (util.preferences is not sufficient!)
  • listeners for listening to config changes
  • accessors to access configuration
  • utilities to work buildup configurations
  • optionally also adapting of Strings to objects
  • some functional extension points (operators, queries)
  • an SE based SPI
Such a configuration implementation then could be easily hooked into CDI and all other JSRs as they provide configurable meta-models. thus covering most of the configuration requirements.
More advanced concepts like configuration meta-modelling, building configurations from multiple trees, merging, filtering, security, views and templates would probably be postponed to a later version of such a spec. Nevertheless the reference implementation could provide some of these features, even as pluggable modules, and best practice will show, which of them will qualify to be further standardized at a later point.

Everybody is welcome to comment on this blog. Especially comments and ideas on how specification of configuration aspects should evolve would be very useful.

Saturday, May 31, 2014

Use Case Summary from Google Groups

Use Cases

In todays blog, I am summarizing the use cases as discussed in groups.google.com/forum/#!forum/java-config. I did only some minor rework on the original posts and hope to still reflecting the essence right.


Configurable Priorities

The configuration system in DeltaSpike uses, what they call, sources http://deltaspike.apache.org/configuration.html#configsource). Configuration hereby comes from several sources :
  • System properties
  • Environment properties
  • JNDI values
  • Properties file values (default filename is "META-INF/apache-deltaspike.properties")
These sources have a default priority (System first…. properties file last) that can be changed. So we could easily say "by default, the WEB-INF/classes directory is a source that has a priority lower that an external file". This way, by default, if there is a config file within a war, it will have lower priority, meaning Java EE components will behave as they use to. By adding an external source this (defaults) can be overriden or extended. And of course, this default behavior can be changed.

→ Configuration comes from different sources.
→ Configuration must be combinable.
→ Configuration must have different priorities that may taken into account, when combining configuration.

Configurable Overrides

Overriding behavior must be configurable, e.g. refer to the way of the Jersey team does things. You can register components and given them a priority. This approach would allow us to provide a default chain of sources of configuration properties and to allow the user to specify his own chain.

→ Configuration can be evaluated by a complex combination of sub-configurations or providers (e.g. a chain of responsibility)
→ Different environments may require different combinations in place


Multi Tenancy

In multi tenancy setups a hierarchical/graph model of contexts for configurations is required. For example there might be some kind of layering:
  • Layer 0: Default App configuration
  • Layer 1: Tenant specific configuration
  • Layer 2: User specific configuration
Configurations made in the tenant or user layer override the default app configuration etc.

→ Configuration must be orgainizable in layers that can override/extend each other.
→ The current environment must be capable of mapping tenant, user and other aspects, so a corresponding configuration (or layer) can be derived.

Scenario Operations

Current support of Java EE for operations (e.g. PaaS offerings) is weak. Also corresponding providers may not be fully compatible, which makes it more difficult to move applications between providers or different offerings/products within the same provider. Hereby a provider requires an extension to the EE runtime model, where all relevant deployment configuration can be controlled by an external source, managed by the provider and consumed by the EE platform. Basically if one deploys a java application a standard way to define it’s configuration, resources and environment to integrate with the provisioning tooling in place should be defined. The configuration should be pluggable (e.g. from a database, an external file,…) and the configuration should also be changeable at runtime.

Also there should be a standardized way to evaluate a configuration for an already deployed application.

→ EE deployments must be configurable. Configuration must be controllable from external sources, which are not controlled by the EE container.
→ External resource can override all aspects, or only override/extend specific parts, but still consider configuration data deployed with the application.
→ a contract is required, how this external configuration can be included/provided.
→ a contract is required, how according configuration is modelled, so the external source can "implement" the contract.
→ Configuration may be fully or partially mutable.
→ Changes on configuration must be observable.
→ a service is required that allows to read out the configuration of a deployed application.


Injectable Configuration and Fragments

As a developper I want to be able to configure my application/module something like this :
public MyPojo {
  private String currency;
  private Long currencyRate;

  // complex algorithm based on the currency
}

How do I configure that depending if my app is dealing with dollars or euros ? The DeltaSpike way of doing is something like :

public MyPojo {
  @Inject @Config("myCurrency")
  private String currency;
  @Inject @Config("myCurrencyRate")
  private Long currencyRate;

  // complex algorithm based on the currency
}

The Seam Config way of doing is quite clever. They use a namespace that is relative to the packing. So, without changing the initial code (so, forget about the @Inject above) they have an XML file that is able to override each attribute of any file.
As a Java EE user (developer or devops) I would like also to be able to package different versions of deployment descriptor fragments within my Java EE application archive, and be able to select which one is used via a -D command line argument.
E.g. have the following file structure within the application archive (a .war in this case):

WEB-INF
    conf
        dev
            web-fragment.xml
        qa
            web-fragment.xml
        live
            web-fragment.xml

And then either directly be able to say that conf/dev/web-fragment.xml should be used, or do this indirectly via an include directive and a placeholder in the main deployment descriptor for this type of fragment (in this case web.xml):

<web-app>
    ...
    <fragment>WEB-INF/conf/${mycompany.staging}/web-fragment.xml</fragment>
</web-app>

→ Application Configuration must be supported.
→ Configuration must be injectable using CDI
→ Configuration should support fragements, which can dynamically loaded by properties on the current runtime environment, or other mechanisms.


Scenario Testing

When testing a Java EE solution, it must be possible to easily control the configuration provided, so isolated component tests can be written effectively. Also it should be possible to control/isolate the configuration level for each test case.

→ isolation of configuration services
→ API for controlling the configuration provided, required for according implementations in the testing frameworks.

Scenario Modules

Complex applications are often built out of many more fine granular pieces, often called modules or plugins. This could be technical abstractions, business models, products or UI components. All of them require some configuration, which may be different for different runtime deployments (e.g. product customizations).

→ it must be possible to add configuration that exceeds the EE deployment aspects (Application Configuration).
→ this configuration must be deployable in different ways, along the code, or from external sources.

Scenario Staging

Different companies go through different staging levels during the development of software components. Currently only rarely the EE frameworks support staging aspects, nevertheless no broader, well modelled staging concept is defined. 
Different companies also have different staging or sub-staging levels in place, which also must be reflected. Especially with sub-stages inheritance of stage related configuration is common sense and should be supported.

→ Main stages available and to be supported by Java EE must be defined.
→ Enable sub-stages, additional aspects to be added, so also custom stages can be supported by configuration.
→ Allow stage properties inheritance, where needed.

Custom of the Shelf (COTS) Integration

When buying software from an external software company it is often very cumbersome to integrate, adapt and customize third party software to the internal operational requirements. Especially, when software is delivered as ear modules portability is often very difficult and time consuming. Configuration should enable COTS providers to define a customization contract, which also can be part of the COTS software interface and integration specifications. This would allow operations to better control and configure third party solutions as possible, whereas in the evaluation phase the integration and configuration options can explicitly be defined.

→ It must be possible to document configuration aspects supported.
→ It must be possible to configure arbitrary aspects, with basically arbitrary complexity, exceeding what is defined by Java EE.
→ Configuration must be overridable from external sources (the operations which must operate the COTS solution).

When operating huge server farms targeting Java EE solutions a typical process is as follows:
  1. An order for a Java EE deployment is created.
  2. An according logical domain is created and prepared image with a standard setup is installed.
  3. The logical domain and the containing Java EE application server are started in standalone mode.
  4. The application(s) are copied to the server and automatically deployed.
Hereby it would ease life of administrators, if deployment of EE solutions can be controlled/automated by the application server. This requires that the application server can be startup in some "maintenance mode", which allows to trigger its configuration service, so according deployments can be controlled by some (external) deployment controller.

→ Configuration must be injectable/deployable also into a running application server.
→ It must be possible to listen to configuration changes, so the deployment could be controlled similarly based on configuration changes (events).
→ configuration must be mutable and changes observable.               

Some Conclusions

So taking all into account, I would suggest the following:

  • Configuration is a very complex thing (OK, this is not new).
  • Configuration is dependent on the environment.
  • Configuration can be static and/or dynamic.
  • Configuration can come in different flavors and types.
  • Different companies have different sources and external systems in place, where and how they manage configurations. It must be possible to interoperate with all/most of them.
  • If EE Configuration focuses only on Java EE aspects, it will fail to cover some of the most important use cases and will make Java EE to fall back much behind e.g. what Springsource or other Cloud platforms are offering already as of today.
  • Configuration should leverage existing functionalities, e.g. by being injectable into CDI, instead of reinventing the wheel.
The good news is that, if interpreting configuration as a more broader and generic concept all/most of these aspects can be covered quite well with only a few abstractions. Though having said that, I am not sure, what will be covered at the end. Nevertheless the benefits for application programmers in Java EE would be tremendous, even if only a few aspects will be targeted. 
One of the risks I currently see, is that configuration aspects are targeted in a too narrow sense, focusing on leveraging EE as a platform only, because
  • focusing on EE only may not require to model configuration in a generic way, which may reduce the flexibility achieved at the end. Especially it might constrain the interoperability of configuration per se or, even worse, it might lead to two different ways of configuration in the future: one for application logic, one for EE logic.
  • adding configuration to all the existing JSRs is a huge and tremendous effort. To try to drive (remodel?) all required changes out of one JSR may quite probably make it fail. Nevertheless, focusing on the most important EE aspects, like EJBs, CDI, servlets, JSF, JMS, JPA, would still create huge benefits, but leave enough time for other aspects described above.
As always, you can add your comments or, even better, add your use cases, you want to be solved, so we can ensure we have covered the most important ones here...