ScanSet is iterable
authorJakub Skoczen <jakub@indexdata.dk>
Tue, 1 Apr 2014 23:06:29 +0000 (01:06 +0200)
committerJakub Skoczen <jakub@indexdata.dk>
Tue, 1 Apr 2014 23:06:29 +0000 (01:06 +0200)
src/main/java/org/yaz4j/ScanSet.java
src/test/org/yaz4j/ConnectionTest.java

index 2ba8dd7..0df08a5 100644 (file)
@@ -1,18 +1,23 @@
 package org.yaz4j;
 
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import org.yaz4j.exception.ZoomException;
 import org.yaz4j.jni.SWIGTYPE_p_ZOOM_scanset_p;
 import org.yaz4j.jni.SWIGTYPE_p_size_t;
 import org.yaz4j.jni.yaz4jlib;
 
-public class ScanSet {
+public class ScanSet implements Iterable<ScanTerm> {
 
   //for GC ref-count
   private Connection conn;
   private SWIGTYPE_p_ZOOM_scanset_p scanSet;
   private boolean disposed = false;
+  private long size = 0;
 
   ScanSet(SWIGTYPE_p_ZOOM_scanset_p scanSet, Connection conn) {
     this.scanSet = scanSet;
+    size = yaz4jlib.ZOOM_scanset_size(scanSet);
     this.conn = conn;
   }
 
@@ -31,7 +36,7 @@ public class ScanSet {
   }
 
   public long getSize() {
-    return yaz4jlib.ZOOM_scanset_size(scanSet);
+    return size;
   }
 
   void _dispose() {
@@ -42,4 +47,25 @@ public class ScanSet {
       disposed = true;
     }
   }
+
+  @Override
+  public Iterator<ScanTerm> iterator() {
+    return new Iterator<ScanTerm>() {
+      private long cur;
+      @Override
+      public boolean hasNext() {
+        return cur < size;
+      }
+
+      @Override
+      public ScanTerm next() {
+        return get(cur++);
+      }
+
+      @Override
+      public void remove() {
+        throw new UnsupportedOperationException("remove operation not supported");
+      }
+    };
+  }
 }
index 56198f0..4459b30 100644 (file)
@@ -51,6 +51,39 @@ public class ConnectionTest {
       con.close();
     }
   }
+  
+   @Test
+  public void testConnectionScan() {
+    Connection con = new Connection("z3950.indexdata.dk:210/gils", 0);
+    assertNotNull(con);
+    try {
+      con.setSyntax("sutrs");
+      System.out.println("Open connection to z3950.indexdata.dk:210/gils...");
+      con.connect();
+      ScanSet s = con.scan(new PrefixQuery("@attr 1=4 utah"));
+      System.out.println("Scan for 'utah'...");
+      assertNotNull(s);
+      assertEquals(s.getSize(), 9);
+      ScanTerm rec = s.get(0);
+      assertNotNull(rec);
+      String term = rec.getTerm();
+      long occur = rec.getOccurences();
+      assertEquals("utah", term);
+      assertEquals(9, occur);
+      System.out.println("Read all scan terms..");
+      // read all records
+      int i = 0;
+      for (ScanTerm r : s) {
+        assertNotNull(r);
+        System.out.println("Got term "+r.getTerm());
+        i++;
+      }
+    } catch (ZoomException ze) {
+      fail(ze.getMessage());
+    } finally {
+      con.close();
+    }
+  }
 
   @Test
   public void testConnectionDeprecated() {