

package gov.va.med.cds.testharness.examples;


import gov.va.med.cds.junit.runners.Suite;
import gov.va.med.cds.junit.runners.SuiteAwareRunner;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.thoughtworks.xstream.XStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;


/**
 * Demonstrates how to serialize and hydrate Java objects to and from xml
 * using the XStream library
 *
 */
@RunWith( SuiteAwareRunner.class )
public class SerializeToXmlTest
{
    public class SerializeToXmlSampleClass
        implements
            Serializable
    {
        private static final long serialVersionUID = -4053408935890457868L;

        private int firstProperty = 10;


        public int getFirstProperty( )
        {
            return firstProperty;
        }


        public void setFirstProperty( int firstProperty )
        {
            this.firstProperty = firstProperty;
        }
    }


    /**
     * Unit test demonstrating the serialize and hydrate of a Java object
     * to a file
     * @throws FileNotFoundException
     * @throws IOException
     */
    @Test
    @Suite( groups = "checkintest" )
    public void testSerializeToXml( )
        throws FileNotFoundException,
            IOException
    {
        try
        {
            XStream xstream = new XStream();
            OutputStream out = new FileOutputStream( "test.xml" );
            SerializeToXmlSampleClass toWrite = new SerializeToXmlSampleClass();
            xstream.toXML( toWrite, out );
            out.close();

            InputStream in = new FileInputStream( "test.xml" );
            SerializeToXmlSampleClass hydrated = ( SerializeToXmlSampleClass )xstream.fromXML( in );
            Assert.assertNotNull( hydrated );
            Assert.assertEquals( toWrite.getFirstProperty(), hydrated.getFirstProperty() );
        }
        finally
        {
            File f = new File( "test.xml" );
            if ( f.exists() )
                f.delete();
        }
    }
}
