Sunday, April 22, 2012

Custom CDI Scopes

Sometimes when working with Dependency Inject (DI) there arises a reason to develop a custom DI scope. For example, if an application has a graph of objects that it will build out, utilize, and then dispose of during the lifetime of the application a custom scope would make sense. Or, if an application is context aware and DI should be performed based on the context a segment of code is running in then a custom scope also makes sense.
For example, when developing the ODE-X project I observed several different code contexts I wanted to support to realize a virtual machine metaphor:
  • Executable - XML is parsed building an object graph consisting of Blocks containing a sequence of Instructions. The executable objects themselves are stateless so they can be utilized in more than one program but they can have DI injection at runtime of the current context. Executables are loaded/unloaded at runtime and if an executable is no longer references by an active program it can be unloaded removing it from memory. Executable PostCreate and PreDestory methods should be invoked when execuables are loaded and unloaded respectively
  • Program - A runtime specific configuration for a set of executables. Programs may be installed and uninstalled and provides a scope of global memory and runtime state for all included executables. Business Process Monitor (BPM) configurations should be specified in this scope.
  • Process - A distinct instance of a business process. Provides process level global memory for a business process that may be shared among member threads
  • Thread - A path of execution maintaining a stack of state. The core premise of ODE-X relies on the ability of removing a virtual thread state from physical memory and persisting it to XML in a database and then rehydrating and resuming execution at some distant point in the future.
  • Instructional - per instruction DI based on the current execution state. At the beginning of instruction execution instructional objects are created and provided t to the executable and then afterwards all objects in the instructional scope are discarded


In this architecture a virtual processor would execute each Executable Instruction with the following scope hierarchy : program->process->thread->instructional->executable.

To summarize, this application will maintain the lifecycle of a set of objects participating in DI and it needs a way of notifying the DI container when a set of DI obtained objects are no longer needed. Additionally, to simplify the architecture and take full advantage of DI, the application would like to configure DI such that objects defined in a higher level scope can be injected into objects defined in a lower level scope.
Fortunately the talented specification leads of JSR 330 (DI for Java) and JSR 299 (CDI) had the prescience to allow custom scopes. While some of my posts about perceived defects in CDI and Weld may be pointed I sincerely am impressed with CDI extensions and it truly does unleash JavaEE. I have written a simple example illustrating a custom CDI scope with the bonus of a scope qualifier.
For this example I disabled CDI auto discovery in favor of manually declaring CDI bean classes which is my personal preference. The key points of the sample is the CDI extension declaration of the sample DI actors

public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd, BeanManager bm) {
  bbd.addAnnotatedType(bm.createAnnotatedType(FooCDIInstanceProducer.class));
  bbd.addAnnotatedType(bm.createAnnotatedType(FooScopeContext.class));
  bbd.addAnnotatedType(bm.createAnnotatedType(Foo.class));
  bbd.addAnnotatedType(bm.createAnnotatedType(Bar.class));
  bbd.addQualifier(FooInstance.class);
  bbd.addScope(FooScope.class, false, false);
}

public void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {
  abd.addContext(new FooCDIContextImpl());
}

The use of the custom scopein the code:

FooScopeContext fooScope = ..
fooScope.create();
try {
fooScope.begin();
...
} finally {
fooScope.end();
}
fooScope.destroy();

and the finally the integration of the application scope with the CDI scope Context. Notice the use of Java ThreadLocals so that the application representation of the scope maintains the actual instances of the Objects and then passes those references to the CDI Context implementation so that they in turn can be passed back to the DI container for injection. While I am not a fan of ThreadLocals they are the ideal solution for custom scopes and I don't think one could make a CDI scope without them.

I came across an additional challenge with CDI custom scopes in that I wanted to add qualifiers to custom scoped objects so that injection point information could be passed into the custom scope Context and based upon the qualifier information the appropriate scoped object could be returned and injected. The solution I ended up at involved creating a custom qualifier producer and then passing the qualifier information on to the scope Context using another ThreadLocal variable. While I think the most ideal solution would be for the scopeContext provider to be presented with the InjectionTarget information if present this approach does have the benefit of separating scoped object creation from qualifier instance modification. For example, the scopeContext simply creates and tracks the lifecycle of the object whereas the Qualifier Provider can mutate the returned object based on the qualifier information.

One final thing to keep in mind with CDI custom scopes is that it adds more utility to the JSR 330 Provider interface. Before I though the Provider interface was only useful for obtaining references to brand new instances of DI objects on demand. In the context of a custom scope using the Provider interface may mean that the returned instance is not a new instance but a handle to an existing scoped object. For example, I will use the Provider interface in Executable and Instructional scoped objects so that contextual instances of objects in the higher Program, Process, and Thread scopes can be retrieved and utilized for contextual execution of the instruction.

Saturday, April 14, 2012

Binding a custom XmlJavaTypeAdapter to the JAXB XJC Code Model using JAXB Binding Customizations

Recently I have been working on an application that heavily utilizes XML schema and JAXB. Since I chose XML Schema as my typing framework I desired to use JAXB's XJC code generator to keep Java model classes in sync with changes I made to the XML model. While 90% of the XJC generated code was sufficient there was 10% that I wanted to customize so that the Java model classes functioned more seamlessly with my framework. XmlAdapter seemed to be a perfect fit for my needs but the problem was how do I generate a reference to my custom XmlAdapter right in the middle of the XJC generated object model?

While there are plenty of trivial examples of using an XmlAdapter to convert a non-mappable Java object to XML all the ones I read utilized a complete handcoded JAXB object model and not one generated from XJC. After much research and head banging I came across two methods of introducing a XmlAdapter or any other valid hand coded JAXB object into the XJC generate code model using  JAXB XJC customizations in an external binding file.


Complete Simple or Complex Type Replacement using jaxb:class ref="..."


The standard <jaxb:class> custom binding actually supports a ref attribute so that a Simple or Complex type can be directly mapped to an existing Java class. The class must be a valid JAXB annotated object or mapped to an XmlAdapter via an XmlJavaTypeAdapter annotation at the package or class level. This technique is actually used extensively inside JAXB episodes for multi schema separate compilation. This seems to be an intuitive means of mapping hand coded JAXB objects into XJC generated code but surprisingly enough there is little documentation on it. If one does a google search on "JAXB bind customization" the first link to the Oracle documentation site completely omits all references to the ref attribute. Below is an example of how I used the jaxb:class ref attribute to bind interfaces to the XJC object model:

XSD:

 <simpleType name="srcIdType">
  <restriction base="ID">
   <pattern value="s\d+" />
  </restriction>
 </simpleType>
 
 <simpleType name="srcIdRefType">
  <restriction base="IDREF">
   <pattern value="s\d+" />
  </restriction>
 </simpleType>

 <complexType name="sourceType">
  <attribute name="src" type="tns:srcIdType" use="required" />
 </complexType>
XJB:

 <jxb:bindings node="//xs:simpleType[@name='srcIdType']">
  <jxb:class ref="somepackage.SrcId" />
 </jxb:bindings>

 <jxb:bindings node="//xs:simpleType[@name='srcIdRefType']">
  <jxb:class ref="somepackage.SrcIdRef" />
 </jxb:bindings>
 
Custom Java:

@XmlJavaTypeAdapter(SrcIdAdapter.class)
public interface SrcId {
 
 String id();

}

@XmlJavaTypeAdapter(SrcIdRefAdapter.class)
public interface SrcIdRef {
 
 String id();

}

public class SourceId implements SrcId, SrcIdRef {
 public SourceId() {
 }

 public SourceId(String id) {
  this.id = id;
 }

 private String id;

 @Override
 public String id() {
  return id;
 }

 public static class SrcIdAdapter extends XmlAdapter<String, SrcId> {

  @Override
  public String marshal(SrcId id) throws Exception {
   if (id != null) {
    return id.id();
   }
   return null;
  }

  @Override
  public SrcId unmarshal(String id) throws Exception {
   return new SourceId(id);
  }

 }

 public static class SrcIdRefAdapter extends XmlAdapter<String, SrcIdRef> {

  @Override
  public String marshal(SrcIdRef id) throws Exception {
   if (id != null) {
    return id.id();
   }
   return null;
  }

  @Override
  public SrcIdRef unmarshal(String id) throws Exception {
   return new SourceId(id);
  }

 }

}



XJC Generated Java:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sourceType", namespace = "somenamespace")
public class Source {
...
@XmlAttribute(name = "src", required = true)
protected SrcId src;
    

Using the custom code:

Source s = new Source();
s.setSrcId(new SourceId("b0i0"));

Here is an example of binding a default java class to a simpletype and using a package level annotation to associate the XMLAdapter
XSD:

<simpleType name="bondURIType">
 <restriction base="anyURI" />
</simpleType>

<complexType name="executionConfigType" abstract="true">
      <attribute name="uri" type="tns:bondURIType" use="required" />
</complexType>
XJB:

<jxb:bindings node="//xs:simpleType[@name='bondURIType']">
 <jxb:class ref="java.net.URI" />
</jxb:bindings>
 
Custom Java:

//URIAdapter.java
public class URIAdapter extends XmlAdapter<String, URI> {

 @Override
 public String marshal(URI uri) throws Exception {
  if (uri != null) {
   return uri.toString();
  }
  return null;
 }

 @Override
 public URI unmarshal(String uri) throws Exception {
  return URI.create(uri);
 }

}

//package-info.java
@XmlJavaTypeAdapter(URIAdapter.class)
@XmlSchema(namespace = "somenamespace", xmlns = { @XmlNs(namespaceURI = "somenamespace", prefix = "myprefix") }, elementFormDefault = XmlNsForm.QUALIFIED)
package somepackage; //needs to match XJC package declaration, XJC -npa flag should be set to not generate a package-info.java file

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;


import somepackage.URIAdapter;

XJC Generated Java:

 @XmlAttribute(name = "uri", required = true)
 protected URI uri;
    

Property Replacement using jaxb:property/jaxb:baseType name=".."


Another scenario to consider is when one would like to use XJC to generate JAXB objects from a schema but then use a XmlAdapter to map a non-compliant Java object to the XJC generated classes. For example, I wanted to bind a Java Map to a custom complexType I wrote. It turns out that if one wants to change the Java type of a property one can use the property/baseType combination. Again, this was not very intuitive and I didn't find many examples on the Internet of this use case.


XSD:

 <element name="Root">
 <complexType>
  <sequence>
   <element ref="tns:TestVariables" minOccurs="1" maxOccurs="1"/>
  </sequence>
 </complexType>
</element>
 
<element name="TestVariables">
 <complexType>
  <sequence>
   <element name="TestVariable" minOccurs="0" maxOccurs="unbounded">
    <complexType>
     <attribute name="name" type="string" />
     <attribute name="value" type="string" />
    </complexType>
   </element>
  </sequence>
 </complexType>
</element>

XJB:

<jxb:bindings node="//xs:element[@name='Root']//xs:element[@ref='tns:TestVariables']">
 <jxb:property>
  <jxb:baseType name="test.TestMap" />
 </jxb:property>
</jxb:bindings>
 
Custom Java:

@XmlJavaTypeAdapter(TestAdapter.class)
public class TestMap extends LinkedHashMap<String,String>{ 

}

public class TestAdapter extends XmlAdapter<TestVariables, TestMap> {
 @Override
 public TestMap unmarshal(TestVariables value) {
  TestMap map = new TestMap();
  for (TestVariable var : value.getTestVariable())
   map.put(var.name, var.value);
  return map;
 }

 @Override
 public TestVariables marshal(TestMap map) {
  TestVariables vars = new TestVariables();
  for (Map.Entry entry : map.entrySet()) {
   TestVariable var = new TestVariable();
   var.name = entry.getKey();
   var.value = entry.getValue();
   vars.getTestVariable().add(var);
  }
  return vars;
 }

}


XJC Generated Java:

@XmlRootElement(name = "Root", namespace = "urn:test")
public class Root {

    @XmlElement(name = "TestVariables", namespace = "urn:test", required = true, type = TestVariables.class)
    protected TestMap testVariables;
    

Using the custom code:

Root root = new Root();
TestMap map = new TestMap();
root.setTestVariables(map);
..
m.marshal(root, writer);

There it is, two ways of injecting your own custom JAXB objects into the XJC generated object model. Now one can enjoy the full benefit of using a XML schema first development approach utilizing XJC to rebuild corresponding Java objects all the while having the flexibility to drop down to hand crafted JAXB objects when appropriate.

Windows Update Forced Restart Woes

Yet again I resumed my netbook only to have Windows Update shutdown my computer losing all my work, probably thirty minutes worth. All these tech companies are so adamant about piracy and losing revenue due to other people's actions. I wish these same companies would be held liable for their own reckless actions that cause lost revenue for people like me.

JAXB Custom XJC Plugin Limitations

I recently attempted to write my own JAXB XJC plugin which I thought would solve some schema derived code generation enhancements that I wanted to implement. It turns out Custom XJC Plugins are worthless beyond adding code to already defined generated classes or adding new classes. It turns out plugins are only invoked after the schema has been parsed into a schema model (Outline) and after all the JAXB classes have been generated in memory (CodeModel). While it is possible to remove fields from an existing class and perhaps even remove methods one cannot completely redefine a class because the schema and code models have been finalized by the time the plugin is invoked. Instead of having a plugin that could interact with the models at various phases it seems XJC plugins were an afterthought. Additionally I found the XJC code difficult to decipher albeit mapping one typed language to another one is not easy. I can now clearly see why the JAXB project has bugs that have not been addressed in six years. Beyond generating simply utility methods on generated classes expect no further value from writing an XJC Plugin.