001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: XMLDocumentInputStream.java 162 2011-10-24 20:42:37Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.jibx;
009    
010    import java.io.BufferedInputStream;
011    import java.io.IOException;
012    import java.io.InputStream;
013    
014    import org.dellroad.stuff.io.InputStreamReader;
015    import org.jibx.runtime.JiBXException;
016    
017    /**
018     * {@link InputStream} over which XML documents are passed. This class is a companion to {@link XMLDocumentOutputStream}.
019     *
020     * <p>
021     * XML documents are converted into Java objects via {@link JiBXUtil#readObject(Class, InputStream) JiBXUtil.readObject()}.
022     * </p>
023     *
024     * <p>
025     * Instances of this class are thread-safe.
026     * </p>
027     *
028     * @param <T> XML document type
029     * @see XMLDocumentOutputStream
030     */
031    public class XMLDocumentInputStream<T> {
032    
033        private final Class<T> type;
034        private final InputStreamReader input;
035    
036        /**
037         * Constructor.
038         *
039         * @param type Java type for XML documents
040         * @param input data source
041         */
042        public XMLDocumentInputStream(Class<T> type, InputStream input) {
043            if (type == null)
044                throw new IllegalArgumentException("null type");
045            if (input == null)
046                throw new IllegalArgumentException("null input");
047            this.type = type;
048            this.input = new InputStreamReader(new BufferedInputStream(input));
049        }
050    
051        /**
052         * Read the next XML document, parsed and objectified.
053         *
054         * @return decoded object or {@code null} on EOF
055         */
056        public T read() throws IOException, JiBXException {
057            InputStream xml = this.input.read();
058            if (xml == null)
059                return null;
060            try {
061                return JiBXUtil.readObject(this.type, xml);
062            } finally {
063                try {
064                    xml.close();
065                } catch (IOException e) {
066                    // ignore
067                }
068            }
069        }
070    
071        public void close() throws IOException {
072            this.input.close();
073        }
074    }
075