O'Reilly logo

JXTA in a Nutshell by Li Gong, Bernard Traversat, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Application Implementation

That completes our look at the RestoPeer implementation; we now have a service that can discover (and create, if necessary) the RestoNet peergroup. Now we’ll turn our attention to the HungryPeer class.

The HungryPeer class represents an individual that is looking to eat at a restaurant. The implementation in this chapter illustrates how a peer can search for and join a peergroup: the HungryPeer class discovers and joins the RestoNet peergroup created by the previous RestoPeer class:

import java.io.*;
import java.util.Enumeration;
import java.util.Vector;

import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.exception.PeerGroupException;
import net.jxta.document.Advertisement;
import net.jxta.discovery.DiscoveryService;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PeerGroupAdvertisement;

// HungryPeer tries to find a restaurant to get a good meal. It finds all
// RestoPeers in the RestoNet peergroup and (in later examples) requests
// bids from them.

public class HungryPeer {

    private PeerGroup netpg = null;     // NetPeerGroup
    private PeerGroup restoNet = null;  // Resto peergroup
    private int timeout = 3000;         // Time-out; can be adjusted

    // Services within the RestoNet peergroup
    private DiscoveryService disco;     // Discovery service
    private PipeService pipes;          // Pipe service

    // Vector of discovered RestoPeers
    private Vector restaurantAdvs = new Vector(  );

    public static void main(String args[]) {
        HungryPeer myapp = new HungryPeer(  );
        myapp.startJxta(  );
        System.exit(0);
    }

    // Start the JXTA application
    private void startJxta(  ) {
        try {
            // Discover (or create) and join
            // the default JXTA NetPeerGroup
            netpg = PeerGroupFactory.newNetPeerGroup(  );
        } catch (PeerGroupException e) {
            // Couldn't initialize; can't continue
            System.out.println(
                "Fatal error : creating the net PeerGroup");
            System.exit(1);
        }

        // Discover and join the RestoNet peergroup
        // HungryPeers never create the RestoNet peergroup
        try {
            if (!joinRestoNet(  )) {
                System.out.println(
                       "Sorry could not find the RestoNet Peergroup");
                System.exit(2);
            }
        } catch (Exception e) {
            System.out.println("Can't join RestoNet group");
            System.exit(1);
        }
    }

    // This method is used to discover the RestoNet peergroup
    // If found, the peer will join the peergroup

    private boolean joinRestoNet(  ) {

        int count = 3; // Maximum number of attempts to discover

        System.out.println(
            "Attempting to discover the RestoNet Peergroup");

        // Get the discovery service handle from the NetPeerGroup
        DiscoveryService hdisco = netpg.getDiscoveryService(  );

        // All discovered RestoNet peers
        Enumeration ae = null;

        // Loop until we find the RestoNet peergroup advertisement
        // or we've exhausted the desired number of attempts
        while (count-- > 0) {
            try {
                // Check if we have the advertisement in the local
                // peer cache
                ae = hdisco.getLocalAdvertisements(
                    DiscoveryService.GROUP, "Name", "RestoNet");

                // If we found the RestoNet advertisement, we are done
                if ((ae != null) && ae.hasMoreElements(  ))
                    break;

                // The RestoNet advertisement is not in the local
                // cache. Send a discovery request to search for it.
                hdisco.getRemoteAdvertisements(null,
                       DiscoveryService.GROUP, "Name",
                       "RestoNet", 1, null);

                // Wait to give peers a chance to respond
                try {
                    Thread.sleep(timeout);
                } catch (InterruptedException ie) {}
            } catch (IOException e) {
                // Found nothing! Move on.
            }
        }

        // Check if we found the RestoNet advertisement
        if (ae == null || !ae.hasMoreElements(  )) {
            return false;
        }

        System.out.println("Found the RestoNet PeerGroup Advertisement");
        // Get the advertisement
        PeerGroupAdvertisement adv =
            (PeerGroupAdvertisement) ae.nextElement(  );

        try {
            // Call the peergroup factory to instantiate a new
            // peergroup instance
            restoNet = netpg.newGroup(adv);
        } catch (Exception e) {
          System.out.println("Could not create RestoPeerGroup");
          return false;
        }

        try {
            // Get the discovery and pipe services for the RestoNet
            // peergroup (unused in this example)
            disco = restoNet.getDiscoveryService(  );
            pipes = restoNet.getPipeService(  );
        } catch (Exception e) {
            System.out.println("Error getting services from RestoNet");
            throw e;
        }

        System.out.println(
            "The HungryPeer joined the restoNet PeerGroup");
        return true;
    }
}

Just as the RestoPeer service did, the HungryPeer starts by discovering and joining the NetPeerGroup. The basic outline of the joinRestoNet( ) method of the HungryPeer is very similar to the one in RestoPeer, except that this joinRestoNet( ) method does not create the RestoNet if one is not found. Instead, if this application does not find an existing RestoNet peergroup, it exits.

Not being able to find the RestoNet advertisement does not necessarily mean that no RestoNet peers are running in the JXTA network; it means only that we were not able to reach any RestoNet peers. This could be because we either did not wait long enough for an answer to come back, or we could not find a route to reach a running RestoNet peer. Trying for a total of 30 seconds is appropriate for this example, but you must make this decision in each application based on the demands of the application.

Note that there’s no particular reason why the HungryPeer couldn’t create the RestoNet peergroup if it didn’t find one; it could wait for a RestoPeer to come along and join that peergroup. This is one reason why the RestoPeer searched for an existing peergroup before creating one.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required