Search in sources :

Example 1 with BasicFuture

use of org.eclipse.flux.client.util.BasicFuture in project flux by eclipse.

the class RabbitMQFluxClientTest method testChannelListener.

/**
	 * Use asynchronous connectToChannel and disconnectFromChannel together with channel listener
	 * to avoid race condition when sending / receiving messages.
	 */
public void testChannelListener() throws Exception {
    final String[] channels = { SUPER_USER, "Bob", "Alice" };
    final BasicFuture<Void> echoServiceReady = new BasicFuture<>();
    //resolves at end of callback spagetti sequence
    final BasicFuture<Void> theEnd = new BasicFuture<Void>();
    final Process<List<String>> root = new Process<List<String>>(SUPER_USER) {

        protected java.util.List<String> execute() throws Exception {
            final List<String> receivedMessages = new ArrayList<String>();
            echoServiceReady.get();
            conn.addMessageHandler(new MessageHandler("echoResponse") {

                @Override
                public void handle(String type, JSONObject message) {
                    try {
                        receivedMessages.add(message.getString("msg"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            conn.addChannelListener(new IChannelListener() {

                public void disconnected(String oldChannel) {
                    String newChannel = nextChannel(oldChannel);
                    if (newChannel != null) {
                        conn.connectToChannel(newChannel);
                    } else {
                        theEnd.resolve(null);
                    }
                }

                @Override
                public void connected(final String currentChannel) {
                    try {
                        send("echoRequest", new JSONObject().put(USERNAME, currentChannel).put("msg", "Hello on channel " + currentChannel));
                        //Give some time for response
                        setTimeout(500, new TimerTask() {

                            public void run() {
                                try {
                                    conn.disconnectFromChannel(currentChannel);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                private String nextChannel(String oldChannel) {
                    for (int i = 0; i < channels.length - 1; i++) {
                        if (channels[i].equals(oldChannel)) {
                            return channels[i + 1];
                        }
                    }
                    return null;
                }
            });
            conn.disconnectFromChannel(channels[0]);
            // must wait until callback spagetti finishes before allowing this process to terminate.
            theEnd.get();
            return receivedMessages;
        }
    };
    Process<Void> echoService = new Process<Void>(SUPER_USER) {

        protected Void execute() throws Exception {
            conn.addMessageHandler(new RequestResponseHandler(conn, "echoRequest") {
            });
            echoServiceReady.resolve(null);
            //once main process finished we can finish too
            await(root);
            return null;
        }

        ;
    };
    run(echoService, root);
    ArrayList<String> expected = new ArrayList<String>();
    for (int i = 1; i < channels.length; i++) {
        expected.add("Hello on channel " + channels[i]);
    }
    assertArrayEquals(expected.toArray(), root.result.get().toArray());
}
Also used : IChannelListener(org.eclipse.flux.client.IChannelListener) MessageHandler(org.eclipse.flux.client.MessageHandler) RequestResponseHandler(org.eclipse.flux.client.RequestResponseHandler) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) JSONObject(org.json.JSONObject) TimerTask(java.util.TimerTask) BasicFuture(org.eclipse.flux.client.util.BasicFuture) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with BasicFuture

use of org.eclipse.flux.client.util.BasicFuture in project flux by eclipse.

the class RabbitMQFluxClientTest method testRequestResponsePattern.

public void testRequestResponsePattern() throws Exception {
    final BasicFuture<Void> serviceStarted = new BasicFuture<Void>();
    final BasicFuture<Void> quitRequested = new BasicFuture<Void>();
    Process<Void> service = new Process<Void>(SUPER_USER) {

        protected Void execute() throws Exception {
            conn.addMessageHandler(new RequestResponseHandler(conn, "helloRequest") {

                @Override
                protected JSONObject fillResponse(String type, JSONObject req, JSONObject res) throws Exception {
                    String cmd = req.getString("cmd");
                    if ("quit".equals(cmd)) {
                        quitRequested.resolve(null);
                        // the message is sent.
                        return res.put("msg", "Quit request received from " + req.getString(USERNAME));
                    } else if ("greeting".equals(cmd)) {
                        return res.put("msg", "Hello " + req.getString(USERNAME));
                    } else {
                        throw new IllegalArgumentException("Unkown command: " + cmd);
                    }
                }
            });
            serviceStarted.resolve(null);
            //Wait for quit request
            return quitRequested.get();
        }
    };
    Process<Void> bob = new Process<Void>("Bob") {

        protected Void execute() throws Exception {
            //Bob has to wait for the service to be ready before sending requests to it!
            serviceStarted.get();
            try {
                assertEquals("Hello Bob", sendRequest("helloRequest", new JSONObject().put(USERNAME, "Bob").put("cmd", "greeting"), new ResponseHandler<String>() {

                    protected String handle(String messageType, JSONObject msg) throws Exception {
                        return msg.getString("msg");
                    }
                }));
                assertError("bogusCommand", asendRequest("helloRequest", new JSONObject().put(USERNAME, "Bob").put("cmd", "bogusCommand"), new ResponseHandler<String>() {

                    protected String handle(String messageType, JSONObject msg) throws Exception {
                        return msg.getString("msg");
                    }
                }));
            } finally {
                conn.send("helloRequest", new JSONObject().put(USERNAME, "Bob").put("cmd", "quit"));
            }
            return null;
        }
    };
    run(service, bob);
}
Also used : JSONObject(org.json.JSONObject) RequestResponseHandler(org.eclipse.flux.client.RequestResponseHandler) RequestResponseHandler(org.eclipse.flux.client.RequestResponseHandler) BasicFuture(org.eclipse.flux.client.util.BasicFuture) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with BasicFuture

use of org.eclipse.flux.client.util.BasicFuture in project flux by eclipse.

the class RabbitMQFluxClientTest method testChannelSwitchingMessageReception.

/**
	 * Test that super user can connect and disconnect channels to 
	 * switch between users.
	 * <p>
	 * This basic test only swtiches channels and verifies the 'isConnected' 
	 * state follows suite. It does not verify whether message delivery is
	 * changed according connected channels. 
	 */
public void testChannelSwitchingMessageReception() throws Exception {
    final String[] users = { "Bob", "Alice" };
    /**
		 * Resolves when the root process is connected to corresponding channel
		 */
    final List<BasicFuture<Void>> channelSynch = new ArrayList<BasicFuture<Void>>();
    for (final String user : users) {
        channelSynch.add(new BasicFuture<Void>());
        final Process<Void> userProcess = new Process<Void>(user) {

            protected Void execute() throws Exception {
                for (int i = 0; i < users.length; i++) {
                    String currentChannel = users[i];
                    //wait for root to switch to this channel.
                    channelSynch.get(i).get();
                    send("bork", new JSONObject().put(USERNAME, user).put("msg", user + " -> " + currentChannel));
                }
                return null;
            }

            ;
        };
        userProcess.start();
    }
    Process<List<String>> root = new Process<List<String>>(SUPER_USER) {

        protected List<String> execute() throws Exception {
            final List<String> receivedMessages = new ArrayList<String>();
            assertTrue(conn.isConnected(SUPER_USER));
            conn.disconnectFromChannelSync(SUPER_USER);
            assertFalse(conn.isConnected(SUPER_USER));
            conn.addMessageHandler(new MessageHandler("bork") {

                @Override
                public void handle(String type, JSONObject message) {
                    try {
                        receivedMessages.add(message.getString("msg"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            for (int i = 0; i < users.length; i++) {
                String currentChannel = users[i];
                if (i > 0) {
                    String previousChannel = users[i - 1];
                    System.out.println("Previous channel = " + previousChannel);
                    conn.disconnectFromChannelSync(previousChannel);
                }
                conn.connectToChannelSync(currentChannel);
                //Check channel connected state(s)
                for (String channel : users) {
                    boolean isConnected = conn.isConnected(channel);
                    assertEquals("[" + currentChannel + "] " + channel + " isConnected? " + isConnected, channel.equals(currentChannel), isConnected);
                }
                channelSynch.get(i).resolve(null);
                //Allow some time for user processes to send messages while root is connected to this channel.
                Thread.sleep(500);
            }
            return receivedMessages;
        }
    };
    run(root);
    List<String> results = root.result.get();
    String[] expectedMessages = new String[users.length];
    for (int i = 0; i < expectedMessages.length; i++) {
        expectedMessages[i] = users[i] + " -> " + users[i];
    }
    assertArrayEquals(expectedMessages, results.toArray());
}
Also used : MessageHandler(org.eclipse.flux.client.MessageHandler) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) JSONObject(org.json.JSONObject) BasicFuture(org.eclipse.flux.client.util.BasicFuture) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

TimeoutException (java.util.concurrent.TimeoutException)3 BasicFuture (org.eclipse.flux.client.util.BasicFuture)3 JSONObject (org.json.JSONObject)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 MessageHandler (org.eclipse.flux.client.MessageHandler)2 RequestResponseHandler (org.eclipse.flux.client.RequestResponseHandler)2 TimerTask (java.util.TimerTask)1 IChannelListener (org.eclipse.flux.client.IChannelListener)1