Listening for events |
For an object to listen for events published by the Rexec instance the following steps are required:
1. Set object to implement BsdListener or extend BsdAdapter class. 2. Overload event handling methods. 3. Subscribe object to receive events published by Rexec instance.
The BsdListener class is a pure interface and can be used in cases where the class you defined to listen for events already extends another class type. The BsdAdapter class implements the BsdListener interface and can be used in cases where there is no need for class inheritance.
Note
Unless your class requires inheritance it is generally easier to use the BsdAdapter class as it provides default implementations for all the event handler methods defined in the BsdListener interface. This allows you to overload only the event handler methods that you are interested in.
Example
The example below demonstrates using the BsdListener class.
import com.jscape.inet.bsd.*;
public class MyBsdListener implements BsdListener {
public void connected(BsdConnectedEvent event) { System.out.println("Connected to host: " + event.getHostname()); }
public void disconnected(BsdDisconnectedEvent event) { System.out.println("Disconnected from host: " + event.getHostname()); }
public void bytesTransmitted(BsdBytesTransmittedEvent event) { // process event }
public void bytesReceived(BsdBytesReceivedEvent event) { // process event }
public static void main(String[] args) { try { // creates new Rexec instance Rexec rexec = new Rexec("server.com", "jsmith", "secret", "ls -al", false);
// add listener rexec.addBsdListener(new MyBsdListener());
// establish connection rexec.connect();
// executes ls -al command on server.com authenticating as user jsmith rexec.execute();
// disconnect rexec.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
}
Example
The following example demonstrates using the BsdAdapter class
import com.jscape.inet.bsd.*;
public class MyBsdAdapter extends BsdAdapter {
public void connected(BsdConnectedEvent event) { System.out.println("Connected to host: " + event.getHostname()); }
public void disconnected(BsdDisconnectedEvent event) { System.out.println("Disconnected from host: " + event.getHostname()); }
public static void main(String[] args) { try { // creates new Rexec instance Rexec rexec = new Rexec("server.com", "jsmith", "secret", "ls -al", false);
// add listener rexec.addBsdListener(new MyBsdListener());
// establish connection rexec.connect();
// executes ls -al command on server.com authenticating as user jsmith rexec.execute();
// disconnect rexec.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }
|