01: package org.geotools.data.jdbc.collection;
02:
03: import java.sql.SQLException;
04: import java.sql.Statement;
05: import java.util.ArrayList;
06: import java.util.List;
07: import java.util.NoSuchElementException;
08:
09: import org.geotools.data.jdbc.PrimaryKey;
10: import org.geotools.feature.AttributeType;
11: import org.geotools.feature.Feature;
12: import org.geotools.feature.FeatureIterator;
13: import org.geotools.feature.FeatureType;
14: import org.geotools.feature.IllegalAttributeException;
15:
16: public class JDBCFeatureIterator implements FeatureIterator {
17:
18: /**
19: * sql statement
20: */
21: Statement st;
22: /**
23: * collection which the iterator originated from
24: */
25: JDBCFeatureCollection collection;
26:
27: public JDBCFeatureIterator(Statement st,
28: JDBCFeatureCollection collection) {
29: this .st = st;
30: this .collection = collection;
31: }
32:
33: public boolean hasNext() {
34: try {
35: return st.getResultSet().next();
36: } catch (SQLException e) {
37: throw new RuntimeException(e);
38: }
39: }
40:
41: public Feature next() throws NoSuchElementException {
42: FeatureType featureType = collection.getSchema();
43:
44: //round up attributes
45: List attributes = new ArrayList();
46: for (int i = 0; i < featureType.getAttributeCount(); i++) {
47: AttributeType type = featureType.getAttributeType(i);
48: try {
49: Object value = st.getResultSet().getObject(
50: type.getName());
51: if (value != null) {
52: attributes.add(value);
53: }
54: } catch (SQLException e) {
55: //log
56: attributes.add(null);
57: }
58: }
59:
60: //fid / primary key
61: PrimaryKey pkey = collection.getFeatureSource().getPrimaryKey();
62: String fid;
63: try {
64: fid = pkey.encode(st.getResultSet());
65: } catch (Exception e) {
66: throw new RuntimeException(
67: "Could not determine fid from primary key", e);
68: }
69:
70: //create the feature
71: try {
72: return featureType.create(attributes.toArray(), fid);
73: } catch (IllegalAttributeException e) {
74: throw new RuntimeException(e);
75: }
76: }
77:
78: public void close() {
79: if (st != null) {
80: try {
81: st.close();
82: } catch (SQLException e) {
83:
84: }
85: }
86: }
87:
88: }
|