aboutsummaryrefslogtreecommitdiff
path: root/examples/Translate.java
blob: 738443cf7942165ecb50a0b566353234fbe5007c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Translate, an Ivy java program sample.
 *
 * @author Yannick Jestin <jestin@cena.fr>
 * 
 * (c) CENA
 *
 */
import fr.dgac.ivy.* ;
import java.io.* ;
import gnu.regexp.* ;

class Translate {

    private Ivy bus;

    Translate(String filename) {
      bus = new Ivy("Translater","Hello le monde",null);
      parseFile(filename);
      bus.bindMsg("^Bye$",new IvyMessageListener() {
	// callback for "Bye" message
	public void receive(IvyClient client, String[] args) {System.exit(0);}
      });
      try {
	// starts the bus on the default domain or IVY_DOMAIN property
	bus.start(null);
      } catch (IvyException ie) {
	System.err.println("can't run the Ivy bus" + ie.getMessage());
      }
    }

    private void parseFile(String filename) {
      try {
	BufferedReader in = new BufferedReader(new FileReader(new File(filename)));
	String s;
	RE regexp;
	regexp = new RE("\"([^\"]*)\" \"([^\"]*)\"");
	while ( (s=in.readLine()) != null ) {
	  REMatch result = regexp.getMatch(s);
	  bus.bindMsg(result.toString(1),new TALK(result.toString(2)));
	}
	in.close();
      } catch (REException ree) {
	System.out.println("regexp error");
	System.exit(-1);
      } catch (FileNotFoundException fnfe) {
	System.out.println("file "+filename+" not found. Good bye !");
	System.exit(-1);
      } catch (IOException ioe) {
	System.out.println("error reading "+filename+". Good bye !");
	System.exit(-1);
      }
    }

    private class TALK implements IvyMessageListener {
      private String go;
      TALK(String s) {go=s;}
      public void receive(IvyClient client, String[] args) {
	bus.sendMsg(go);
      }
    }

    public void receive(IvyClient client, String[] args) {
      bus.sendMsg("Bonjour"+((args.length>0)?args[0]:""));
    }

    public static void main(String args[]) { new Translate("translation.txt"); }
}