001: package org.geotools.data.ogr;
002:
003: import java.io.IOException;
004: import java.util.NoSuchElementException;
005:
006: import org.gdal.ogr.DataSource;
007: import org.gdal.ogr.Layer;
008: import org.geotools.data.FeatureReader;
009: import org.geotools.feature.Feature;
010: import org.geotools.feature.FeatureType;
011: import org.geotools.feature.IllegalAttributeException;
012:
013: import com.vividsolutions.jts.geom.GeometryFactory;
014:
015: /**
016: * An OGR feature reader, reads data from the provided layer.<br>
017: * It assumes eventual filters have already been set on it, and will extract
018: * only the
019: *
020: * @author aaime
021: */
022: public class OGRFeatureReader implements FeatureReader {
023:
024: DataSource ds;
025:
026: Layer layer;
027:
028: FeatureType schema;
029:
030: org.gdal.ogr.Feature curr;
031:
032: private FeatureMapper mapper;
033:
034: boolean layerCompleted;
035:
036: public OGRFeatureReader(DataSource ds, Layer layer,
037: FeatureType schema) {
038: this .ds = ds;
039: this .layer = layer;
040: this .schema = schema;
041: this .layer.ResetReading();
042: this .layerCompleted = false;
043: // TODO: use the most appropriate Geometry Factory once the SPI system
044: // allows us to provide such an hint
045: this .mapper = new FeatureMapper(new GeometryFactory());
046: }
047:
048: public void close() throws IOException {
049: if (curr != null) {
050: curr.delete();
051: curr = null;
052: }
053: if (layer != null) {
054: layer.delete();
055: layer = null;
056: }
057: if (ds != null) {
058: ds.delete();
059: ds = null;
060: }
061: schema = null;
062: }
063:
064: protected void finalize() throws Throwable {
065: close();
066: }
067:
068: public FeatureType getFeatureType() {
069: return schema;
070: }
071:
072: public boolean hasNext() throws IOException {
073: // ugly, but necessary to close the reader when getting to the end, because
074: // it would break feature appending otherwise (the reader is used in feature
075: // writing too)
076: if (layerCompleted)
077: return false;
078:
079: if (curr != null)
080: return true;
081: boolean hasNext = (curr = layer.GetNextFeature()) != null;
082: if (!hasNext)
083: layerCompleted = true;
084: return hasNext;
085: }
086:
087: public Feature next() throws IOException,
088: IllegalAttributeException, NoSuchElementException {
089: if (!hasNext())
090: throw new NoSuchElementException(
091: "There are no more Features to be read");
092:
093: Feature f = mapper.convertOgrFeature(schema, curr);
094:
095: // .. nullify curr, so that we can move to the next one
096: curr.delete();
097: curr = null;
098:
099: return f;
100: }
101:
102: }
|