/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.util;

import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;

/**
 * This provides OutputStream that delegates to com.sleepycat.util.FastOutputStream 
 * if it is available and if it is not it delegates to java.io.ByteArrayOutputStream.
 * 
 * This class allows ActiveMQ to not be dependent on the bdb lib.  It might 
 * be worth it to just fully implement a FastOutputStream ourselfs.  I think
 * it's just a ByteArrayOutputStream what is not thread safe.
 * 
 * @version $Revision: 1.1 $
 */
public class FastOutputStream extends FilterOutputStream {

	public FastOutputStream() {
		super(createOutputStream());
	}
	private static OutputStream createOutputStream() {
		try {
			Class c = FastOutputStream.class.getClassLoader().loadClass("com.sleepycat.util.FastOutputStream");
			return (OutputStream) c.newInstance();
		} catch (Throwable e) {
			return new ByteArrayOutputStream(); 
		}
	}

	public byte[] toByteArray() {
		if( out instanceof ByteArrayOutputStream ) {
			return ((ByteArrayOutputStream)out).toByteArray();
		}
		try {
			Method method = out.getClass().getMethod("toByteArray",new Class[]{});
			return (byte[]) method.invoke(out, new Object[]{});
		} catch (Throwable e) {
			throw new RuntimeException("Could not invoke toByteArray() method on "+out.getClass(), e);
		}
	}
}
