users@jaxb.java.net

Compiling schemas in the runtime

From: Aleksei Valikov <valikov_at_gmx.net>
Date: Fri, 12 Oct 2007 09:47:14 +0200

Hi there,

Last weeks few users asked how to compile schemas in the runtime. I
did a small example on that and I'd like to share it.

I assume that you have schema files, binding files and (optionally) a
catalog file to resolve external schemas.

What you need to do is:
1) Generate the code.
2) Compile this code.
3) Create and use the class loader with the compiled classes.

I'm attaching the source code of the DynamicCompiler which implements
these task. After initializing and calling execute() you can get a
class loader and a context path of the generated classes.

Here is a small usage example:

        public void testUnmarshall() throws Exception {

                final File schema = new File(getClass().getResource("schema.xsd")
                                .toURI());
                final File bindings = new File(getClass().getResource("bindings.xjb")
                                .toURI());
                final File sample = new File(getClass().getResource("po.xml").toURI());

                final DynamicCompiler compiler = new DynamicCompiler(
                                new File[] { schema }, new File[] { bindings }, null,
                                temporaryDirectory);

                compiler.execute();

                final JAXBContext context = JAXBContext.newInstance(compiler
                                .getContextPath(), compiler.getClassLoader());

                final JAXBElement element = (JAXBElement) context.createUnmarshaller()
                                .unmarshal(sample);

                final String elementValueClassName = element.getValue().getClass()
                                .getName();
                logger.debug("We have just loaded an instance of ["
                                + elementValueClassName + "]");
                Assert
                                .assertEquals(
                                                "org.jvnet.hyperjaxb3.ejb.tests.pocustomized.PurchaseOrderType",
                                                elementValueClassName);
        }

The DynamicCompiler version I've attached also turns on few plugins,
feel free to modify getArguments() for a different set of plugins you
want to load.

The solution only works with files at the moment, however switching to
URIs is not a big deal.

If you don't see the attachment, let me know.

Bye.
/lexi