View Javadoc

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