001: /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
002: * This code is licensed under the GPL 2.0 license, availible at the root
003: * application directory.
004: */
005: package org.geoserver.wfsv.response.v1_1_0;
006:
007: import org.geotools.data.postgis.FeatureDiffReader;
008: import java.io.IOException;
009: import java.util.AbstractCollection;
010: import java.util.Iterator;
011: import java.util.logging.Level;
012: import java.util.logging.Logger;
013:
014: /**
015: * To really wrap a FeatureDiffReader into a freemarker template, we have to
016: * wrap it into a collection. This allows the reader to be scrolled over without
017: * the need to copy it memory.
018: *
019: * @author Andrea Aime - TOPP
020: *
021: */
022: public class FeatureDiffCollection extends AbstractCollection {
023: static Logger LOGGER = org.geotools.util.logging.Logging
024: .getLogger("org.geoserver.wfs");
025: private FeatureDiffReader reader;
026:
027: public FeatureDiffCollection(FeatureDiffReader reader) {
028: this .reader = reader;
029: }
030:
031: public Iterator iterator() {
032: try {
033: return new FeatureDiffReaderIterator(new FeatureDiffReader(
034: reader));
035: } catch (Exception e) {
036: close(reader);
037: throw new RuntimeException(e);
038: }
039: }
040:
041: public int size() {
042: FeatureDiffReader clone = null;
043:
044: try {
045: clone = new FeatureDiffReader(reader);
046:
047: int size = 0;
048:
049: while (clone.hasNext())
050: size++;
051:
052: return size;
053: } catch (Exception e) {
054: close(reader);
055: throw new RuntimeException(e);
056: } finally {
057: if (clone != null) {
058: close(clone);
059: }
060: }
061: }
062:
063: private void close(FeatureDiffReader r) {
064: try {
065: r.close();
066: r = null;
067: } catch (Exception e) {
068: LOGGER.log(Level.SEVERE,
069: "Error closing diff reader wrapping iterator", e);
070: }
071: }
072:
073: private static class FeatureDiffReaderIterator implements Iterator {
074: private FeatureDiffReader reader;
075:
076: public FeatureDiffReaderIterator(FeatureDiffReader reader) {
077: this .reader = reader;
078: }
079:
080: public boolean hasNext() {
081: try {
082: boolean hasNext = reader.hasNext();
083:
084: if (!hasNext) {
085: close();
086: }
087:
088: return hasNext;
089: } catch (IOException e) {
090: close();
091: throw new RuntimeException(e);
092: }
093: }
094:
095: private void close() {
096: try {
097: reader.close();
098: reader = null;
099: } catch (Exception e) {
100: LOGGER.log(Level.SEVERE,
101: "Error closing diff reader wrapping iterator",
102: e);
103: }
104: }
105:
106: public Object next() {
107: try {
108: return reader.next();
109: } catch (Exception e) {
110: close();
111: throw new RuntimeException(e);
112: }
113: }
114:
115: public void remove() {
116: throw new UnsupportedOperationException(
117: "Feature diffs are read only");
118: }
119: }
120: }
|