com.itelg.spring.xml.unmarshaller.XPathUnmarshaller Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spring-xml-extensions Show documentation
Show all versions of spring-xml-extensions Show documentation
Spring Marshaller/Unmarshaller based on Xom
package com.itelg.spring.xml.unmarshaller;
import java.util.LinkedList;
import java.util.List;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException;
import nu.xom.Builder;
import nu.xom.Document;
public class XPathUnmarshaller implements Unmarshaller
{
private List> parsers = new LinkedList<>();
public XPathUnmarshaller(List> parsers)
{
this.parsers = parsers;
}
public XPathUnmarshaller()
{
}
public void addParser(ConverterParser> parser)
{
parsers.add(parser);
}
public List> getParsers()
{
return parsers;
}
@Override
public boolean supports(final Class> clazz)
{
for (ConverterParser> parser : parsers)
{
if (clazz.equals(parser.getSupportingClass()))
{
return true;
}
}
return false;
}
@Override
public Object unmarshal(final Source source) throws XmlMappingException
{
try
{
Document doc;
if (((StreamSource) source).getInputStream() != null)
{
doc = new Builder().build(((StreamSource) source).getInputStream());
}
else
{
doc = new Builder().build(((StreamSource) source).getReader());
}
return lookup(doc.getRootElement().getLocalName()).doParse(doc.getRootElement());
}
catch (Exception e)
{
throw new UnmarshallingFailureException("Unmarshalling failed: " + e.getMessage(), e);
}
}
private ConverterParser> lookup(final String localName) throws Exception
{
for (ConverterParser> parser : parsers)
{
if (localName.equalsIgnoreCase(parser.getRootTagName()))
{
return parser;
}
}
throw new Exception("No parser configured (Root-Tag: " + localName + ")");
}
}