Sunday, May 26, 2013

Guava Joiner: Converting an Iterable into a String

Guava's Joiner makes it really easy to convert an Iterable into a String, so you no longer have to iterate over it and build the String manually. Here is an example:
// joining a list
final List<String> fruits = Lists.newArrayList("apple", "banana", null, "cherry");
System.out.println(Joiner.on(", ").skipNulls().join(fruits));

// joining a map
final Map<String, Integer> people = ImmutableMap.of("Alice", 21, "Bob", 19);
System.out.println(Joiner.on("\n").withKeyValueSeparator(": ").join(people));
prints:
apple, banana, cherry
Alice: 21
Bob: 19

Saturday, May 25, 2013

JAXB: Marshalling/Unmarshalling Example

This post shows how you can marshal a JAXB object into XML and unmarshal XML into a JAXB object.

Consider the following JAXB class:

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Book {

  @XmlElement
  private String author;

  @XmlElement
  private String title;
}
Unmarshalling:
To convert an XML string into an object of class Book:
public static Book unmarshal(final String xml) throws JAXBException {
  return (Book) JAXBContext.newInstance(Book.class)
                           .createUnmarshaller()
                           .unmarshal(new StringReader(xml));
}
Marshalling:
To convert a Book object into an XML string:
public static String marshal(Book book) throws JAXBException {
  final Marshaller m = JAXBContext.newInstance(Book.class)
                                  .createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  final StringWriter w = new StringWriter();
  m.marshal(book, w);
  return w.toString();
}