View Javadoc

1   /*
2    * $Id: FileToByteArray.java 10489 2008-01-23 17:53:38Z 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.transformer.AbstractTransformer;
15  import org.mule.util.ArrayUtils;
16  
17  import java.io.File;
18  import java.io.FileInputStream;
19  import java.io.FileNotFoundException;
20  import java.io.IOException;
21  
22  import org.apache.commons.io.IOUtils;
23  
24  /**
25   * <code>FileToByteArray</code> reads the contents of a file as a byte array.
26   */
27  public class FileToByteArray extends AbstractTransformer
28  {
29  
30      public FileToByteArray()
31      {
32          registerSourceType(File.class);
33          setReturnClass(byte[].class);
34      }
35  
36      public Object doTransform(Object src, String encoding) throws TransformerException
37      {
38          File file = (File)src;
39  
40          if (file == null)
41          {
42              throw new TransformerException(this, new IllegalArgumentException("null file"));
43          }
44  
45          if (!file.exists())
46          {
47              throw new TransformerException(this, new FileNotFoundException(file.getPath()));
48          }
49  
50          if (file.length() == 0)
51          {
52              logger.warn("File is empty: " + file.getAbsolutePath());
53              return ArrayUtils.EMPTY_BYTE_ARRAY;
54          }
55  
56          FileInputStream fis = null;
57          byte[] bytes = null;
58  
59          try
60          {
61              fis = new FileInputStream(file);
62              // TODO Attention: arbitrary 4GB limit & also a great way to reap
63              // OOMs
64              int length = new Long(file.length()).intValue();
65              bytes = new byte[length];
66              fis.read(bytes);
67              return bytes;
68          }
69          // at least try..
70          catch (OutOfMemoryError oom)
71          {
72              throw new TransformerException(this, oom);
73          }
74          catch (IOException e)
75          {
76              throw new TransformerException(this, e);
77          }
78          finally
79          {
80              IOUtils.closeQuietly(fis);
81          }
82      }
83  
84  }