Handle errors and do not hard-code count
[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
11 /**
12  *
13  * @author jakub
14  */
15 public class AsyncConnection extends Connection {
16   private ResultSet lastResultSet;
17   ErrorHandler eh;
18   //make sure error is only handled once
19   boolean errorHandled = false;
20   ErrorHandler reh;
21   SearchHandler sh;
22   RecordHandler rh;
23   
24   public interface SearchHandler {
25     public void handle(ResultSet rs);
26   }
27   
28   public interface RecordHandler {
29     public void handle(Record r);
30   }
31   
32   public interface ErrorHandler {
33     public void handle(ZoomException e);
34   }
35
36   public AsyncConnection(String host, int port) {
37     super(host, port);
38     ZOOM_connection_option_set(zoomConnection, "async", "1");
39     closed = false;
40   }
41
42   @Override
43   public ResultSet search(Query query) throws ZoomException {
44     errorHandled = false;
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   public AsyncConnection onRecordError(ErrorHandler reh) {
65     this.reh = reh;
66     return this;
67   }
68   
69   //actuall handler, pkg-private
70   
71   void handleSearch() {
72     handleError();
73     //handle search
74     if (sh != null) sh.handle(lastResultSet);
75   }
76   
77   void handleRecord() {
78     //TODO clone the record to detach it from the result set
79     try {
80       if (rh != null) rh.handle(lastResultSet.getRecord(lastResultSet.asyncRecordOffset));
81     } catch (ZoomException ex) {
82       if (reh != null) reh.handle(ex);
83     } finally {
84       lastResultSet.asyncRecordOffset++;
85     }
86   }
87   
88   void handleError() {
89     //handle error
90     if (!errorHandled) {
91       ZoomException err = ExceptionUtil.getError(zoomConnection, host, port);
92       if (err != null) {
93         if (eh != null) {
94           eh.handle(err);
95           errorHandled = true;
96         }
97       }
98     }
99   }
100   
101 }