4. Your first Ivy application

We are going to write a "Hello world translater" for an Ivy bus. The application will subscribe to all messages starting with the "Hello" string, and re-emit them on the bus having translated "Hello" into "Bonjour" (Hello in french). In addition, the application will quit as soon as it receives a "Bye" message.

4.1. The code

Here is the code of "ivyTranslater.java":

import fr.dgac.ivy.* ;

class ivyTranslater implements IvyMessageListener {

  private Ivy bus;

  ivyTranslater() throws IvyException {
    // initialization, name and ready message
    bus = new Ivy("IvyTranslater","IvyTranslater Ready",null);
    // classical subscription
    bus.bindMsg("^Hello(.*)",this);
    // inner class subscription ( think awt )
    bus.bindMsg("^Bye$",new IvyMessageListener() {
      public void receive(IvyClient client, String[] args) {
	// leaves the bus, and as it is the only thread, quits
        bus.stop();
      }
    });
    bus.start(null); // starts the bus on the default domain
  }

  // callback associated to the "Hello" messages"
  public void receive(IvyClient client, String[] args) {
    try {
      bus.sendMsg("Bonjour"+((args.length>0)?args[0]:""));
    } catch (IvyException ie) {
      System.out.println("can't send my message on the bus");
    }
  }

  public static void main(String args[]) throws IvyException {
    new ivyTranslater();
  }
}

4.2. Compiling it

You should be able to compile the application with the following command (if the ivy-java jar is in your development classpath):

$ javac ivyTranslater.java
$

4.3. Testing

We are going to test our application with fr.dgac.ivy.Probe. In a shell, launch ivyTranslater:

$ java ivyTranslater
In another shell, launch java fr.dgac.ivy.Probe '(.*)'. You can see that the IvyTranslater has joined the bus, published its subscriptions, and sent the mandatory ready message. As your probe has subscribed to the eager regexp .* and reports the matched string within the brackets (.*), the ready message is printed.
$ java fr.dgac.ivy.Probe '(.*)'
you want to subscribe to (.*)
broadcasting on 127.255.255.255:2010
IvyTranslater connected
IvyTranslater subscribes to ^Bye$
IvyTranslater subscribes to ^Hello(.*)
IvyTranslater sent 'IvyTranslater Ready'
Probe is an interactive program. Type "Hello Paul", and you should receive "Bonjour Paul". Type "Bye", and the ivyTranslater application should quit to the shell. Just quit Probe, issuing a Control-D ( or .quit ) on a line, and Probe exists to the shell.
Hello Paul
-> Sent to 1 peers
IvyTranslater sent 'Bonjour Paul'
Bye
-> Sent to 1 peers
IvyTranslater disconnected
<Ctrl-D>
$