/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: EntityReaderInterceptor.java 71408 2013-04-04 11:49:25Z supol $  
 */

package com.sun.ts.tests.jaxrs.spec.filter.interceptor;

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

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

@Provider
public class EntityReaderInterceptor implements ReaderInterceptor {

	@Override
	public Object aroundReadFrom(ReaderInterceptorContext context)
			throws IOException, WebApplicationException {
		MultivaluedMap<String, String> headers = context.getHeaders();
		String header = headers.getFirst(Resource.HEADERNAME);
		if (header != null && header.startsWith(getClass().getName())) {
			StringBuilder sb = new StringBuilder().append("<interceptor>")
					.append(getClass().getName());
			if (header.contains(Resource.DIRECTION))
				sb.append(Resource.DIRECTION);
			sb.append("</interceptor>");
			String content = sb.toString();
			ByteArrayInputStream stream = new ByteArrayInputStream(
					content.getBytes());
			context.setInputStream(stream);
		}
		return context.proceed();
	}
}
