package org.openrdf.server.metadata.providers.base;

import static org.openrdf.http.protocol.Protocol.X_QUERY_TYPE;
import info.aduna.lang.FileFormat;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.openrdf.result.Result;
import org.openrdf.store.StoreException;

public abstract class ResultMessageWriterBase<T extends Result> extends
		MessageWriterBase<T> {
	private String queryType;

	public ResultMessageWriterBase(FileFormat format, Class<T> type) {
		super(format, type);
	}

	public void setQueryType(String queryType) {
		this.queryType = queryType;
	}

	public void writeTo(T result, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders, OutputStream out)
			throws IOException, WebApplicationException {
		String contentType = format.getDefaultMIMEType();
		Charset charset = getCharset(mediaType);
		if (format.hasCharset()) {
			contentType += "; charset=" + charset.name();
		}
		httpHeaders.putSingle("Content-Type", contentType);
		if (queryType != null) {
			httpHeaders.putSingle(X_QUERY_TYPE, queryType);
		}
		try {
			writeTo(result, out, charset);
		} catch (IOException e) {
			throw e;
		} catch (WebApplicationException e) {
			throw e;
		} catch (Exception e) {
			throw new WebApplicationException(e);
		} finally {
			try {
				result.close();
			} catch (StoreException e) {
				// TODO logger
				e.printStackTrace();
			}
		}
	}

	public abstract void writeTo(T result, OutputStream out, Charset charset) throws Exception;

}

@@ -1037,237 +1037,15 @@
 %7B%0A%09%09
-S
 tr
-ing contentType = format.getDefaultMIMEType();%0A%09%09Charset charset = getCharset(mediaType);%0A%09%09if (format.hasCharset()) %7B%0A%09%09%09contentType += %22; charset=%22 + charset.name();%0A%09%09%7D%0A%09%09httpHeaders.putSingle(%22Content-Type%22, contentType);%0A
+y %7B%0A%09
 %09%09if
@@ -1067,16 +1067,17 @@
 null) %7B%0A
+%09
 %09%09%09httpH
@@ -1125,21 +1125,20 @@
 ;%0A%09%09
+%09
 %7D%0A%09%09
-try %7B%0A%09%09%09
+%09super.
 writ
@@ -1153,179 +1153,72 @@
 lt, 
-out, charset);%0A%09%09%7D catch (IOException e) %7B%0A%09%09%09throw e;%0A%09%09%7D catch (WebApplicationException e) %7B%0A%09%09%09throw e;%0A%09%09%7D catch (Exception e) %7B%0A%09%09%09throw new WebApplicationException(e
+type, genericType, annotations, mediaType,%0A%09%09%09%09%09httpHeaders, out
 );%0A%09
@@ -1422,17 +1422,20 @@
 charset)
- 
+%0A%09%09%09
 throws E

Call super class method and reduce code duplication