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