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