Created
January 3, 2013 07:13
-
-
Save codyaray/4441436 to your computer and use it in GitHub Desktop.
Simple AbstractXmlReader for building RESTful web services with Jersey using Guava to find the generic parameter types. See http://codyaray.com/2013/01/finding-generic-type-parameters-with-guava for details.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mydomain.myapp.resources.xml; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.lang.annotation.Annotation; | |
import java.lang.reflect.Type; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.MultivaluedMap; | |
import javax.ws.rs.ext.MessageBodyReader; | |
import javax.xml.parsers.DocumentBuilder; | |
import com.google.common.base.Throwables; | |
import com.google.common.reflect.TypeToken; | |
import org.w3c.dom.Element; | |
import org.xml.sax.SAXException; | |
/** | |
* Base class for Jersey XML readers. | |
* | |
* @param <T> the type of the domain object | |
* @author codyaray | |
* @since 7/15/12 | |
*/ | |
public abstract class AbstractXmlReader<T> implements MessageBodyReader<T> { | |
@SuppressWarnings("serial") | |
private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) { }; | |
private final Type type = typeToken.getType(); | |
private final DocumentBuilder builder; | |
protected AbstractXmlReader(DocumentBuilder builder) { | |
this.builder = builder; | |
} | |
@Override | |
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, | |
MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) | |
throws IOException, WebApplicationException { | |
try { | |
return fromXml(builder.parse(entityStream).getDocumentElement()); | |
} catch (SAXException e) { | |
throw Throwables.propogate(e); | |
} | |
} | |
@Override | |
public boolean isReadable(Class<?> type, Type genericType, | |
Annotation[] annotations, MediaType mediaType) { | |
return MediaType.TEXT_XML_TYPE.equals(mediaType) && this.type.equals(genericType); | |
} | |
/** | |
* Subclasses implement this method to read the domain object from the xml dom. | |
* | |
* @param documentElement root document element | |
* @return domain object | |
* @throws org.xml.sax.SAXException | |
*/ | |
protected abstract T fromXml(Element documentElement) throws SAXException; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment