All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.itelg.spring.xml.unmarshaller.XPathUnmarshaller Maven / Gradle / Ivy

There is a newer version: 0.3.0-RELEASE
Show newest version
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 + ")");
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy