Dennis Kao
2013-06-05 fc9880cd77a09dcfdea2791dee418f54f5721cf3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package com.ximple.io.dgn7;
 
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
 
import org.apache.log4j.Logger;
 
import oracle.jdbc.OracleConnection;
import oracle.sql.BLOB;
 
/**
 * Dgn7OracleReader
 * User: Ulysses
 * Date: 2007/10/24
 * Time:
 */
public class Dgn7OracleReader implements Iterator<Element> {
    private final static Logger logger = Logger.getLogger(Dgn7OracleReader.class);
 
    private String _sql;
    private String _fieldName;
    private Connection _connection;
    private ResultSet _resultSet;
    private static final int FETCHSIZE = 20;
    private Element _element;
 
    public Dgn7OracleReader(String sql, String fieldName, OracleConnection connection) {
        this._sql = sql;
        this._fieldName = fieldName;
        this._connection = connection;
    }
 
    public String getSql() {
        return _sql;
    }
 
    public void setSql(String sql) {
        this._sql = sql;
    }
 
    public String getFieldName() {
        return _fieldName;
    }
 
    public void setFieldName(String fieldName) {
        this._fieldName = fieldName;
    }
 
    public boolean hasNext() {
        if (_resultSet == null) {
            try {
                initializeReader();
            } catch (SQLException e) {
                throw new RuntimeException("initialize oralce error.", e);
            } catch (Dgn7Exception e) {
                throw new RuntimeException("initialize oralce error.", e);
            }
        }
        return _element != null;
    }
 
    public Element next() {
        Element result = _element;
 
        try {
            fetchElement();
        } catch (SQLException e) {
            throw new RuntimeException("Error:" + e.getMessage(), e);
        } catch (Dgn7Exception e) {
            throw new RuntimeException("Error:" + e.getMessage(), e);
        }
 
        return result;
    }
 
    public void remove() {
        throw new RuntimeException("Not Support this method.");
    }
 
    private boolean initializeReader() throws SQLException, Dgn7Exception {
        if (_resultSet != null) return true;
        Statement stmtSrc = _connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 
        stmtSrc.setFetchSize(FETCHSIZE);
        _resultSet = stmtSrc.executeQuery(_sql);
 
        fetchElement();
 
        return true;
    }
 
    private boolean fetchElement() throws SQLException, Dgn7Exception {
        if (_resultSet.next()) {
            byte[] raw = null;
            Object value = _resultSet.getObject(this._fieldName);
 
            if (value instanceof BLOB) {
                BLOB blob = (BLOB) value;
 
                try {
                    raw = getBytesFromBLOB(blob);
                } catch (IOException e) {
                    throw new Dgn7Exception("IOError", e);
                }
                // blob.close();
            } else if (value instanceof byte[]) {
                raw = (byte[]) value;
            }
            if (raw == null) {
                _element = null;
                return false;
            }
 
            ByteBuffer buffer = ByteBuffer.wrap(raw);
            buffer.order(ByteOrder.LITTLE_ENDIAN);
            short signature = buffer.getShort();
 
            // byte type = (byte) (buffer.get() & 0x7f);
            byte type = (byte) ((signature >>> 8) & 0x007f);
 
            // silly Bentley say contentLength is in 2-byte words
            // and ByteByffer uses bytes.
            // track the record location
            int elementLength = (buffer.getShort() * 2) + 4;
            ElementType recordType = ElementType.forID(type);
            IElementHandler handler = recordType.getElementHandler();
            _element = (Element) handler.read(buffer, signature, elementLength);
            if (recordType.isComplexElement() && (elementLength < raw.length)) {
                int offset = elementLength;
                while (offset < (raw.length - 4)) {
                    buffer.position(offset);
                    signature = buffer.getShort();
                    type = (byte) ((signature >>> 8) & 0x007f);
                    elementLength = (buffer.getShort() * 2) + 4;
                    if (raw.length < (offset + elementLength)) {
                        System.out.println("Length not match:" + offset + ":" + buffer.position() + ":" + buffer.limit());
                        break;
                    }
                    recordType = ElementType.forID(type);
                    handler = recordType.getElementHandler();
                    if (handler != null) {
                        Element subElement = (Element) handler.read(buffer, signature, elementLength);
                        ((ComplexElement) _element).add(subElement);
                        offset += elementLength;
                    } else {
                        byte[] remain = new byte[buffer.remaining()];
                        System.arraycopy(raw, offset, remain, 0, buffer.remaining());
                        for (int i = 0; i < remain.length; i++) {
                            if (remain[i] != 0) {
                                logger.info("fetch element has some error. index=" + (offset + i) + ":value=" + remain[i]);
                                System.out.println("fetch element has some error. index=" + (offset + i) + ":value=" + remain[i]);
                            }
                        }
                        break;
                    }
                }
            }
 
        } else {
            _element = null;
            return false;
        }
        return true;
    }
 
    protected byte[] getBytesFromBLOB(BLOB blob) throws SQLException, IOException {
        byte[] raw;
 
        // BLOB        blob        = (BLOB) rs.getBlob(1);
        int optimalSize = blob.getChunkSize();
        byte[] chunk = new byte[optimalSize];
        InputStream is = blob.getBinaryStream(0);
        ByteBuffer buffer = null;    // ByteBuffer.allocate(optimalSize);
        int len;
 
        try {
            while ((len = (is.read(chunk))) != -1) {
                if (buffer != null) {
                    buffer.limit(buffer.limit() + len);
                } else {
                    buffer = ByteBuffer.allocate(len);
                }
 
                buffer.put(chunk);
            }
 
            assert buffer != null;
            buffer.position(0);
            raw = buffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                logger.warn("InputStream cannot close", e);
            }
            ;
        }
 
        return raw;
    }
}