From: Gautam J. <ga...@us...> - 2007-02-10 23:37:32
|
Update of /cvsroot/jaffa/JaffaCore/source/unittest/java/org/jaffa/persistence/blackboxtests/logging In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv28359/source/unittest/java/org/jaffa/persistence/blackboxtests/logging Added Files: DomainXmlReader.java DomainXmlTest.java DomainXmlWriter.java Log Message: Created sample classes to marshal a bunch of domain objects into XML, and unmarshal them back. Wrote UnitTest for the same. --- NEW FILE: DomainXmlWriter.java --- /* * ==================================================================== * JAFFA - Java Application Framework For All * * Copyright (C) 2002 JAFFA Development Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Redistribution and use of this software and associated documentation ("Software"), * with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name "JAFFA" must not be used to endorse or promote products derived from * this Software without prior written permission. For written permission, * please contact mail to: jaf...@ya.... * 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA" * appear in their names without prior written permission. * 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net). * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jaffa.persistence.blackboxtests.logging; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.LinkedList; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import org.jaffa.persistence.IPersistent; import org.jaffa.util.StringHelper; /** This class can be used to serialize a bunch of domain objects into XML. * * The XML format is * * <?xml version='1.0'?> * <rows> * * <!-- A <row> element represents a domain object --> * <row> * <!-- The <bean-class> element contains the fully qualified classname of the domain object --> * <bean-class></bean-class> * * <!-- The <bean-data> element contains the domain object serialized to XML. The contents will be ESCAPED --> * <bean-data></bean-data> * </row> * * <row> * ... * ... * </row> * * ... * ... * * </rows> * */ public class DomainXmlWriter { private Collection<IPersistent> m_objects = new LinkedList<IPersistent>(); /** Adds the input object to be serialized. * @param obj The object to be serialized. */ public void addObject(IPersistent obj) { m_objects.add(obj); } /** Generate XML based on the added objects. * @param w The writer to which the XML will be written to. * @throws IOException if any IO error occurs. */ public void write(Writer w) throws IOException { w.write("<?xml version='1.0'?>\n"); w.write("<rows>\n"); for (IPersistent obj : m_objects) { w.write(" <row>\n"); w.write(" <bean-class>"); w.write(obj.getClass().getName()); w.write("</bean-class>\n"); w.write(" <bean-data>\n"); try { StringWriter tempWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(new Class[] {obj.getClass()}); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty("jaxb.fragment", Boolean.TRUE); marshaller.marshal(obj, tempWriter); w.write(StringHelper.convertToHTML(tempWriter.toString())); } catch (Exception e) { throw new RuntimeException("Error in marshalling domain object to XML", e); } w.write("\n </bean-data>\n"); w.write(" </row>\n"); } w.write("</rows>\n"); } } --- NEW FILE: DomainXmlTest.java --- /* * ==================================================================== * JAFFA - Java Application Framework For All * * Copyright (C) 2002 JAFFA Development Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Redistribution and use of this software and associated documentation ("Software"), * with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name "JAFFA" must not be used to endorse or promote products derived from * this Software without prior written permission. For written permission, * please contact mail to: jaf...@ya.... * 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA" * appear in their names without prior written permission. * 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net). * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jaffa.persistence.blackboxtests.logging; import java.io.StringReader; import java.io.StringWriter; import java.util.Iterator; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.jaffa.persistence.UOW; import org.jaffa.persistence.blackboxtests.Wrapper; import org.jaffa.persistence.domainobjects.CategoryOfInstrument; import org.jaffa.persistence.domainobjects.Item; import org.jaffa.persistence.domainobjects.Part; /** This class will test the DomainXmlReader and DomainXmlWriter utilities. */ public class DomainXmlTest extends TestCase { private static final int ITEM_COUNT = 5; /** Assembles and returns a test suite containing all known tests. * @return A test suite. */ public static Test suite() { return new Wrapper(new TestSuite(DomainXmlTest.class)); } /** Creates new DomainXmlTest * @param name The name of the test case. */ public DomainXmlTest(String name) { super(name); } /** This method serializes a bunch of domain objects to XML. * The XML is then deserialized back to domain objects. */ public void testDomainXmlWriterReader() throws Exception { UOW uow = null; try { // Retrieve a few objects and add them to the DomainXmlWriter uow = new UOW(); DomainXmlWriter dxw = new DomainXmlWriter(); dxw.addObject(CategoryOfInstrument.findByPK(uow, "Z-TESTCI-01")); dxw.addObject(Part.findByPK(uow, "Z-TESTPART-01")); dxw.addObject(Part.findByPK(uow, "Z-TESTPART-02")); dxw.addObject(Item.findByPK(uow, "Z-TESTITEM-01")); dxw.addObject(Item.findByPK(uow, "Z-TESTITEM-03")); // write XML StringWriter w = new StringWriter(); dxw.write(w); // Now unmarhsal the XML into domain objects Object obj = null; String xml = w.toString(); System.out.println("*** Marshalled XML ***\n" + xml); DomainXmlReader dxr = new DomainXmlReader(new StringReader(xml)); Iterator itr = dxr.iterator(); // Verify the deserialzed objects obj = itr.next(); assertTrue("CategoryOfInstrument should have been generated", obj instanceof CategoryOfInstrument); assertEquals("Z-TESTCI-01", ((CategoryOfInstrument) obj).getCategoryInstrument()); assertEquals("Z-TESTCIDESC-01", ((CategoryOfInstrument) obj).getDescription()); obj = itr.next(); assertTrue("Part should have been generated", obj instanceof Part); assertEquals("Z-TESTPART-01", ((Part) obj).getPart()); assertEquals("Z-TESTNOUN-01", ((Part) obj).getNoun()); obj = itr.next(); assertTrue("Part should have been generated", obj instanceof Part); assertEquals("Z-TESTPART-02", ((Part) obj).getPart()); assertEquals("Z-TESTNOUN-02", ((Part) obj).getNoun()); obj = itr.next(); assertTrue("Item should have been generated", obj instanceof Item); assertEquals("Z-TESTITEM-01", ((Item) obj).getItemId()); obj = itr.next(); assertTrue("Item should have been generated", obj instanceof Item); assertEquals("Z-TESTITEM-03", ((Item) obj).getItemId()); assertTrue("No more records should exist", !itr.hasNext()); } catch (Exception e) { e.printStackTrace(); fail(); } finally { if (uow != null) uow.rollback(); } } } --- NEW FILE: DomainXmlReader.java --- /* * ==================================================================== * JAFFA - Java Application Framework For All * * Copyright (C) 2002 JAFFA Development Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Redistribution and use of this software and associated documentation ("Software"), * with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name "JAFFA" must not be used to endorse or promote products derived from * this Software without prior written permission. For written permission, * please contact mail to: jaf...@ya.... * 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA" * appear in their names without prior written permission. * 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net). * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jaffa.persistence.blackboxtests.logging; import java.io.Reader; import java.io.StringReader; import java.util.Iterator; import java.util.NoSuchElementException; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** This class can be used to unmarshal XML of the following format into domain objects. * * The XML format is * * <?xml version='1.0'?> * <rows> * * <!-- A <row> element represents a domain object --> * <row> * <!-- The <bean-class> element contains the fully qualified classname of the domain object --> * <bean-class></bean-class> * * <!-- The <bean-data> element contains the domain object serialized to XML. The contents will be ESCAPED --> * <bean-data></bean-data> * </row> * * <row> * ... * ... * </row> * * ... * ... * * </rows> * */ public class DomainXmlReader { private Reader m_xml = null; private XMLEventReader m_xer = null; /** Creates an instance * @param xml The XML to be unmarshalled. */ public DomainXmlReader(Reader xml) { m_xml = xml; } /** Returns an Iterator for iterating through the domain objects unmarshalled from the source XML. * @return an Iterator for iterating through the domain objects unmarshalled from the source XML. * @throws XMLStreamException if any error occurs during XML parsing. */ public Iterator iterator() throws XMLStreamException { if (m_xer != null) throw new UnsupportedOperationException("Only one iterator can be obtained from this instance"); XMLInputFactory factory = XMLInputFactory.newInstance(); m_xer = factory.createXMLEventReader(m_xml); return new XmlIterator(); } /** This is a Custom implementation of the Iterator. It unmarshals the XML on demand. */ private class XmlIterator implements Iterator { private String m_beanClass = null; private Object m_beanData = null; /** Returns true if any more domain objects can be unmarshalled from the XML. * @return true if any more domain objects can be unmarshalled from the XML. */ public boolean hasNext() { if (m_beanData == null) parseXml(); return m_beanData != null; } /** Returns the next domain object unmarshalled from the XML. * A NoSuchElementException is thrown if the end of the XML document is reached. * @return the next domain object unmarshalled from the XML. */ public Object next() { if (hasNext()) { Object obj = m_beanData; m_beanData = null; return obj; } else { throw new NoSuchElementException("No more elements to iterate through"); } } /** This method is not supported. * An UnsupportedOperationException will always be thrown. */ public void remove() { throw new UnsupportedOperationException("Remove operation is not supported on this iterator"); } /** Parses the XML until a domain object is unmarshalled. */ private void parseXml() { while (m_beanData == null && m_xer.hasNext()) { try { XMLEvent event = (XMLEvent) m_xer.next(); if (event.isStartElement()) { QName qname = ((StartElement) event).getName(); String namespaceURI = qname.getNamespaceURI(); String localName = qname.getLocalPart(); if ("bean-class".equals(localName)) { m_beanClass = m_xer.getElementText(); } else if ("bean-data".equals(localName)) { String s = m_xer.getElementText(); JAXBContext jc = JAXBContext.newInstance(new Class[] {Class.forName(m_beanClass)}); Unmarshaller unmarshaller = jc.createUnmarshaller(); m_beanData = unmarshaller.unmarshal(new StringReader(s)); } } } catch (Exception e) { throw new RuntimeException("Error in parsing XML", e); } } } } } |