001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.converter;
018    
019    import java.io.BufferedInputStream;
020    import java.io.BufferedOutputStream;
021    import java.io.BufferedReader;
022    import java.io.BufferedWriter;
023    import java.io.ByteArrayInputStream;
024    import java.io.ByteArrayOutputStream;
025    import java.io.File;
026    import java.io.FileInputStream;
027    import java.io.FileNotFoundException;
028    import java.io.FileOutputStream;
029    import java.io.FileReader;
030    import java.io.FileWriter;
031    import java.io.IOException;
032    import java.io.InputStream;
033    import java.io.InputStreamReader;
034    import java.io.ObjectInput;
035    import java.io.ObjectInputStream;
036    import java.io.ObjectOutput;
037    import java.io.ObjectOutputStream;
038    import java.io.OutputStream;
039    import java.io.OutputStreamWriter;
040    import java.io.Reader;
041    import java.io.StringReader;
042    import java.io.UnsupportedEncodingException;
043    import java.io.Writer;
044    import java.net.URL;
045    import java.util.Properties;
046    
047    import javax.xml.transform.OutputKeys;
048    import javax.xml.transform.Source;
049    import javax.xml.transform.Transformer;
050    import javax.xml.transform.TransformerException;
051    import javax.xml.transform.TransformerFactory;
052    import javax.xml.transform.dom.DOMSource;
053    import javax.xml.transform.stream.StreamResult;
054    
055    import org.apache.camel.Converter;
056    import org.apache.camel.Exchange;
057    import org.apache.camel.util.CollectionStringBuffer;
058    import org.apache.commons.logging.Log;
059    import org.apache.commons.logging.LogFactory;
060    
061    /**
062     * Some core java.io based <a
063     * href="http://activemq.apache.org/camel/type-converter.html">Type Converters</a>
064     *
065     * @version $Revision: 63649 $
066     */
067    @Converter
068    public final class IOConverter {
069        private static final transient Log LOG = LogFactory.getLog(IOConverter.class);
070    
071        /**
072         * Utility classes should not have a public constructor.
073         */
074        private IOConverter() {
075        }
076    
077        @Converter
078        public static InputStream toInputStream(URL url) throws IOException {
079            return url.openStream();
080        }
081    
082        @Converter
083        public static InputStream toInputStream(File file) throws FileNotFoundException {
084            return new BufferedInputStream(new FileInputStream(file));
085        }
086    
087        @Converter
088        public static BufferedReader toReader(File file) throws FileNotFoundException {
089            return new BufferedReader(new FileReader(file));
090        }
091    
092        @Converter
093        public static File toFile(String name) throws FileNotFoundException {
094            return new File(name);
095        }
096    
097        @Converter
098        public static OutputStream toOutputStream(File file) throws FileNotFoundException {
099            return new BufferedOutputStream(new FileOutputStream(file));
100        }
101    
102        @Converter
103        public static BufferedWriter toWriter(File file) throws IOException {
104            return new BufferedWriter(new FileWriter(file));
105        }
106    
107        @Converter
108        public static Reader toReader(InputStream in) throws FileNotFoundException {
109            return new InputStreamReader(in);
110        }
111    
112        @Converter
113        public static Writer toWriter(OutputStream out) throws FileNotFoundException {
114            return new OutputStreamWriter(out);
115        }
116    
117        @Converter
118        public static StringReader toReader(String text) {
119            return new StringReader(text);
120        }
121    
122        @Converter
123        public static InputStream toInputStream(String text) {
124            return toInputStream(text, null);
125        }
126        
127        @Converter
128        public static InputStream toInputStream(String text, Exchange exchange) {
129            if (exchange != null) {
130                String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
131                if (charsetName != null) {
132                    try {
133                        return toInputStream(text.getBytes(charsetName));
134                    } catch (UnsupportedEncodingException e) {
135                        LOG.warn("Can't convert the String into the bytes with the charset " + charsetName, e);
136                    }
137                }
138            }
139            return toInputStream(text.getBytes());
140        }
141        
142        @Converter
143        public static InputStream toInputStream(BufferedReader buffer) throws IOException {
144            return toInputStream(toString(buffer), null);
145        }
146    
147        @Converter
148        public static InputStream toInputStream(BufferedReader buffer, Exchange exchange) throws IOException {
149            return toInputStream(toString(buffer), exchange);
150        }
151    
152        @Converter
153        public static InputStream toInputStrean(DOMSource source) throws TransformerException, IOException {
154            ByteArrayInputStream bais = new ByteArrayInputStream(toString(source).getBytes());
155            return bais;
156        }
157    
158        @Converter
159        public static String toString(byte[] data, Exchange exchange) {
160            if (exchange != null) {
161                String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
162                if (charsetName != null) {
163                    try {
164                        return new String(data, charsetName);
165                    } catch (UnsupportedEncodingException e) {
166                        LOG.warn("Can't convert the byte to String with the charset " + charsetName, e);
167                    }
168                }
169            }
170            return new String(data);
171        }
172    
173    
174        @Converter
175        public static String toString(File file) throws IOException {
176            return toString(toReader(file));
177        }
178    
179        @Converter
180        public static byte[] toByteArray(File file) throws IOException {
181            return toBytes(toInputStream(file));
182        }
183    
184        @Converter
185        public static byte[] toByteArray(Reader reader) throws IOException {
186            if (reader instanceof BufferedReader) {
187                return toByteArray((BufferedReader)reader);
188            } else {
189                return toByteArray(new BufferedReader(reader));
190            }
191        }
192    
193        @Converter
194        public static String toString(URL url) throws IOException {
195            return toString(toInputStream(url));
196        }
197    
198        @Converter
199        public static String toString(Reader reader) throws IOException {
200            if (reader instanceof BufferedReader) {
201                return toString((BufferedReader)reader);
202            } else {
203                return toString(new BufferedReader(reader));
204            }
205        }
206    
207        @Converter
208        public static String toString(BufferedReader reader) throws IOException {
209            if (reader == null) {
210                return null;
211            }
212            try {
213                CollectionStringBuffer builder = new CollectionStringBuffer("\n");
214                while (true) {
215                    String line = reader.readLine();
216                    if (line == null) {
217                        return builder.toString();
218                    }
219                    builder.append(line);
220                }
221            } finally {
222                try {
223                    reader.close();
224                } catch (IOException e) {
225                    LOG.warn("Failed to close stream: " + e, e);
226                }
227            }
228        }
229    
230        @Converter
231        public static byte[] toByteArray(BufferedReader reader) throws IOException {
232            if (reader == null) {
233                return null;
234            }
235    
236            StringBuilder sb = new StringBuilder(1024);
237            char[] buf = new char[1024];
238            try {
239                int len = reader.read(buf);
240                if (len != -1) {
241                    sb.append(buf, 0, len);
242                }
243            } finally {
244                try {
245                    reader.close();
246                } catch (IOException e) {
247                    LOG.warn("Failed to close stream: " + e, e);
248                }
249            }
250            return sb.toString().getBytes();
251        }
252    
253        @Converter
254        public static String toString(InputStream in) throws IOException {
255            return toString(toReader(in));
256        }
257    
258        @Converter
259        public static String toString(Source source) throws TransformerException, IOException {
260            return toString(source, null);
261        }
262    
263        @Converter
264        public static InputStream toInputStream(byte[] data) {
265            return new ByteArrayInputStream(data);
266        }
267    
268        @Converter
269        public static ObjectOutput toObjectOutput(OutputStream stream) throws IOException {
270            if (stream instanceof ObjectOutput) {
271                return (ObjectOutput) stream;
272            } else {
273                return new ObjectOutputStream(stream);
274            }
275        }
276    
277        @Converter
278        public static ObjectInput toObjectInput(InputStream stream) throws IOException {
279            if (stream instanceof ObjectInput) {
280                return (ObjectInput) stream;
281            } else {
282                return new ObjectInputStream(stream);
283            }
284        }
285    
286        @Converter
287        public static byte[] toBytes(InputStream stream) throws IOException {
288            ByteArrayOutputStream bos = new ByteArrayOutputStream();
289            copy(stream, bos);
290            return bos.toByteArray();
291        }
292    
293        public static void copy(InputStream stream, OutputStream os) throws IOException {
294            byte[] data = new byte[4096];
295            int read = stream.read(data);        
296            while (read != -1) {            
297                os.write(data, 0, read);
298                read = stream.read(data);
299            }
300            os.flush();
301        }
302    
303        protected static String toString(Source source, Properties props) throws TransformerException, IOException {
304            ByteArrayOutputStream bos = new ByteArrayOutputStream();
305            try {
306                StreamResult sr = new StreamResult(bos);
307                Transformer trans = TransformerFactory.newInstance().newTransformer();
308                if (props == null) {
309                    props = new Properties();
310                    props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
311                }
312                trans.setOutputProperties(props);
313                trans.transform(source, sr);
314            } finally {
315                bos.close();
316            }
317            return bos.toString();
318        }
319    
320    }