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: 51083 $
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.getBytes());
125        }
126    
127        @Converter
128        public static InputStream toInputStream(BufferedReader buffer) throws IOException {
129            return toInputStream(toString(buffer));
130        }
131    
132        @Converter
133        public static InputStream toInputStrean(DOMSource source) throws TransformerException, IOException {
134            ByteArrayInputStream bais = new ByteArrayInputStream(toString(source).getBytes());
135            return bais;
136        }
137    
138        @Converter
139        public static String toString(byte[] data, Exchange exchange) {
140            if (exchange != null) {
141                String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
142                if (charsetName != null) {
143                    try {
144                        return new String(data, charsetName);
145                    } catch (UnsupportedEncodingException e) {
146                        LOG.warn("Can't convert the byte to String with the charset " + charsetName, e);
147                    }
148                }
149            }
150            return new String(data);
151        }
152    
153    
154        @Converter
155        public static String toString(File file) throws IOException {
156            return toString(toReader(file));
157        }
158    
159        @Converter
160        public static byte[] toByteArray(File file) throws IOException {
161            return toBytes(toInputStream(file));
162        }
163    
164        @Converter
165        public static byte[] toByteArray(Reader reader) throws IOException {
166            if (reader instanceof BufferedReader) {
167                return toByteArray((BufferedReader)reader);
168            } else {
169                return toByteArray(new BufferedReader(reader));
170            }
171        }
172    
173        @Converter
174        public static String toString(URL url) throws IOException {
175            return toString(toInputStream(url));
176        }
177    
178        @Converter
179        public static String toString(Reader reader) throws IOException {
180            if (reader instanceof BufferedReader) {
181                return toString((BufferedReader)reader);
182            } else {
183                return toString(new BufferedReader(reader));
184            }
185        }
186    
187        @Converter
188        public static String toString(BufferedReader reader) throws IOException {
189            if (reader == null) {
190                return null;
191            }
192            try {
193                CollectionStringBuffer builder = new CollectionStringBuffer("\n");
194                while (true) {
195                    String line = reader.readLine();
196                    if (line == null) {
197                        return builder.toString();
198                    }
199                    builder.append(line);
200                }
201            } finally {
202                try {
203                    reader.close();
204                } catch (IOException e) {
205                    LOG.warn("Failed to close stream: " + e, e);
206                }
207            }
208        }
209    
210        @Converter
211        public static byte[] toByteArray(BufferedReader reader) throws IOException {
212            if (reader == null) {
213                return null;
214            }
215    
216            StringBuilder sb = new StringBuilder(1024);
217            char[] buf = new char[1024];
218            try {
219                int len = reader.read(buf);
220                if (len != -1) {
221                    sb.append(buf, 0, len);
222                }
223            } finally {
224                try {
225                    reader.close();
226                } catch (IOException e) {
227                    LOG.warn("Failed to close stream: " + e, e);
228                }
229            }
230            return sb.toString().getBytes();
231        }
232    
233        @Converter
234        public static String toString(InputStream in) throws IOException {
235            return toString(toReader(in));
236        }
237    
238        @Converter
239        public static String toString(Source source) throws TransformerException, IOException {
240            return toString(source, null);
241        }
242    
243        @Converter
244        public static InputStream toInputStream(byte[] data) {
245            return new ByteArrayInputStream(data);
246        }
247    
248        @Converter
249        public static ObjectOutput toObjectOutput(OutputStream stream) throws IOException {
250            if (stream instanceof ObjectOutput) {
251                return (ObjectOutput) stream;
252            } else {
253                return new ObjectOutputStream(stream);
254            }
255        }
256    
257        @Converter
258        public static ObjectInput toObjectInput(InputStream stream) throws IOException {
259            if (stream instanceof ObjectInput) {
260                return (ObjectInput) stream;
261            } else {
262                return new ObjectInputStream(stream);
263            }
264        }
265    
266        @Converter
267        public static byte[] toBytes(InputStream stream) throws IOException {
268            ByteArrayOutputStream bos = new ByteArrayOutputStream();
269            copy(stream, bos);
270            return bos.toByteArray();
271        }
272    
273        protected static void copy(InputStream stream, ByteArrayOutputStream bos) throws IOException {
274            byte[] data = new byte[4096];
275            int read = stream.read(data);
276            while (read != -1) {
277                bos.write(data, 0, read);
278                read = stream.read(data);
279            }
280            bos.flush();
281        }
282    
283        protected static String toString(Source source, Properties props) throws TransformerException, IOException {
284            ByteArrayOutputStream bos = new ByteArrayOutputStream();
285            try {
286                StreamResult sr = new StreamResult(bos);
287                Transformer trans = TransformerFactory.newInstance().newTransformer();
288                if (props == null) {
289                    props = new Properties();
290                    props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
291                }
292                trans.setOutputProperties(props);
293                trans.transform(source, sr);
294            } finally {
295                bos.close();
296            }
297            return bos.toString();
298        }
299    
300    }