litesoft
@ 950
litesoft / trunk / Java / Rest / RestfulDTOs / DTOsupport / src / org / litesoft / rest / adapters / JAXB_Helper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package org.litesoft.rest.adapters; import java.io.*; import javax.xml.bind.*; import org.litesoft.rest.utils.*; @SuppressWarnings({"UnusedDeclaration"}) public class JAXB_Helper { private static final String OBJECT_FACTORY_NAME_SUFFIX = ".ObjectFactory"; private JAXBContext mContext; public JAXB_Helper( Class pObjectFactoryClass ) throws JAXBException { notNull( "Object Factory Class", pObjectFactoryClass ); String zName = pObjectFactoryClass.getName(); if ( !zName.endsWith( OBJECT_FACTORY_NAME_SUFFIX ) ) { throw new IllegalArgumentException( "Object Factory Class Name did NOT end with: " + OBJECT_FACTORY_NAME_SUFFIX ); } mContext = JAXBContext.newInstance( zName.substring( 0, zName.length() - OBJECT_FACTORY_NAME_SUFFIX.length() ) ); } public String toXML( JAXBgeneratedClassSuperClass pInstance ) throws JAXBException { StringWriter zWriter = new StringWriter(); toXML( pInstance, zWriter ); return zWriter.toString(); } public void toXML( JAXBgeneratedClassSuperClass pInstance, Writer pWriter ) throws JAXBException { notNull( "Instance to convert to XML", pInstance ); notNull( "Writer", pWriter ); // Currently we are creating a new Marshaller each time as the spec does specify reentrancy Marshaller zMarshaller = mContext.createMarshaller(); zMarshaller.marshal( pInstance, pWriter ); } public <T extends JAXBgeneratedClassSuperClass> T fromXML( Class<T> pType, String pXML ) throws JAXBException { notNull( "XML", pXML ); return fromXML( pType, new StringReader( pXML ) ); } public <T extends JAXBgeneratedClassSuperClass> T fromXML( Class<T> pType, Reader pReader ) throws JAXBException { notNull( "Type create from XML", pType ); notNull( "Reader", pReader ); // Currently we are creating a new Unmarshaller each time as the spec does specify reentrancy Unmarshaller zUnmarshaller = mContext.createUnmarshaller(); Object o = zUnmarshaller.unmarshal( pReader ); return Unchecked.cast( pType, o ); } private static void notNull( String pWhat, Object pToCheck ) { if ( pToCheck == null ) { throw new IllegalArgumentException( pWhat + " was Null" ); } } } |