107a00fb232f5fe31b9a75377b46055043ee941e
[yaz4j-moved-to-github.git] / src / main / java / org / yaz4j / AsyncConnection.java
1 /*
2  * Copyright (c) 1995-2015, Index Data
3  * All rights reserved.
4  * See the file LICENSE for details.
5  */
6 package org.yaz4j;
7
8 import org.yaz4j.exception.ZoomException;
9 import org.yaz4j.jni.yaz4jlib;
10 import static org.yaz4j.jni.yaz4jlib.*;
11
12 /**
13  *
14  * @author jakub
15  */
16 public class AsyncConnection extends Connection {
17   private ResultSet lastResultSet;
18   ErrorHandler eh;
19   SearchHandler sh;
20   RecordHandler rh;
21   
22   public interface SearchHandler {
23     public void handle(ResultSet rs);
24   }
25   
26   public interface RecordHandler {
27     public void handle(Record r);
28   }
29   
30   public interface ErrorHandler {
31     public void handle(ZoomException e);
32   }
33
34   public AsyncConnection(String host, int port) {
35     super(host, port);
36     ZOOM_connection_option_set(zoomConnection, "async", "1");
37     //what about piggy back?
38     ZOOM_connection_option_set(zoomConnection, "count", "100");
39     ZOOM_connection_option_set(zoomConnection, "step", "20");
40     closed = false;
41   }
42
43   @Override
44   public ResultSet search(Query query) throws ZoomException {
45     lastResultSet = super.search(query);
46     return null;
47   }
48   
49   public AsyncConnection onSearch(SearchHandler sh) {
50     this.sh = sh;
51     return this;
52   }
53   
54   public AsyncConnection onRecord(RecordHandler rh) {
55     this.rh = rh;
56     return this;
57   }
58   
59   public AsyncConnection onError(ErrorHandler eh) {
60     this.eh = eh;
61     return this;
62   }
63   
64   //actuall handler, pkg-private
65   
66   void handleSearch() {
67     handleError();
68     //handle search
69     if (sh != null) sh.handle(lastResultSet);
70   }
71   
72   void handleRecord() {
73     try {
74       if (rh != null) rh.handle(lastResultSet.getRecord(lastResultSet.asyncRecordOffset));
75     } catch (ZoomException ex) {
76       if (eh != null) eh.handle(ex);
77     } finally {
78       lastResultSet.asyncRecordOffset++;
79     }
80   }
81   
82   void handleError() {
83     //handle error
84     ZoomException err = ExceptionUtil.getError(zoomConnection, host, port);
85     if (err != null) {
86       if (eh != null) eh.handle(err);
87     }
88   }
89   
90 }