View Javadoc

1   /*
2    * $Id: GZipUncompressTransformer.java 21584 2011-03-18 12:17:31Z tcarlson $
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.config.i18n.MessageFactory;
15  import org.mule.transformer.types.DataTypeFactory;
16  import org.mule.util.IOUtils;
17  import org.mule.util.SerializationUtils;
18  import org.mule.util.compression.GZipCompression;
19  
20  import java.io.IOException;
21  import java.io.InputStream;
22  
23  /**
24   * <code>GZipCompressTransformer</code> will uncompress a byte[] or InputStream
25   */
26  public class GZipUncompressTransformer extends AbstractCompressionTransformer
27  {
28      public GZipUncompressTransformer()
29      {
30          super();
31          this.setStrategy(new GZipCompression());
32          this.registerSourceType(DataTypeFactory.BYTE_ARRAY);
33          this.registerSourceType(DataTypeFactory.INPUT_STREAM);
34          this.setReturnDataType(DataTypeFactory.BYTE_ARRAY);
35      }
36  
37      @Override
38      public Object doTransform(Object src, String outputEncoding) throws TransformerException
39      {
40          byte[] buffer;
41  
42          try
43          {
44              byte[] input = null;
45              if (src instanceof InputStream)
46              {
47                  InputStream inputStream = (InputStream) src;
48                  try
49                  {
50                      input = IOUtils.toByteArray(inputStream);
51                  }
52                  finally
53                  {
54                      inputStream.close();
55                  }
56              }
57              else
58              {
59                  input = (byte[]) src;
60              }
61  
62              buffer = getStrategy().uncompressByteArray(input);
63          }
64          catch (IOException e)
65          {
66              throw new TransformerException(
67                      MessageFactory.createStaticMessage("Failed to uncompress message."), this, e);
68          }
69  
70          if (!DataTypeFactory.BYTE_ARRAY.equals(getReturnDataType()))
71          {
72              return SerializationUtils.deserialize(buffer, muleContext);
73          }
74  
75          return buffer;
76      }
77  }