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

com.github.resource4j.extras.xstream.XStreamParser Maven / Gradle / Ivy

There is a newer version: 3.3.1
Show newest version
package com.github.resource4j.extras.xstream;

import java.io.IOException;

import com.github.resource4j.ResourceObject;
import com.github.resource4j.ResourceObjectException;
import com.github.resource4j.objects.parsers.AbstractValueParser;
import com.github.resource4j.objects.parsers.ResourceObjectFormatException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamParser extends AbstractValueParser {

	private Class type;
	
	private XStream xstream;
	
	public static  XStreamParser xml(Class type) {
		XStream xstream = new XStream(new StaxDriver());
		xstream.processAnnotations(type);
		return new XStreamParser<>(type, xstream);
	}

	public static  XStreamParser xml(Class type, XStream xstream) {
		return new XStreamParser<>(type, xstream);
	}
	
	public XStreamParser(Class type, XStream xstream) {
		this.type = type;
		this.xstream = xstream;
	}
	
	@Override
	protected T parse(ResourceObject file) throws IOException, ResourceObjectException {
		Object object = null;
		try {
			object = xstream.fromXML(file.asStream());
			return type.cast(object);
		} catch (XStreamException e) {
			throw new ResourceObjectFormatException(file, "Cannot parse resource object");
		} catch (ClassCastException e) {
			throw new ResourceObjectFormatException(file,
					"Resource data type " + object.getClass().getName() 
					+ " does not match requested " + type.getName());
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy