/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: TemplateReaderInterceptor.java 69498 2013-01-14 14:49:15Z supol $ 
 */

package com.sun.ts.tests.jaxrs.api.rs.ext.interceptor.reader;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;

import com.sun.ts.tests.jaxrs.api.rs.ext.interceptor.InterceptorCallbackMethods;
import com.sun.ts.tests.jaxrs.api.rs.ext.interceptor.TemplateInterceptorBody;

/**
 * This class is a superclass for any interceptor @Provider.
 * Any such provider is then given a body, inherited from TemplateInterceptorBody.
 * The body actually contains methods with name equalIgnoreCase to ContextOperation
 * items name, the name of the method executed is passed by http header OPERATION
 * @see TemplateInterceptorBody   
 * 
 * The injection of the body solves the issue with inheritance 
 * from two super-classes.
 */
public abstract class TemplateReaderInterceptor implements ReaderInterceptor,
		InterceptorCallbackMethods {

	protected ReaderInterceptorContext readerCtx;
	protected TemplateInterceptorBody<ReaderInterceptorContext> interceptorBody;

	public TemplateReaderInterceptor(
			TemplateInterceptorBody<ReaderInterceptorContext> interceptorBody) {
		super();
		this.interceptorBody = interceptorBody;
	}

	@Override
	public Object aroundReadFrom(ReaderInterceptorContext ctx)
			throws IOException, WebApplicationException {
		this.readerCtx = ctx;
		return interceptorBody.executeMethod(readerCtx, this);
	}

	@Override
	public void writeEntity(String entity) {
		readerCtx.setInputStream(new ByteArrayInputStream(entity.getBytes()));
	}

	@Override
	public Object proceed() throws IOException {
		return readerCtx.proceed();
	}

	@Override
	public String getHeaderString() {
		MultivaluedMap<String, String> headers = readerCtx.getHeaders();
		return headers.getFirst(TemplateInterceptorBody.OPERATION);
	}

}
