Tuesday, October 07, 2008

Callable and the Case of the Disappearing Exceptions

If you have a class that implements Callable, but you don't plan on using the Future that is returned after you call Executor.submit(), you may lose any exceptions that are thrown. They literally disappear into the void. No log whatsoever.

So it is good practice to treat it a bit like you would with a Runnable and wrap the code in your call method with a try/catch to print the exception or log it somewhere.

Thursday, October 02, 2008

How To Give a User Root Access on Linux

NOTE: I take no responsibility for using the following and do not recommend using it.

But for those that want it:

usermod -G root username


This changes the user with ‘username’ to the root group and thus gives root access.



And remember, as Uncle Ben says, “with great power comes great responsibility”.

Wednesday, October 01, 2008

Using JAXB Without Annotations

The latest JAXB included with JDK 1.6 is really a great addition to the JDK making it easy to send objects around in XML format without requiring any third party libraries. All you have to do is put an @XmlRootElement annotation on a class and then call:

marshaller.marshal(Object, OutputStream);

Example class using @XmlRootElement:

@XmlRootElement
class MyClass {
  String name;
  String content;
}


To read the object back in, you simply call:



MyClass object = unmarshaller.unmarshal(InputStream);



But what if you are building a library that doesn’t know what the class is and doesn’t have the @XmlRootElement annotation?  Well it turns out that it’s almost just as easy without it you just need to let JAXB know what class you expect.



First get the JAXBContext like this:



JAXBContext context = JAXBContext.newInstance(object.getClass());


To marshal:



marshaller.marshal(new JAXBElement(new QName(object.getClass().getSimpleName()), object.getClass(), object), out);


To unmarshal:



JAXBElement o = unmarshaller.unmarshal(new StreamSource(inputStream), expectedType);
MyClass object = o.getValue();


That’s it.