001    /** 
002     * 
003     * Copyright 2004 Hiram Chirino
004     * 
005     * Licensed under the Apache License, Version 2.0 (the "License"); 
006     * you may not use this file except in compliance with the License. 
007     * You may obtain a copy of the License at 
008     * 
009     * http://www.apache.org/licenses/LICENSE-2.0
010     * 
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS, 
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
014     * See the License for the specific language governing permissions and 
015     * limitations under the License. 
016     * 
017     **/
018    package org.activemq.util;
019    
020    import java.io.ByteArrayOutputStream;
021    import java.io.FilterOutputStream;
022    import java.io.OutputStream;
023    import java.lang.reflect.Method;
024    
025    /**
026     * This provides OutputStream that delegates to com.sleepycat.util.FastOutputStream 
027     * if it is available and if it is not it delegates to java.io.ByteArrayOutputStream.
028     * 
029     * This class allows ActiveMQ to not be dependent on the bdb lib.  It might 
030     * be worth it to just fully implement a FastOutputStream ourselfs.  I think
031     * it's just a ByteArrayOutputStream what is not thread safe.
032     * 
033     * @version $Revision: 1.1.1.1 $
034     */
035    public class FastOutputStream extends FilterOutputStream {
036    
037            public FastOutputStream() {
038                    super(createOutputStream());
039            }
040            private static OutputStream createOutputStream() {
041                    try {
042                            Class c = FastOutputStream.class.getClassLoader().loadClass("com.sleepycat.util.FastOutputStream");
043                            return (OutputStream) c.newInstance();
044                    } catch (Throwable e) {
045                            return new ByteArrayOutputStream(); 
046                    }
047            }
048    
049            public byte[] toByteArray() {
050                    if( out instanceof ByteArrayOutputStream ) {
051                            return ((ByteArrayOutputStream)out).toByteArray();
052                    }
053                    try {
054                            Method method = out.getClass().getMethod("toByteArray",new Class[]{});
055                            return (byte[]) method.invoke(out, new Object[]{});
056                    } catch (Throwable e) {
057                            throw new RuntimeException("Could not invoke toByteArray() method on "+out.getClass(), e);
058                    }
059            }
060    }