Add connections accessor
[yaz4j-moved-to-github.git] / src / main / java / org / yaz4j / 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;
7
8 import java.util.ArrayList;
9 import java.util.List;
10 import org.yaz4j.jni.SWIGTYPE_p_p_ZOOM_connection_p;
11 import static org.yaz4j.jni.yaz4jlib.*;
12 import static java.lang.System.out;
13
14 /**
15  *
16  * @author jakub
17  */
18 public class AsyncConnections {
19   private List<AsyncConnection> conns = new ArrayList<AsyncConnection>();
20   
21   public void add(AsyncConnection conn) {
22     conns.add(conn);
23   }
24
25   public List<AsyncConnection> getConnections() {
26     return conns;
27   }
28   
29   public void start() {
30     SWIGTYPE_p_p_ZOOM_connection_p c_conns = new_zoomConnectionArray(conns.size());
31     try {
32       for (int i=0; i<conns.size(); i++) {
33         Connection conn = conns.get(i);
34         zoomConnectionArray_setitem(c_conns, i, conn.zoomConnection);
35       }
36       int ret = 0;
37       while ((ret = ZOOM_event(conns.size(), c_conns)) != 0) {
38         int idx = ret - 1;
39         int last = ZOOM_connection_last_event(zoomConnectionArray_getitem(c_conns, idx));
40         AsyncConnection conn = conns.get(idx);
41         String event = ZOOM_get_event_str(last);
42         out.println("Received event " + event + " on connection #"+idx);
43         switch (last) {
44           case ZOOM_EVENT_RECV_SEARCH: conn.handleSearch(); break;
45           case ZOOM_EVENT_RECV_RECORD: conn.handleRecord(); break;
46             //TODO this will make handle error twice
47           case ZOOM_EVENT_END: conn.handleError(); break;
48             //TODO should we simply handle error for any event?
49         }
50       }
51     } finally {
52       delete_zoomConnectionArray(c_conns);
53     }
54   }
55
56 }