Add documentation.
[yaz4j-moved-to-github.git] / src / main / java / org / yaz4j / async / AsyncConnections.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.async;
7
8 import java.util.ArrayList;
9 import java.util.List;
10 import org.yaz4j.Connection;
11 import org.yaz4j.jni.SWIGTYPE_p_p_ZOOM_connection_p;
12 import static org.yaz4j.jni.yaz4jlib.*;
13 import static java.lang.System.out;
14 import org.yaz4j.util.Unstable;
15
16 /**
17  * Allows to group and execute asynchronous connections within an event loop.
18  * 
19  * @author jakub
20  */
21 @Unstable
22 public class AsyncConnections {
23   private List<AsyncConnection> conns = new ArrayList<AsyncConnection>();
24   
25   /**
26    * Include async connection in the event loop processing.
27    * @param conn 
28    */
29   public void add(AsyncConnection conn) {
30     conns.add(conn);
31   }
32
33   /**
34    * List all included connections.
35    * @return 
36    */
37   public List<AsyncConnection> getConnections() {
38     return conns;
39   }
40   
41   /**
42    * Start the event loop, which effectively executes and processes all 
43    * async connections.
44    */
45   public void start() {
46     SWIGTYPE_p_p_ZOOM_connection_p c_conns = new_zoomConnectionArray(conns.size());
47     try {
48       for (int i=0; i<conns.size(); i++) {
49         AsyncConnection conn = conns.get(i);
50         zoomConnectionArray_setitem(c_conns, i, conn.getNativeConnection());
51       }
52       int ret = 0;
53       while ((ret = ZOOM_event(conns.size(), c_conns)) != 0) {
54         int idx = ret - 1;
55         int last = ZOOM_connection_last_event(zoomConnectionArray_getitem(c_conns, idx));
56         AsyncConnection conn = conns.get(idx);
57         String event = ZOOM_get_event_str(last);
58         out.println("Received event " + event + " on connection #"+idx);
59         switch (last) {
60           case ZOOM_EVENT_RECV_SEARCH: conn.handleSearch(); break;
61           case ZOOM_EVENT_RECV_RECORD: conn.handleRecord(); break;
62           case ZOOM_EVENT_END: conn.handleError(); break;
63         }
64       }
65     } finally {
66       delete_zoomConnectionArray(c_conns);
67     }
68   }
69
70 }