View Javadoc

1   /*
2    * $Id: FileToString.java 11561 2008-04-10 23:42:48Z dfeist $
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.transport.file.transformers;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.util.IOUtils;
15  
16  import java.io.File;
17  import java.io.InputStream;
18  import java.io.UnsupportedEncodingException;
19  
20  /**
21   * <code>FileToString</code> reads file contents into a string.
22   */
23  public class FileToString extends FileToByteArray
24  {
25  
26      public FileToString()
27      {
28          registerSourceType(File.class);
29          registerSourceType(InputStream.class);
30          registerSourceType(byte[].class);
31          setReturnClass(String.class);
32      }
33  
34      /**
35       * Simple implementation which relies on {@link FileToByteArray} to get a
36       * <code>byte[]</code> from the file beeing parsed and then transform it to a
37       * String with the correct encoding. If the encoding isn't supported simply throw
38       * an exception, good tranformation or no transformation at all. NOTE: if a
39       * <code>byte[]</code> is passed in as a source object this transformer accepts
40       * it and tries the usual transformation.
41       */
42      // @Override
43      public Object doTransform(Object src, String encoding) throws TransformerException
44      {
45          byte[] bytes;
46  
47          if (src instanceof InputStream)
48          {
49              bytes = IOUtils.toByteArray((InputStream) src);
50          }
51          else if (src instanceof byte[])
52          {
53              bytes = (byte[])src;
54          }
55          else
56          {
57              bytes = (byte[])super.doTransform(src, encoding);
58          }
59  
60          try
61          {
62              return new String(bytes, encoding);
63          }
64          catch (UnsupportedEncodingException uee)
65          {
66              throw new TransformerException(this, uee);
67          }
68      }
69  
70  }