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.stream;
018    
019    import java.io.ByteArrayInputStream;
020    import java.io.IOException;
021    import java.io.InputStream;
022    
023    import javax.xml.transform.TransformerException;
024    import javax.xml.transform.stream.StreamSource;
025    
026    import org.apache.camel.Converter;
027    import org.apache.camel.converter.IOConverter;
028    import org.apache.camel.converter.jaxp.StringSource;
029    import org.apache.camel.converter.jaxp.XmlConverter;
030    
031    /**
032     * A set of {@link Converter} methods for wrapping stream-based messages in a {@link StreamCache} implementation to ensure message re-readability (e.g. multicasting, retrying, ...)  
033     */
034    @Converter
035    public class StreamCacheConverter {
036        
037        private XmlConverter converter = new XmlConverter();
038    
039        @Converter
040        public StreamCache convertToStreamCache(StreamSource source) throws TransformerException {
041            //TODO: we can probably build a more generic converter method to support other kinds of Sources as well (e.g. SAXSource, StAXSource, ...)
042            return new StreamSourceCache(converter.toString(source));
043        }
044        
045        @Converter
046        public StreamCache convertToStreamCache(InputStream stream) throws IOException {
047            return new InputStreamCache(IOConverter.toBytes(stream));
048        }
049    
050        private class StreamSourceCache extends StringSource implements StreamCache {
051            
052            private static final long serialVersionUID = 4147248494104812945L;
053    
054            public StreamSourceCache(String text) {
055                super(text);
056            }
057        }
058        
059        private class InputStreamCache extends ByteArrayInputStream implements StreamCache {
060         
061            public InputStreamCache(byte[] data) {
062                super(data);
063            }
064            
065        }
066    }