/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: AbstractAddInterceptor.java 69718 2013-01-31 11:55:55Z supol $  
 */

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

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

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;

import com.sun.ts.tests.jaxrs.common.util.JaxrsUtil;

public abstract class AbstractAddInterceptor implements ReaderInterceptor,
		WriterInterceptor {

	private int amount;

	public AbstractAddInterceptor(int amount) {
		this.amount = amount;
	}

	@Override
	public void aroundWriteTo(WriterInterceptorContext context)
			throws IOException, WebApplicationException {
		String entity = (String) context.getEntity();
		if (entity != null) { //when unhandled exception, status 500 
							  //does not have entity
			Integer i = Integer.parseInt(entity);
			entity = String.valueOf(i + amount);
			context.setEntity(entity);
		}
		context.proceed();
	}

	@Override
	public Object aroundReadFrom(ReaderInterceptorContext context)
			throws IOException, WebApplicationException {
		InputStream inputStream = context.getInputStream();
		String entity = JaxrsUtil.readFromStream(inputStream);
		if (entity != null) {
			Integer i = Integer.parseInt(entity);
			entity = String.valueOf(i + amount);
			context.setInputStream(new ByteArrayInputStream(entity.getBytes()));
		}
		return context.proceed();
	}

}
