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