October 15, 2009

JAXB2: Marshalling fails due to validation, but you can't see the error

Having used JAXB2 to construct a tree of XML from objects, you try and marshall your objects to XML, only to find you get an Exception telling you your resulting XML has failed validation. But as you cannot see the generated XML, you have no way to see where you've gone wrong.


JAXB2 has a deprecated the javax.xml.bind.Validator class, and the person who documented this didn't bother to document the mechanism to replace it.

What I did manage to find was the javax.xml.bind.util.ValidationEventCollector class, which you can add to your Marshaller object, like this:

			ValidationEventCollector collector = new ValidationEventCollector();

Now the marshaling works! And your errors can be retrieved from ValidationEventCollector, like this:


Hopefully this will save someone some pain.

June 07, 2008

Importing private keys into a Java keystore using keytool

For ages the keytool application shipped as part of Java could provide all the functionality to generate a private key and certificate sign request from a Java keystore, but the most basic function, importing a preexisting private key and certificate generated externally, remained overlooked.

This is fixed in Java 6, at long last.

The solution is to convert your existing certificate and key into a PKCS12 file, and then use the keytool functionality to merge one keystore with another one. Java 6 can treat a PKCS12 file as a keystore, so putting this together, you get this:

keytool -importkeystore -deststorepass changeit -destkeypass changeit -destkeystore my-keystore.jks -srckeystore cert-and-key.p12 -srcstoretype PKCS12 -srcstorepass cert-and-key-password -alias 1

The alias of 1 is required to choose the certificate in the source PKCS12 file, keytool isn't clever enough to figure out which certificate you want in a store containing one certificate.

At last, it works.