View Javadoc

1   package com.atlassian.gzipfilter.util;
2   
3   import com.atlassian.gzipfilter.flushable.FlushableGZIPOutputStream;
4   
5   import java.io.IOException;
6   import java.io.OutputStream;
7   import java.lang.reflect.Constructor;
8   import java.lang.reflect.InvocationTargetException;
9   import java.util.zip.GZIPOutputStream;
10  
11  /**
12   * Factory for creating flushable GZIP output streams. Easy in JDK7+, more difficult in earlier JDKs.
13   */
14  public class FlushableGZIPOutputStreamFactory
15  {
16      private static final Constructor JDK7_CONSTRUCTOR;
17      static
18      {
19          Constructor ctor = null;
20          try
21          {
22              ctor = GZIPOutputStream.class.getConstructor(OutputStream.class, Integer.TYPE, Boolean.TYPE);
23          }
24          catch (NoSuchMethodException e) {
25              // that's fine, we'll fall back
26          }
27          JDK7_CONSTRUCTOR = ctor;
28      }
29      public static GZIPOutputStream makeFlushableGZIPOutputStream(OutputStream out, int bufferSize) throws IOException
30      {
31          if (JDK7_CONSTRUCTOR == null)
32          {
33              return new FlushableGZIPOutputStream(out, bufferSize);
34          }
35          else
36          {
37              try {
38                  return (GZIPOutputStream) JDK7_CONSTRUCTOR.newInstance(out, bufferSize, true);
39              } catch (InstantiationException e) {
40                  throw new IOException(e);
41              } catch (IllegalAccessException e) {
42                  throw new IOException(e);
43              } catch (InvocationTargetException e) {
44                  throw new IOException(e);
45              }
46          }
47      }
48  }