aboutsummaryrefslogtreecommitdiff
path: root/src/Probe.java
blob: bd37089506b55571439abc31a35df46f5ae41bc9 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/**
 * terminal implementation in java of the ivyprobe.
 *
 * @author	Yannick Jestin
 * @author	<a href="http://www.tls.cena.fr/products/ivy/">http://www.tls.cena.fr/products/ivy/</a>
 *
 * (c) CENA
 *
 * Changelog:
 * 1.2.3
 *   - now allows directMessages with the .direct command
 *   - the parseMsg is being rewritten with regexps
 *   - now handles the IVY_DEBUG property
 *   - now handles the -q quiet option
 *   - now handles the ^D ( end of input ) in a clean fashion
 *   - the constructor is public, you can embed a Probe in other programs
 * 1.2.2
 *   - changes setProperty to a backward-compatible construct
 *   - now uses the bus.domains(String domain) in order to display the domain
 *   list
 * 1.2.1
 *   - new -t switch to print the date for each ivy message
 *   - now displays the correct domain list
 *   - now has .bind and .unbind commands
 * 1.2.0
 *   - Probe can now send empty strings on keyboard input
 *   - rewritten with a looping thread on stdin to allow a cleaner exit on die
 *     message : not very good
 *   - processes .help, .die , .quit and .bye commands
 *   - it is possible to rename the JPROBE on the bus with the -n switch, it can
 *     circumvent name collisions during tests
 *     e.g: java fr.dgac.ivy.Probe -n JPROBE2
 * 1.0.10
 * 	exits on end of user input
 *	handles multiple domains - it was a IvyWatcher problem -
 */
package fr.dgac.ivy ;
import java.io.*;
import java.util.*;
import gnu.getopt.Getopt;
import gnu.regexp.*;

public class Probe implements IvyApplicationListener, IvyMessageListener, Runnable {

  public static final String helpCommands = "Available commands:\n.die CLIENTNAME sends a die message\n.direct CLIENTNAME ID MESSAGE sends the direct message to the client, with a message id set to the numerical ID\n.bye quits the application\n.quit idem\n.list lists the available clients\n.ping sends a ping request if IVY_PING is enabled\n.bind REGEXP binds to a regexp at runtime\n.unbind REGEXP unbinds to a regexp at runtime";

  public static final String helpmsg = "usage: java fr.dgac.ivy.Probe [options] [regexp]\n\t-b BUS\tspecifies the Ivy bus domain\n\t-n ivyname (default JPROBE)\n\t-q\tquiet, no tty output\n\t-d\tdebug\n\t-t\ttime stamp each message\n\t-h\thelp\n\n\t regexp is a Perl5 compatible regular expression";

  public static void main(String[] args) throws IvyException {
    Getopt opt = new Getopt("Probe",args,"n:b:dqht");
    int c;
    boolean timestamp=false;
    boolean quiet=false;
    String domain=Ivy.getDomain(null);
    String name="JPROBE";
    while ((c = opt.getopt()) != -1) switch (c) {
    case 'd':
      Properties sysProp = System.getProperties();
      sysProp.put("IVY_DEBUG","yes");
      break;
    case 'b': domain=opt.getOptarg(); break;
    case 'n': name=opt.getOptarg(); break;
    case 'q': quiet=true; break;
    case 't': timestamp=true; break;
    case 'h':
    default: System.out.println(helpmsg); System.exit(0);
    }
    Probe p = new Probe(new BufferedReader(new InputStreamReader(System.in)),timestamp,quiet,System.getProperty("IVY_DEBUG")!=null);
    p.setExitOnDie(true);
    Ivy bus=new Ivy(name,name+" ready",null);
    for (int i=opt.getOptind();i<args.length;i++) {
      if (!quiet) System.out.println("you want to subscribe to " + args[i]);
      bus.bindMsg(args[i],p);
    }
    if (!quiet) System.out.println(bus.domains(domain));
    bus.start(domain);
    p.start(bus);
  }

  private BufferedReader in;
  private volatile Thread looperThread;
  private Ivy bus;
  private boolean timestamp,quiet,debug,exitOnDie=false;
  private RE directMsgRE;


  public Probe(BufferedReader in, boolean timestamp,boolean quiet,boolean debug) {
    this.in=in;
    this.timestamp=timestamp;
    this.quiet=quiet;
    this.debug = debug;
    try {
      directMsgRE = new RE("^\\.direct ([^ ]*) ([0-9]+) (.*)");
    } catch (REException ree) {
      System.err.println("Regexp fatal error in the Probe program.");
      ree.printStackTrace();
      System.exit(0);
    }
  }

  public void start(Ivy bus) throws IvyException {
    if (looperThread!=null) throw new IvyException("Probe already started");
    this.bus=bus;
    bus.addApplicationListener(this);
    looperThread=new Thread(this);
    looperThread.start();
  }

  public void setExitOnDie(boolean b) { exitOnDie=b; }

  public void run() {
    traceDebug("Thread started");
    Thread thisThread=Thread.currentThread();
    String s;
    // "infinite" loop on keyboard input
    while (looperThread==thisThread) {
      try {
	s=in.readLine();
	if (s==null) break;
	parseCommand(s);
      } catch (NullPointerException e) {
	// EOF triggered by a ^D, for instance
	break;
      } catch (IOException e) {
	// System input was closed
	break;
      }
    }
    println("End of input. Good bye !");
    bus.stop();
    traceDebug("Probe Thread stopped");
  }

  void parseCommand(String s) throws IOException {
    REMatch result;
    traceDebug("parsing the ["+s+"] (length "+s.length()+") string");
    // crude parsing of the ".xyz" commands
    // TODO use regexps instends of String.lastIndexOf(String). Example
    // provided with .direct !
    if (s.length()==0) {
      println("-> Sent to " +bus.sendMsg(s)+" peers");
    } else if ((result=directMsgRE.getMatch(s))!=null) {
      String target = result.toString(1);
      int id = Integer.parseInt(result.toString(2));
      String message = result.toString(3);
      Vector v=bus.getIvyClientsByName(target);
      if (v.size()==0) println("no Ivy client with  the name \""+target+"\"");
      for (int i=0;i<v.size();i++) ((IvyClient)v.elementAt(i)).sendDirectMsg(id,message);
      return;
    } else if (s.lastIndexOf(".die ")>=0){
      String target=s.substring(5);
      Vector v=bus.getIvyClientsByName(target);
      if (v.size()==0) println("no Ivy client with  the name \""+target+"\"");
      for (int i=0;i<v.size();i++) ((IvyClient)v.elementAt(i)).sendDie();
    } else if (s.lastIndexOf(".unbind ")>=0){
      String regexp=s.substring(8);
      if (bus.unBindMsg(regexp)) {
        println("you want to unsubscribe to " + regexp);
      } else {
        println("you can't unsubscribe to " + regexp + ", your're not subscribed to it");
      }
    } else if (s.lastIndexOf(".bind ")>=0){
      String regexp=s.substring(6);
      println("you want to subscribe to " + regexp);
      bus.bindMsg(regexp,this);
    } else if (s.lastIndexOf(".ping ")>=0){
      String target=s.substring(6);
      Vector v=bus.getIvyClientsByName(target);
      if (v.size()==0) {
	println("no Ivy client with  the name \""+target+"\"");
      }
      for (int i=0;i<v.size();i++) {
	((IvyClient)v.elementAt(i)).sendPing("test");
      }
    } else if ( (s.lastIndexOf(".quit")>=0)||(s.lastIndexOf(".bye")>=0)){
      bus.stop();
      System.exit(0);
    } else if (s.lastIndexOf(".list")>=0) {
      Vector v = bus.getIvyClients();
      println(v.size()+" clients on the bus");
      for (int i=0;i<v.size();i++) {
	println("-> "+((IvyClient)v.elementAt(i)).getApplicationName());
      }
    } else if ( s.lastIndexOf(".help")>=0) {
      println(helpCommands);
    } else if ( s.charAt(0)=='.') {
      println("this command is not recognized");
      println(helpCommands);
    } else {
      println("-> Sent to " +bus.sendMsg(s)+" peers");
    }
  } // parseCommand

  public void connect(IvyClient client) {
    println(client.getApplicationName() + " connected " );
    for (java.util.Enumeration e=client.getRegexps();e.hasMoreElements();)
      println(client.getApplicationName() + " subscribes to " +e.nextElement() );
  }

  public void disconnect(IvyClient client) {
    println(client.getApplicationName() + " disconnected " );
  }

  public void die(IvyClient client, int id) {
    println("received die msg from " + client.getApplicationName() +" good bye");
    /* I cannot stop the readLine(), because it is native code */
    if (exitOnDie) System.exit(0);
  }

  public void directMessage(IvyClient client, int id, String arg) {
   println(client.getApplicationName() + " direct Message "+ id + arg );
  }

  public void receive(IvyClient client, String[] args) {
    String s=client.getApplicationName() + " sent";
    for (int i=0;i<args.length;i++) s+=" '"+args[i]+"'";
    println(s);
  }

  private void traceDebug(String s){ if (debug) System.out.println("-->Probe<-- "+s); }
  private void println(String s){ if (!quiet) System.out.println(date()+s); }
  private String date() {
    if (!timestamp) return "";
    Date d = new Date();
    java.text.DateFormat df = java.text.DateFormat.getTimeInstance();
    return "["+df.format(d)+"] ";
  }

}