Move async result cursor to AsyncConnection
[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 static org.yaz4j.jni.yaz4jlib.*;
10 import org.yaz4j.util.Unstable;
11
12 /**
13  *
14  * @author jakub
15  */
16 @Unstable
17 public class AsyncConnection extends Connection {
18   private ResultSet lastResultSet;
19   ErrorHandler eh;
20   //make sure error is only handled once
21   boolean errorHandled = false;
22   int handledRecordOffset = 0;
23   ErrorHandler reh;
24   SearchHandler sh;
25   RecordHandler rh;
26   
27   public interface SearchHandler {
28     public void handle(ResultSet rs);
29   }
30   
31   public interface RecordHandler {
32     public void handle(Record r);
33   }
34   
35   public interface ErrorHandler {
36     public void handle(ZoomException e);
37   }
38
39   public AsyncConnection(String host, int port) {
40     super(host, port);
41     ZOOM_connection_option_set(zoomConnection, "async", "1");
42     closed = false;
43   }
44
45   @Override
46   public ResultSet search(Query query) throws ZoomException {
47     errorHandled = false;
48     lastResultSet = super.search(query);
49     return null;
50   }
51   
52   public AsyncConnection onSearch(SearchHandler sh) {
53     this.sh = sh;
54     return this;
55   }
56   
57   public AsyncConnection onRecord(RecordHandler rh) {
58     this.rh = rh;
59     return this;
60   }
61   
62   public AsyncConnection onError(ErrorHandler eh) {
63     this.eh = eh;
64     return this;
65   }
66   
67   public AsyncConnection onRecordError(ErrorHandler reh) {
68     this.reh = reh;
69     return this;
70   }
71   
72   //actuall handler, pkg-private
73   
74   void handleSearch() {
75     handleError();
76     //handle search
77     if (sh != null) sh.handle(lastResultSet);
78   }
79   
80   void handleRecord() {
81     //TODO clone the record to detach it from the result set
82     try {
83       if (rh != null) rh.handle(lastResultSet.getRecord(handledRecordOffset));
84     } catch (ZoomException ex) {
85       if (reh != null) reh.handle(ex);
86     } finally {
87       handledRecordOffset++;
88     }
89   }
90   
91   void handleError() {
92     //handle error
93     if (!errorHandled) {
94       ZoomException err = ExceptionUtil.getError(zoomConnection, host, port);
95       if (err != null) {
96         if (eh != null) {
97           eh.handle(err);
98           errorHandled = true;
99         }
100       }
101     }
102   }
103   
104 }