/* * AnimalXmlSerializer.java * * Created on: 08-Apr-2010 * */ package netukar.animalia.rest.xml; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import netukar.animalia.Animal; import netukar.animalia.rest.AnimalSerializer; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author Radovan Netuka */ public class AnimalXmlSerializer implements AnimalSerializer { private Animal animal; /** * Creates a new instance of AnimalXmlSerializer. */ public AnimalXmlSerializer() { } public void setAnimal(Animal animal) { if (animal == null) { throw new IllegalArgumentException("Parameter animal cannot be null"); } this.animal = animal; } @Override public String toString() { if (animal == null) { throw new IllegalStateException("No animal has been set"); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element animalElement = document.createElement("animal"); document.appendChild(animalElement); Element genus = document.createElement("genus"); genus.setTextContent(animal.getGenus()); animalElement.appendChild(genus); Element species = document.createElement("species"); species.setTextContent(animal.getSpecies()); animalElement.appendChild(species); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, result); return writer.toString(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (TransformerConfigurationException ex) { throw new RuntimeException(ex); } catch (TransformerException ex) { throw new RuntimeException(ex); } } }