View Javadoc

1   /*
2    * $Id: GZipCompressTransformer.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.transformer.types.DataTypeFactory;
15  import org.mule.util.IOUtils;
16  import org.mule.util.compression.GZipCompression;
17  
18  import java.io.IOException;
19  import java.io.InputStream;
20  import java.io.Serializable;
21  
22  import org.apache.commons.lang.SerializationUtils;
23  
24  /**
25   * <code>GZipCompressTransformer</code> is a transformer compressing objects into
26   * byte arrays.
27   */
28  public class GZipCompressTransformer extends AbstractCompressionTransformer
29  {
30      public GZipCompressTransformer()
31      {
32          super();
33          this.setStrategy(new GZipCompression());
34          this.registerSourceType(DataTypeFactory.create(Serializable.class));
35          this.registerSourceType(DataTypeFactory.BYTE_ARRAY);
36          this.registerSourceType(DataTypeFactory.INPUT_STREAM);
37          this.setReturnDataType(DataTypeFactory.BYTE_ARRAY);
38      }
39  
40      @Override
41      public Object doTransform(Object src, String outputEncoding) throws TransformerException
42      {
43          try
44          {
45              byte[] data = null;
46              if (src instanceof byte[])
47              {
48                  data = (byte[]) src;
49              }
50              else if (src instanceof InputStream)
51              {
52                  InputStream input = (InputStream)src;
53                  try
54                  {
55                      data = IOUtils.toByteArray(input);
56                  }
57                  finally
58                  {
59                      input.close();
60                  }
61              }
62              else
63              {
64                  data = SerializationUtils.serialize((Serializable) src);
65              }
66              return this.getStrategy().compressByteArray(data);
67          }
68          catch (IOException ioex)
69          {
70              throw new TransformerException(this, ioex);
71          }
72      }
73  }