OW2 Consortium ops

Rev

Rev 5 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 ebruchez 1
/**
2
 *  Copyright (C) 2004 Orbeon, Inc.
3
 *
4
 *  This program is free software; you can redistribute it and/or modify it under the terms of the
5
 *  GNU Lesser General Public License as published by the Free Software Foundation; either version
6
 *  2.1 of the License, or (at your option) any later version.
7
 *
8
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 *  See the GNU Lesser General Public License for more details.
11
 *
12
 *  The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
13
 */
14
package org.orbeon.oxf.util;
15
 
16
import org.orbeon.oxf.common.OXFException;
17
 
18
import java.io.IOException;
19
import java.io.Reader;
20
import java.util.Iterator;
21
 
22
public class SequenceReader extends Reader {
23
    private Iterator iterator;
24
    private Reader reader;
25
 
26
    public SequenceReader(Iterator iterator) {
27
        this.iterator = iterator;
28
        try {
29
            nextReader();
30
        } catch (IOException ex) {
31
            throw new OXFException("Invalid state");
32
        }
33
    }
34
 
35
    public int read() throws IOException {
36
        if (reader == null)
37
            return -1;
38
 
39
        int c = reader.read();
40
        if (c == -1) {
41
            nextReader();
42
            return read();
43
        }
44
        return c;
45
    }
46
 
47
    public int read(char b[], int off, int len) throws IOException {
48
        if (reader == null) {
49
            return -1;
50
        } else if (b == null) {
51
            throw new NullPointerException();
52
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
53
                ((off + len) > b.length) || ((off + len) < 0)) {
54
            throw new IndexOutOfBoundsException();
55
        } else if (len == 0) {
56
            return 0;
57
        }
58
 
59
        int n = reader.read(b, off, len);
60
        if (n <= 0) {
61
            nextReader();
62
            return read(b, off, len);
63
        }
64
        return n;
65
    }
66
 
67
    public void close() throws IOException {
68
        do {
69
            nextReader();
70
        } while (reader != null);
71
    }
72
 
73
    void nextReader() throws IOException {
74
        if (reader != null)
75
            reader.close();
76
 
77
        if (iterator.hasNext()) {
78
            reader = (Reader) iterator.next();
79
            if (reader == null)
80
                throw new OXFException("Null reader passed to " + getClass().getName());
81
        } else
82
            reader = null;
83
    }
84
}