View Javadoc

1   /*
2    * $Id: GZipCompressTransformer.java 11316 2008-03-11 15:50:38Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transformer.compression;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.util.IOUtils;
15  import org.mule.util.compression.GZipCompression;
16  
17  import java.io.IOException;
18  import java.io.InputStream;
19  import java.io.Serializable;
20  
21  import org.apache.commons.lang.SerializationUtils;
22  
23  /**
24   * <code>GZipCompressTransformer</code> is a transformer compressing objects into
25   * byte arrays.
26   */
27  public class GZipCompressTransformer extends AbstractCompressionTransformer
28  {
29  
30      public GZipCompressTransformer()
31      {
32          super();
33          this.setStrategy(new GZipCompression());
34          this.registerSourceType(Serializable.class);
35          this.registerSourceType(byte[].class);
36          this.registerSourceType(InputStream.class);
37          this.setReturnClass(byte[].class);
38      }
39  
40      public Object doTransform(Object src, String encoding) throws TransformerException
41      {
42          try
43          {
44              byte[] data = null;
45              if (src instanceof byte[])
46              {
47                  data = (byte[]) src;
48              }
49              else if (src instanceof InputStream)
50              {
51                  InputStream input = (InputStream)src;
52                  try
53                  {
54                      data = IOUtils.toByteArray(input);
55                  }
56                  finally
57                  {
58                      input.close();
59                  }
60              }
61              else
62              {
63                  data = SerializationUtils.serialize((Serializable) src);
64              }
65              return this.getStrategy().compressByteArray(data);
66          }
67          catch (IOException ioex)
68          {
69              throw new TransformerException(this, ioex);
70          }
71      }
72  
73  }