KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > file > transformers > FileToByteArray


1 /*
2  * $Id: FileToByteArray.java 3798 2006-11-04 04:07:14Z aperepel $
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 MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.file.transformers;
12
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.FileNotFoundException JavaDoc;
16 import java.io.IOException JavaDoc;
17
18 import org.apache.commons.io.IOUtils;
19 import org.apache.commons.lang.ArrayUtils;
20 import org.mule.transformers.AbstractTransformer;
21 import org.mule.umo.transformer.TransformerException;
22
23 /**
24  * <code>FileToByteArray</code> reads the contents of a file as a byte array.
25  */

26 public class FileToByteArray extends AbstractTransformer
27 {
28     /**
29      * Serial version
30      */

31     private static final long serialVersionUID = -2836878450595052607L;
32
33     public FileToByteArray()
34     {
35         registerSourceType(File JavaDoc.class);
36         setReturnClass(byte[].class);
37     }
38
39     public Object JavaDoc doTransform(Object JavaDoc src, String JavaDoc encoding) throws TransformerException
40     {
41         File JavaDoc file = (File JavaDoc)src;
42
43         if (file == null)
44         {
45             throw new TransformerException(this, new IllegalArgumentException JavaDoc("null file"));
46         }
47
48         if (!file.exists())
49         {
50             throw new TransformerException(this, new FileNotFoundException JavaDoc(file.getPath()));
51         }
52
53         if (file.length() == 0)
54         {
55             logger.warn("File is empty: " + file.getAbsolutePath());
56             return ArrayUtils.EMPTY_BYTE_ARRAY;
57         }
58
59         FileInputStream JavaDoc fis = null;
60         byte[] bytes = null;
61
62         try
63         {
64             fis = new FileInputStream JavaDoc(file);
65             // TODO Attention: arbitrary 4GB limit & also a great way to reap
66
// OOMs
67
int length = new Long JavaDoc(file.length()).intValue();
68             bytes = new byte[length];
69             fis.read(bytes);
70             return bytes;
71         }
72         // at least try..
73
catch (OutOfMemoryError JavaDoc oom)
74         {
75             throw new TransformerException(this, oom);
76         }
77         catch (IOException JavaDoc e)
78         {
79             throw new TransformerException(this, e);
80         }
81         finally
82         {
83             IOUtils.closeQuietly(fis);
84         }
85     }
86
87 }
88
Popular Tags