aboutsummaryrefslogtreecommitdiff
path: root/examples/Translate.java
blob: 43ed82f756e549392c3778a9e277519b93d7e8ec (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
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * Translate, an Ivy java program sample.
 *
 * @author Yannick Jestin <jestin@cena.fr>
 * 
 * (c) CENA
 *
 * 1.2.6
 *  - goes apache jakarta regexp
 *
 */
import fr.dgac.ivy.* ;
import java.io.* ;
import org.apache.regexp.* ;

class Translate {

    private Ivy bus;

    Translate(String filename) throws IvyException {
      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 re = new RE("\"([^\"]*)\" \"([^\"]*)\"");
	while ( (s=in.readLine()) != null ) {
	  if (re.match(s)) {
	    System.out.println("binding " +re.getParen(1)+" and translating to " + re.getParen(2));
	    try {
	      bus.bindMsg(re.getParen(1),new TALK(re.getParen(2)));
	    } catch (IvyException ie) {
	      System.out.println(re.getParen(1)+" is not a valid PCRE regex");
	    }
	  }
	}
	in.close();
      } 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) {
	try {
	  bus.sendMsg(go);
	} catch (IvyException ie) {
	}
      }
    }

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

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