
package gov.samhsa.consent2share.c32;

import gov.samhsa.consent2share.c32.dto.GreenCCD;

import java.io.StringReader;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * The Class GreenCcdSerializerImpl.
 */
public class GreenCcdSerializerImpl implements GreenCcdSerializer {

	/** The logger. */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * gov.samhsa.consent2share.c32.GreenCcdSerializer#Deserialize(java.lang
	 * .String)
	 */
	@Override
	public GreenCCD Deserialize(String greenCcdXml)
			throws GreenCcdSerializerException {
		Assert.hasText(greenCcdXml);

		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(GreenCCD.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			StringReader reader = new StringReader(greenCcdXml);
			GreenCCD greenCcd = (GreenCCD) unmarshaller.unmarshal(reader);
			reader.close();

			return greenCcd;

		} catch (Exception ex) {
			String erroMessage = "Error occured when trying to serialize Green CCD XML";
			logger.error(erroMessage, ex);
			throw new GreenCcdSerializerException(erroMessage, ex);
		}
	}
}
