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