package com.sun.persistence.tools.apt; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.*; /** * This class reads/writes Persistence XML deployment descriptor and builds a * descriptor object graph. * * @author Sanjeeb Sahoo * @version 1.0 */ public class XMLReaderWriter { public PersistenceDescriptor read(InputStream is) throws IOException { try { JAXBContext jc = JAXBContext.newInstance( PersistenceDescriptor.class.getPackage().getName(), getClass().getClassLoader()); Unmarshaller unmarshaller = jc.createUnmarshaller(); return (PersistenceDescriptor) unmarshaller.unmarshal(is); } catch (JAXBException je) { je.printStackTrace(); IOException ioe = new IOException(); ioe.initCause(je); throw ioe; } } public void write(PersistenceDescriptor persistenceJar, OutputStream os) throws IOException { try { getMarshaller(persistenceJar.getClass()).marshal(persistenceJar, os); } catch (JAXBException je) { je.printStackTrace(); IOException ioe = new IOException(); ioe.initCause(je); throw ioe; } } public void write(PersistenceDescriptor persistenceJar, Writer writer) throws IOException { try { getMarshaller(persistenceJar.getClass()).marshal(persistenceJar, writer); } catch (JAXBException je) { je.printStackTrace(); IOException ioe = new IOException(); ioe.initCause(je); throw ioe; } } private Marshaller getMarshaller(Class clazz) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(), getClass().getClassLoader()); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); return marshaller; } public static void main(String... args) throws IOException { PersistenceDescriptor dd = new XMLReaderWriter().read( new FileInputStream(new File(args[0]))); new XMLReaderWriter().write(dd, System.out); } }