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

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

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.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;

import com.sun.ts.tests.jaxrs.common.impl.ReplacingOutputStream;

@Provider
public class EntityWriterInterceptor implements WriterInterceptor {

	@Override
	public void aroundWriteTo(WriterInterceptorContext context)
			throws IOException, WebApplicationException {
		MultivaluedMap<String, Object> headers = context.getHeaders();
		String header = (String) headers.getFirst(Resource.HEADERNAME);
		if (header != null && header.startsWith(getClass().getName())) {
			StringBuilder sb = new StringBuilder();
			sb.append("<interceptor>").append(getClass().getName());
			if (header.contains(Resource.DIRECTION))
				sb.append(Resource.DIRECTION);
			sb.append("</interceptor>");
			String content = sb.toString();
			ReplacingOutputStream stream = new ReplacingOutputStream(
					context.getOutputStream(), content);
			context.setOutputStream(stream);
			headers.remove(Resource.HEADERNAME);
		}
		context.proceed();
	}
}
