
import com.apple.dnssd.RegisterListener;
import com.apple.dnssd.DNSSDRegistration;
import com.apple.dnssd.DNSSDService;
import com.apple.dnssd.DNSSD;
import com.apple.dnssd.DNSSDException;
import com.apple.dnssd.BrowseListener;

public class RegistrationMonitor implements RegisterListener, BrowseListener {
  private Object greeter = null;
  private Class clss[] = {String.class};

  RegistrationMonitor() {
    try {
      greeter = Class.forName("Greeter").newInstance();

    } catch (ClassNotFoundException e) {
      System.out.println("You need to provide a class named Greeter " +
        "in a file named Greeter.java.");
      System.exit(0);
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }

  public void serviceRegistered(DNSSDRegistration dnssdRegistration,
                                int i, String s, String s1, String s2) {
    System.out.println("Roster:");
    try {
      DNSSD.browse("_example-rolecall._tcp", this);
    } catch (DNSSDException e) {
      System.err.println("couldn't browse");
    }
  }

  public void serviceFound(DNSSDService dnssdService, int i, int i1, String s, String s1, String s2) {
    Object serviceName[] = {s};
    try {
      Class.forName("Greeter").getMethod("serviceFound", clss).invoke(greeter, serviceName);
    } catch (ClassNotFoundException e) {
      //should never be called
    } catch (NoSuchMethodException e) {
      System.out.println("The Greeter class must contain the public method " +
        " named serviceFound return type void which takes a String as a parameter.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void serviceLost(DNSSDService dnssdService, int i, int i1, String s, String s1, String s2) {
    Object serviceName[] = {s};
    try {
      Class.forName("Greeter").getMethod("serviceLost", clss).invoke(greeter, serviceName);
    } catch (ClassNotFoundException e) {
      //should never be called
    } catch (NoSuchMethodException e) {
      System.out.println("The Greeter class must contain the public method " +
        " named serviceLost return type void which takes a String as a parameter.");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void operationFailed(DNSSDService dnssdService, int i) {
    System.err.println("Could not register service.");
  }
}