/**
 * JAXB Demonstration Example
 * @author Jaeho Shin <netj@sparcs.org>
 * Created: 2008-05-16
 * See: http://java.sun.com/javase/6/docs/technotes/guides/xml/jaxb/index.html
 *      http://java.sun.com/developer/technicalArticles/WebServices/jaxb/
 *      http://java.sun.com/javaee/5/docs/tutorial/doc/bnazf.html
 */

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class TestSuite {
	@XmlAttribute
	String name;
	@XmlElement
	List<TestCase> testcase;

	TestSuite() {
	}

	TestSuite(String name, List<TestCase> testcase) {
		this.name = name;
		this.testcase = testcase;
	}
}

class TestCase {
	@XmlAttribute
	String name;
	@XmlElement
	int repeat;
	@XmlElement
	boolean result;
	@XmlAttribute
	double testTime;

	TestCase() {
	}

	TestCase(String name, int repeat, boolean result, double testTime) {
		this.name = name;
		this.repeat = repeat;
		this.result = result;
		this.testTime = testTime;
	}
}

public class JAXBDemo {

	public static void main(String[] args) {
		try {
			TestSuite ts = createSampleTestSuite();
			writeXML(ts, System.out);
			ts = readXML(System.in);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	private static TestSuite createSampleTestSuite() {
		List<TestCase> testcases = new ArrayList<TestCase>();
		testcases.add(new TestCase("test case 1", 1, false, 0.1));
		testcases.add(new TestCase("test case 2", 1, false, 0.5));
		testcases.add(new TestCase("test case 3", 1, false, 1.7));
		return new TestSuite("sample", testcases);
	}

	private static TestSuite readXML(InputStream xmlInput) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(TestSuite.class);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		TestSuite ts = (TestSuite) unmarshaller.unmarshal(xmlInput);
		return ts;
	}

	private static void writeXML(TestSuite ts, OutputStream xmlOutput)
			throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(TestSuite.class);
		Marshaller marshaller = jaxbContext.createMarshaller();
		marshaller.marshal(ts, xmlOutput);
	}
}

