2 * Copyright (c) 1995-2015, Index Data
4 * See the file LICENSE for details.
6 package org.yaz4j.async;
8 import org.yaz4j.Connection;
9 import org.yaz4j.Query;
10 import org.yaz4j.Record;
11 import org.yaz4j.ResultSet;
12 import org.yaz4j.exception.ZoomException;
13 import org.yaz4j.jni.SWIGTYPE_p_ZOOM_connection_p;
14 import static org.yaz4j.jni.yaz4jlib.*;
15 import org.yaz4j.util.Unstable;
18 * Represents an asynchronous connection, all methods of this class
19 * (e.g connect, search) are non-blocking.
21 * Note that async support is missing for scan and extended services at this point.
26 public class AsyncConnection extends Connection {
27 private ResultSet lastResultSet;
29 //make sure error is only handled once
30 boolean errorHandled = false;
31 int handledRecordOffset = 0;
37 * Invoked immediately in response to the search request.
39 * Allows to read things the hit count and facets. Records should be read
40 * and processed in the record handler.
42 public interface SearchHandler {
43 public void handle(ResultSet rs);
47 * Invoked for every retrieved record.
49 public interface RecordHandler {
50 public void handle(Record r);
54 * Invoked for any protocol or connection level error.
56 public interface ErrorHandler {
57 public void handle(ZoomException e);
60 public AsyncConnection(String host, int port) {
62 ZOOM_connection_option_set(zoomConnection, "async", "1");
67 public ResultSet search(Query query) throws ZoomException {
69 lastResultSet = super.search(query);
74 * Register a hander for the search response.
75 * @param sh search response handler
78 public AsyncConnection onSearch(SearchHandler sh) {
84 * Register a handler for each retrieved record.
85 * @param rh record handler
88 public AsyncConnection onRecord(RecordHandler rh) {
94 * Register a handler for a connection level errors.
95 * @param eh error handler
98 public AsyncConnection onError(ErrorHandler eh) {
104 * Register a handler for record level errors (e.g decoding).
105 * @param reh record error handler
108 public AsyncConnection onRecordError(ErrorHandler reh) {
113 //actuall handler, pkg-private
115 void handleSearch() {
118 if (sh != null) sh.handle(lastResultSet);
121 void handleRecord() {
122 //TODO clone the record to detach it from the result set
124 if (rh != null) rh.handle(lastResultSet.getRecord(handledRecordOffset));
125 } catch (ZoomException ex) {
126 if (reh != null) reh.handle(ex);
128 handledRecordOffset++;
135 ZoomException err = getZoomException();
146 * Expose native connection to the async package, keep it package private.
148 SWIGTYPE_p_ZOOM_connection_p getNativeConnection() {
149 return zoomConnection;