package org.bench4q.share.helper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class MarshalHelper {

	public static String marshal(Class<?> classToMarshal, Object input)
			throws JAXBException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		Marshaller marshaller;
		marshaller = JAXBContext.newInstance(classToMarshal).createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		marshaller.marshal(input, os);
		try {
			return os.toString("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static Object unmarshal(Class<?> classToUnmarshal, String input)
			throws JAXBException {
		try {
			Unmarshaller unmarshaller;
			unmarshaller = JAXBContext.newInstance(classToUnmarshal)
					.createUnmarshaller();

			return unmarshaller.unmarshal(new ByteArrayInputStream(input
					.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static void main(String args[]) {
	}

	/**
	 * 
	 * @param classToUnmarshal
	 * @param input
	 * @return null if there is an exception happened.
	 */
	public static Object tryUnmarshal(Class<?> classToUnmarshal, String input) {
		try {
			return unmarshal(classToUnmarshal, input);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String tryMarshal(Object result) {
		try {
			return marshal(result.getClass(), result);
		} catch (Exception e) {
			return null;
		}
	}
}
