BUY THIS BOOK
Add to Cart

Print Book $34.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint this content?


JXTA in a Nutshell
JXTA in a Nutshell

By Scott Oaks, Bernard Traversat, Li Gong
Price: $34.95 USD
£24.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to JXTA
You're driving home at night; it's late and you're hungry. Imagine that your car has a device that automatically locates nearby restaurants and tells you which of them has the food you want at the best price. Better yet — what if you could contact nearby drivers, see if any of them also want to stop for food, and spontaneously form a group that negotiates with a nearby restaurant for a volume discount?
While you're waiting in the restaurant, you run into an old business acquaintance; in a brief discussion, you realize that she is working on a project that could provide a key feature for your own work. You could exchange business cards with her, of course, but why not immediately exchange the specifications of your projects instead?
And speaking of your office: you've still got to stop by the new print shop and pick up the slides for tomorrow's meeting. What if your desktop computer could find a new print shop that provides full color transparency printing services in just one hour?
These types of services have long been envisioned in an increasingly mobile and "connected" population. To a certain extent, many of them are possible today, especially if you have access to a centralized server or the other participants. JXTA will help us to expand such applications.
JXTA is a collaborative research project for peer-to-peer (P2P) computing. "Project JXTA" (or, more simply, JXTA) stands for Project Juxtapose; it is an acknowledgment that while client/server and web-based computing are important standards today, a strong need exists for P2P computing standards for a variety of applications. These applications share a few common traits.
  • They are spontaneous in nature.
  • They are more effective when the supporting architecture involves many distributed providers of the service rather than a single, centralized server.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is JXTA?
JXTA is a collaborative research project for peer-to-peer (P2P) computing. "Project JXTA" (or, more simply, JXTA) stands for Project Juxtapose; it is an acknowledgment that while client/server and web-based computing are important standards today, a strong need exists for P2P computing standards for a variety of applications. These applications share a few common traits.
  • They are spontaneous in nature.
  • They are more effective when the supporting architecture involves many distributed providers of the service rather than a single, centralized server.
  • Users of the application may be providers or consumers of the service abstracted by the application; they often perform both roles.
  • Users of the application come and go and therefore may not be available at any particular point in time.
  • Users of the application may be using any device at any time in any location.
Applications with these requirements are difficult to implement with traditional client/server computing models; they run better from a collection of cooperating peers with the ability to discover each other independently and to communicate regardless of the network infrastructure on which they reside.
To that end, JXTA defines a small set of common protocols that enable P2P computing. Each protocol is simple to implement and integrate into existing systems. This set of protocols defines JXTA.
It's important to realize the ramifications of that last statement. In particular, JXTA is not an API; although there are standard language bindings for the JXTA protocols, their use is not mandatory. Application developers and hardware providers may provide their own language bindings. New languages can evolve and provide their own bindings to the JXTA protocols, and new platforms can be developed that implement the JXTA protocols in entirely new ways. JXTA is language- and platform-independent.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why JXTA?
The rationale for JXTA has two facets. The first is the advantage of a P2P architecture for many applications. Take the auctioning example we used at the beginning of this chapter. We love the centralized auction services provided by eBay (and others) as much as anyone, but that model isn't well-suited for the type of auction described above.
No single factor determines when a P2P architecture is appropriate. At the risk of overwhelming you with buzzwords, we can say that a P2P architecture should be considered whenever you require scalable, robust, dynamic, fault-tolerant, spontaneous, self-organizing network computing. P2P architectures achieve buzzword compliance through mechanisms other than client/server computing:
Scalability
A web auction for specialized French fries available only at your local restaurant presents enormous scalability problems for a centralized system, which must handle requests and responses from every conceivable restaurant and potential diner. The service can segregate requests, but this isn't easy: the granularity the service uses to segregate the requests will directly affect the quality of the service it provides. And such a segregated service will inevitably be problematic for users on the segregation boundary. For example, if the service is segregated by zip code, users may be directed miles away within the same zip code when a closer choice is available a few blocks away in a different zip code.
A P2P system has a much easier time of it: the diner can discover nearby services automatically and at an appropriate scale. Since no centralized system monitors everything, there are no problems with system capacity: users of the service monitor nearby services in which they are interested and discard other information.
Robustness
As all computer users can attest, network computing is inherently unreliable: connections drop, servers crash, companies go out of business, and so on. Web search engines are useful entities and quite good at what they do, but they often lead to dead links and moved documents. We'd hate to direct our diner three miles out of his way to a restaurant that closed last week; it would be much better if we can direct him only to open restaurants. Similarly, we'd hate for our diner to go hungry because the restaurant auctioning server has gone down or is being subjected to a denial of service attack.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JXTA Overview
At a specification level, JXTA defines a number of protocols that enable P2P computing. At another level, the JXTA community has developed language bindings; these bindings implement the protocols and allow developers to write JXTA applications. Embedded within these bindings are several core JXTA services that provide needed functions for JXTA applications. Neither the language bindings nor the core service implementations provided by the JXTA community are strictly necessary in order to develop JXTA applications: as long as the application correctly implements the necessary protocols, it can use any language, network transport, and service implementation to do so. Nonetheless, we expect most initial JXTA applications to follow the Java language bindings presented throughout this book and to use the core services implementations provided by the JXTA community.
Think in terms of other protocol specifications. Today, most computer networks run on the Internet Protocol (IP) specification. Other network protocols, like the Transmission Control Protocol (TCP) and Uniform Datagram Protocol (UDP), are layered on top of IP. Still other protocols, such as the HyperText Transfer Protocol (HTTP), are layered on top of those protocols. Yet for the most part, developers of network applications and services have no idea how the underlying protocols work. Developers create a TCP connection to another server by opening a socket with the BSD socket library, the WinSock socket library, the Java Socket class, or some other API layer. Some intrepid developers may use TCP sockets to send HTTP protocol messages, but most will use an HTTP protocol binding, such as the Java URL-related classes. Still fewer developers will open raw IP sockets and deal with the network at that level.
JXTA is a network protocol that is layered on top of other network protocols. In its Java language bindings, it is layered on both TCP and HTTP, but it can be layered equally as well over emerging network standards, such as Bluetooth. You could certainly open TCP sockets and send JXTA protocol messages over those sockets, but it is far easier to use the JXTA language bindings to hide the details of the protocol.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
P2P applications have caught the imagination of millions of computer users worldwide; from Napster to Instant Messenger, P2P applications are among the most widely used applications on the Internet today.
Yet there are several barriers to the widespread adoption of P2P technology. Primary among these is that such applications tend to be developed in isolation and without standards; an application that can deal with IM has no concept of how to operate in any other P2P realm. In addition, though much of the communication in these applications is P2P, they still tend to rely on big, centralized servers to provide key features of the service.
JXTA seeks to level these barriers by providing a standard set of protocols that all P2P applications can use. These protocols are network- and language-independent and allow the development of services that do not rely on a centralized system. In the same way that standardized network protocols such as TCP and HTTP made the explosion of client/server network applications possible, the standardized JXTA protocols seek to fulfill the promise of P2P computing.
In the next chapter, we'll explore JXTA in more depth by interacting with a standard JXTA demo, the JXTA Shell. This will position us to begin writing our own JXTA applications in the following chapters.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started with JXTA
In this chapter, we'll see how to get started with JXTA. Although JXTA is a language- and platform-neutral specification, we'll focus on using the standard JXTA applications for the Java platform. The basic concepts that you'll learn in this chapter are applicable to any JXTA implementation using any language; we chose to illustrate the concepts of JXTA using the Java platform because it allows for the simplest discussion of JXTA concepts, and because the Java platform gives us a common basis for our examples, regardless of the computer on which you might run them.
We'll start by discussing how to set up a Java environment to run JXTA programs. Then we'll look in depth at one particular program: the JXTA Shell. Examining the shell will allow us to look in depth at each of the protocols and techniques that JXTA defines; working through the examples in this chapter should provide you with a working knowledge of the key concepts of the JXTA platform and how programs operate within that platform.
The first step in using JXTA is to set up your environment. In this case, that means setting up a Java environment to run JXTA, for which you'll need three things: a Java platform, the JXTA Java class libraries, and any JXTA programs that you want to run.
For the Java platform, you'll need the Java 2 Standard Edition (J2SE), Version 1.3.1 or later (Version 1.4 is preferred). Multiple implementations of the JXTA protocols are already available. A C implementation (jxta.c.jxta) and a Personal Java Profile edition are both available.
This chapter focuses on running and explaining existing JXTA applications. Therefore, if you're using the Java 2 platform, you need only the Java 2 runtime environment (J2RE). If you plan on programming with JXTA (using the examples in subsequent chapters), then you'll need the Java 2 Software Developer's Kit (SDK).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting Up a Java Environment
The first step in using JXTA is to set up your environment. In this case, that means setting up a Java environment to run JXTA, for which you'll need three things: a Java platform, the JXTA Java class libraries, and any JXTA programs that you want to run.
For the Java platform, you'll need the Java 2 Standard Edition (J2SE), Version 1.3.1 or later (Version 1.4 is preferred). Multiple implementations of the JXTA protocols are already available. A C implementation (jxta.c.jxta) and a Personal Java Profile edition are both available.
This chapter focuses on running and explaining existing JXTA applications. Therefore, if you're using the Java 2 platform, you need only the Java 2 runtime environment (J2RE). If you plan on programming with JXTA (using the examples in subsequent chapters), then you'll need the Java 2 Software Developer's Kit (SDK).
There are a number of ways to obtain current releases of the Java platform. If your system is running Solaris, Microsoft Windows, or Linux, the simplest way is to download the SDK from http://java.sun.com/j2se/. For other operating systems, check with your system vendor. More commonly, many integrated development environments (IDEs) come with support for Java (and hence a Java platform).
Once you've obtained and installed Java, you must make sure that the java executable is in your standard path.
You can obtain all the JXTA files you need at http://download.jxta.org/easyinstall/install.html. On this page, you can obtain the JXTA demo package for a variety of platforms. In fact, the JXTA demo implementation at this site is written completely in Java; the difference between the platforms lies only in how the parts of the implementation are packaged and how they are installed. Therefore, for Microsoft Windows, download an executable (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic JXTA Concepts
Now that we have all of this software, we'll use it to explain a little more about the basic JXTA concepts we outlined in Chapter 1, including how a JXTA application is constructed. We'll use the JXTA Shell as the basis for our exploration, since it provides us with an interactive tool that uses the JXTA platform to perform its operations.
Before we dive into the shell, here are some notes on its syntax. Like any shell, the JXTA Shell issues a prompt (JXTA>) at which you type in commands.
Shell commands have two kinds of output. Most of them simply send their output to the screen. Some commands, however, produce an object as their output. These objects should be saved in a shell variable. If you do not save the object, most commands will create a new object with a default name to hold the return value; if you're going to need the object, it's easier to assign a name to it yourself. Shell variables are created in JXTA by assigning a new name to the output of such a command.
Here are some simple examples. The env command produces as its output a list of all the shell variables and their values:
JXTA>env
stdin = Default InputPipe (class net.jxta.impl.shell.ShellInputPipe)
parentShell = Root Shell (class net.jxta.impl.shell.bin.Shell.Shell)
Shell = Root Shell (class net.jxta.impl.shell.bin.Shell.Shell)
stdout = Default OutputPipe (class net.jxta.impl.pipe.NonBlockingOutputPipe)
consout = Console OutputPipe (class net.jxta.impl.shell.ShellOutputPipe)
consin = Default Console InputPipe (class 
net.jxta.impl.shell.ShellInputPipe)
stdgroup = Default Peergroup (class net.jxta.impl.peergroup.StdPeerGroup)
Shell variables are created by assigning a new name to the output of a command that creates an object. mkadv
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JXTA Peers
We'll start our examination of JXTA's key concepts with the notion of a peer. As defined in the JXTA specification, a peer is a device that implements one or more JXTA protocols. The key idea is that something implements the protocols. Don't get too hung up on the notion of a device—a device is not necessarily a machine. A single machine can host multiple JXTA programs, each of which is really a peer. The program is really a virtual device.
Of course, peers normally communicate with each other over a network, so a JXTA community typically has many different machines within it. However, some of these machines could be running multiple JXTA peers. A single JXTA peer could be a distributed application running across multiple machines. And if you're following the example in this chapter at home on your own single computer, you'll end up running many peers on your local system.
To start our first peer, we'll execute the JXTA Shell. On Microsoft Windows systems, you can do this by selecting Programs Jxta JXTA Shell from the start menu. On other platforms, you can do this by executing these commands:
piccolo% cd /files/JXTA_Demo/Shell
piccolo% sh shell.sh
            
When you first start the shell, you'll see the window displayed in Figure 2-1. This allows you to configure the shell for the network on which it will run. We explain the configurator in detail later in this chapter. For now, we'll just step through the two required elements that you must configure.
Figure 2-1: The JXTA configurator tool
First, fill in the peer name with a string of your choice (we chose "Test Shell 1") and press the OK button. On the next screen, fill in the username you'd like to use and a password for that username. In Figure 2-2, we've specified myusername and entered a password.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Peergroups
Peers self-organize into groups. JXTA does not define what these groups are, nor why they exist: the JXTA framework supports the creation of groups and the definition of group membership, but it is up to cooperating peers to define groups, join groups, and leave groups. Among other purposes, peergroups serve to:
Define a set of services and resources
In order to participate in an auction, a peer must find a JXTA peergroup that provides an auction service. The peer must join that group; only peers that have joined the group can use the services available in the group.
There are a number of important resources that exist within each peergroup. A service is a specific type of JXTA resource. A peer that wants to use the resources of a particular peergroup must join that peergroup. Similarly, peers can communicate only with each other if they have joined the same group (although, as we'll see, all peers belong to the NetPeerGroup, so they can always communicate with each other).
Provide a secure region
Because of their membership requirement, peergroups form an entity with a logical boundary. Peergroups may strongly enforce a membership requirement so that the boundaries define a secure environment as well: content within a peergroup can be accessed only by peers belonging to that group, so a peergroup with strict membership requirements can secure its content from the rest of the world.
The underlying network topologies of peers within a peergroup do not necessarily reflect physical network boundaries, such as those imposed by routers and firewalls. A peergroup can consist of peers on completely disparate networks. Peergroups virtualize the notion of routers and firewalls, subdividing the network in secure regions without respect to actual physical network boundaries.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Discovery
So far, our shell does not know a lot of peers. In the JXTA world, this is not a good thing, as a peerless JXTA application is not very useful. The first thing it must do, therefore, is find other peers with whom it can exchange information. The process of finding other peers is called discovery.
The process of discovery applies to any JXTA resource: peers discover other peers, and they also discover peergroups, pipes, advertisements, and other resources. There are two ways in which peers discover resources: peers discover resources dynamically, and they use special, statically configured peers to tell them about JXTA resources. Discovery occurs within the context of a peergroup: a peer attempts to discover resources within a specific peergroup.
Peers use the JXTA Peer Discovery Protocol (PDP) to discover JXTA resources dynamically. The PDP defines the lowest-level technique that is available for peers to discover resources. On an IP network, it consists of two parts: a multicast message that is sent on the local network and the use of rendezvous peers to discover peers beyond the scope of the local network. Other network bindings will behave differently, but the essential operation of the PDP is that the requesting peer sends a message, and resources that hear the request will respond directly to the peer. Therefore, a peer using PDP will discover all JXTA resources that are on the local network or are known by the peer's rendezvous peers.
The implementation of discovery is actually a feature of the peergroup in which the peer is running. Certain peergroups may define other protocols by which peers can discover resources within the peergroup. The PDP is implemented by the discovery service that runs within the NetPeerGroup (and most other peergroups).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JXTA Application Configuration
The dialog box that we showed in Figure 2-1 should make a little more sense now. That box is called the JXTA configurator tool, and it's a basic feature of the JXTA platform. All JXTA applications use this tool when they are first configured.
Configuration information is stored by this tool in the local directory. The configuration information also includes a local port number on which the JXTA application will listen. For that reason, you cannot run two instances of the shell (or any other application) on the same machine from the same directory. Instead, you must do the following:
  • Create a new directory in which to hold the configuration information (e.g., /files/JXTA_Demo/Shell.2).
  • Copy the shell.sh or shell.bat script into that directory.
  • cd to that directory.
  • Execute the startup script.
When this shell starts, you will again be presented with the configuration box from Figure 2-1. You'll need to perform some advanced configuration in order for this second shell to run.
The configurator has four panels:
Basic
The basic panel of the configurator allows you to assign a name to your peer. Any string can be entered (we chose "Test Shell 1"): it can represent a person's name, a hostname, or any other identifier. The name you enter is not guaranteed to be unique. No centralized naming service is used by the configurator; therefore, two peers may end up with the same name. This is okay, since the peer name is intended to be used only as a hint for searching or identifying peers. Also, each peer is assigned a peer ID that is guaranteed to be unique for every peer in the JXTA network.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Pipes
One of the most powerful of JXTA's services is the pipe service. The idea of a pipe is familiar to users of Unix systems: a pipe is used to connect the output from one command to the input of another command. On a Unix system, if you want to count the number of unique exceptions that occur in a log file, you might use this command:
piccolo% cat log | grep "Exception" | sort | uniq | wc -l
            
The cat command prints the log file to its standard output. The grep command reads this file from its standard input and searches for lines containing the string "Exception"; it prints matching lines to its standard output. The sort command reads these lines from its standard input and sends the sorted list to its standard output, where it is read by the uniq command, which removes duplicate lines. The unduplicated lines are sent to its standard output, where they are read by the wc command, which counts the number of lines and finally prints that number.
Pipes are quite useful in that they allow you to build complex functionality from a number of simple building blocks. JXTA takes the familiar idea of pipes and extends their functionality to the network.
JXTA pipes are defined in terms of the endpoints available to a peer. A peer endpoint is a logical abstraction of an address on a network transport that is capable of sending and receiving network messages. In the examples we've seen so far, the network transport has always been IP-based: the shell peer we've looked at has a TCP endpoint (port 9701 by default) and can have an HTTP endpoint. However, JXTA does not make this assumption and allows an endpoint to be an address on any network transport as long as the network is capable of sending and receiving datagram-style (i.e., unreliable packet-based) messages.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Advertisements
We've mentioned advertisements in passing a number of times in this chapter; we even created advertisements for pipes and groups using the shell's mkadv command. Advertisements are one of the basic building blocks of JXTA: they help peers discover any kind of service, including peergroups, other peers, and pipes. In fact, at a basic level, the JXTA infrastructure is simply about sending advertisements for various resources around to interested parties. A JXTA application simply searches for advertisements it is interested in and responds to requests for advertisements that it has published. The basic protocols we've mentioned all use advertisements as the mechanism by which they send data. Advertisements provide a platform-independent representation of platform objects that can be exchanged between different platform implementations (Java, C, etc.).
Advertisements are structured XML documents. The JXTA infrastructure defines six such documents:
  • Peer advertisement
  • Peergroup advertisement
  • Pipe advertisement
  • Service advertisement
  • Content advertisement
  • Endpoint advertisement
Developers may subclass these advertisements when they create their own services. For example, a content advertisement could announce that a peer has a particular item (such as a PDF file of this chapter). A JXTA application may create a subclass of the content advertisement to refer only to PDF files of this book. Peers who are interested in generic content can look for standard content advertisements; peers who are interested in only the PDF files of this book can look for the content subclass. Both peers will find the PDF of this chapter, but the second will find less extraneous content.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, we used the JXTA Shell to explore the underpinnings of the JXTA framework. Each instance of the shell is a peer, and we've seen how multiple peers can use a variety of techniques to discover other peers. As implemented in the shell, these techniques are tied to a particular network binding (e.g., TCP), though the PDP is designed to run over any network.
Similarly, we've seen how the shell peers organize themselves into peergroups, another key JXTA concept. Peergroups allow for the segregation of services so that peers can more easily manage their relationships with other peers.
The communication between peers in JXTA is based on the notion of an endpoint. One key example of an endpoint is a pipe, which can provide either input or output for a peer and allows complex behavior to be built from several simple peers. Pipes form the basis of communication in JXTA; peers depend on advertisements to locate pipes and other endpoints with which they want to communicate.
The shell provides a mechanism by which we can explore and test many of these features. In the next few chapters, we'll look into how we can develop our own JXTA applications that include these same features.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: A Hello World Example
In the next few chapters, we'll show you how to write JXTA applications using the Java language API provided with the JXTA platform. If you want to use a different language, the program structure that we describe will be helpful, though the syntax and API calls will be different. The JXTA API is used by application and service developers: it provides high-level constructs, such as pipes and peergroups, for application developers, as well as low-level constructs, such as advertisements and structured documents, for service developers. The examples in the next few chapters cover both types of constructs.
We'll start in this chapter with a simple "Hello world" example. This example will cover the basic flow of control for a JXTA application and how a JXTA application is configured and executed. In later chapters, we'll use a restaurant auction example to illustrate other key concepts, such as discovery, peergroups, pipes, advertisements, services, and security.
The JXTA platform provides an integrated environment to run applications. An application can be run in three ways:
  • An application can be added to the JXTA Shell, after which it may be run interactively in an instance of the shell.
  • A standalone application can be written to instantiate, configure, and use the JXTA platform.
  • A JXTA service can be used by other JXTA applications. JXTA services can be started on demand.
In the next three chapters, we'll focus on the second method. This method describes in more detail how an application interacts with the platform. We'll discuss the last method in Chapter 6.
The first thing a JXTA application must do is discover and join the NetPeerGroup. As we explained in Chapter 2, every JXTA peer belongs to the NetPeerGroup (also called the World Peergroup). New peergroups are created within the NetPeerGroup and are composed of a subset of the NetPeerGroup peer members. From the NetPeerGroup, applications can discover and crawl through all other peergroups within the NetPeerGroup.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Peergroups
The first thing a JXTA application must do is discover and join the NetPeerGroup. As we explained in Chapter 2, every JXTA peer belongs to the NetPeerGroup (also called the World Peergroup). New peergroups are created within the NetPeerGroup and are composed of a subset of the NetPeerGroup peer members. From the NetPeerGroup, applications can discover and crawl through all other peergroups within the NetPeerGroup.
The NetPeerGroup permits all peers to find enough information to bootstrap and support themselves. For obvious scalability reasons, usage of the NetPeerGroup should be limited to bootstrapping. Peers should create and join other peergroups after bootstrapping themselves.
In the Java language, peergroups' objects are instances of the PeerGroup class (net.jxta.peergroup.PeerGroup). There are ways to create your own peergroups, of course, but an object that represents the special NetPeerGroup is returned from the static newNetPeerGroup( ) method of the PeerGroupFactory class (net.jxta.peergroup.PeerGroupFactory). Therefore, the simplest of all JXTA applications looks like this:
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.exception.PeerGroupException;

public class HelloWorld {

    static PeerGroup group = null;

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

    private void startJxta(  ) {

        try {
            // Create and start the default JXTA NetPeerGroup
            group = PeerGroupFactory.newNetPeerGroup(  );
        } catch (PeerGroupException e) {
            // Could not instantiate the group; print the stack and exit
            System.out.println(
                "Fatal error : creating the net PeerGroup");
            System.exit(1);
        }
        System.out.println("Started Hello World");
    }
}
When the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running JXTA Applications
To compile this example, you need to add JXTA files to your classpath as we discussed in Chapter 2. Then you can simply compile the HelloWorld class:
piccolo% javac HelloWorld.java
            
The application is started as we might expect:
piccolo% java HelloWorld
            
As we mentioned, the first time you run the platform from a particular directory, the configurator will pop up and ask you to configure the network environment. Subsequent invocations of the application will require you to enter the secure username and password that you entered into the configurator when you first ran the program. Once you've run the configurator and/or entered the correct username and password, the platform starts booting, and the following message is printed:
Started Hello World
If you examine the directory in which the program was run, you'll discover that the .jxta directory contains the platform configuration file (PlatformConfig), the peergroup cache directory (cm), and the username directory (pse).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Advertisements
Let's look now at some JXTA advertisements. Advertisements are central to JXTA; you discover JXTA peers and their resources by looking for advertisements, and you provide your own services by publishing advertisements. Therefore, working with advertisements and the documents they contain is the next step we must take in learning how to develop JXTA applications.
Advertisements are represented by the abstract Advertisement class (net.jxta.document.Advertisement). Each advertisement has a unique type, which is returned by the getAdvertisementType( ) method. The JXTA API defines the following core advertisement types (each of which is an abstract class in the net.jxta.protocol package):
  • PeerAdvertisement
  • PeerGroupAdvertisement
  • PipeAdvertisement
  • PeerInfoAdvertisement
  • EndpointAdvertisement
  • ModuleClassAdvertisement , ModuleSpecAdvertisement, and ModuleImplAdver-tisement (module-related advertisements)
  • RdvAdvertisement
  • TransportAdvertisement
Each advertisement object holds an object that implements the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Peergroup Services
All peergroup objects carry certain information: the name of the peergroup, its unique universal identifier (UUID), and so on. In addition, peergroups provide certain core JXTA services, as we mentioned in Chapter 2. In particular, peergroups can provide a discovery service that can be used to discover other JXTA peers and services, a pipe service that can be used to create input and output pipes, and a membership service that can be used to join the peergroup. All of this information can be retrieved from the peergroup object:
private void startJxta(  ) {
    try {
        // Create and start the default JXTA NetPeerGroup
        group = PeerGroupFactory.newNetPeerGroup(  );
    } catch (PeerGroupException e) {
        // Could not instantiate the group; print the stack and exit
        System.out.println("Fatal error : creating the net PeerGroup");
        System.exit(1);
    }

    System.out.println("Started Hello World");

        // Now we'll access the peergroup service
        // and get various information from it
        PeerGroupID pgid = group.getPeerGroupID(  );
        System.out.println ("pgid= " + pgid);
            
        PeerID pid = group.getPeerID(  );
        System.out.println("pid= " + pid);
            
        String name = group.getPeerName(  );
        System.out.println("peer name=" + name);

        // Get the core services. We don't use the core services in this
        // example, but this is how you retrieve them if you need them.
        DiscoveryService disco = group.getDiscoveryService(  );
        PipeService pipe = group.getPipeService(  );
        MembershipService member = group.getMembershipService(  );
        ResolverService resolv = group.getResolverService(  );
            
        System.out.println("All done");

     } catch (Exception ex) {
         ex.printStackTrace(  );
     }
}
The information printed by this code looks like this:
Started Hello World
pgid= urn:jxta:jxta-NetGroup
pid= urn:jxta:uuid-59616261646162614A7874615032503368D0F1C1B8B54A3ABE2F8D
DEEE47489F03
peer name=Test Application 1
All done
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, we provided the skeleton of a basic JXTA application. This application shows us how to initialize the JXTA platform and perform basic operations with JXTA advertisements and peergroups.
While the HelloWorld class is a complete JXTA application and has allowed us to understand the basic structure of programming in JXTA, it doesn't actually do anything except print out a lot of interesting information. In the next few chapters, we'll develop a more complete example, one that leverages the features of the JXTA platform to create a community of cooperating peers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Service Advertisement and Discovery
In the next few chapters, we'll expand on the JXTA application interface and develop a complete JXTA application that is both a decentralized service and an application that uses the service. The complete example is spread out over a few chapters; we begin in this chapter by showing how to handle service advertisement and discovery. In later chapters, we'll add the pipe communication between the service and application as well as handling some security issues.
The example we'll build will perform auctioning. Auctioning applications are great for demonstrating decentralized, P2P interactions between auctioneers and biders. The JXTA programming model can be applied with great simplicity to build a cost-effective and efficient auctioning system.
Auctioning systems are typically implemented with a centralized (client/server) auctioning server model (see Figure 4-1). The central auctioning server receives auction offers and bids, and matches them. While centralized auction architecture has some advantages, it presents some significant scalability, security, and reliability issues. The auctioning server needs to be scaled when the number of auctions and bid requests increase, as performance tends to decrease as more and more users are active on the system.
Figure 4-1: The client/server auction architecture
The auctioning server is a single point of failure for the entire system: if the server goes down, all transactions are stopped. While clustering and failover technologies are typically used to address single server failures, there is a tremendous cost associated with maintaining and growing a centralized server infrastructure. One cannot expect to continue to grow centralized server computing facilities without reaching a point at which too much complexity is introduced. Furthermore, as these facilities become larger, their level of unreliability is increased because more components can fail. Auctioning servers are also the perfect target for denial of service attacks as intruders and attackers can focus their effort on a limited set of servers to bring the entire system down.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Auctioning Example
The example we'll build will perform auctioning. Auctioning applications are great for demonstrating decentralized, P2P interactions between auctioneers and biders. The JXTA programming model can be applied with great simplicity to build a cost-effective and efficient auctioning system.
Auctioning systems are typically implemented with a centralized (client/server) auctioning server model (see Figure 4-1). The central auctioning server receives auction offers and bids, and matches them. While centralized auction architecture has some advantages, it presents some significant scalability, security, and reliability issues. The auctioning server needs to be scaled when the number of auctions and bid requests increase, as performance tends to decrease as more and more users are active on the system.
Figure 4-1: The client/server auction architecture
The auctioning server is a single point of failure for the entire system: if the server goes down, all transactions are stopped. While clustering and failover technologies are typically used to address single server failures, there is a tremendous cost associated with maintaining and growing a centralized server infrastructure. One cannot expect to continue to grow centralized server computing facilities without reaching a point at which too much complexity is introduced. Furthermore, as these facilities become larger, their level of unreliability is increased because more components can fail. Auctioning servers are also the perfect target for denial of service attacks as intruders and attackers can focus their effort on a limited set of servers to bring the entire system down.
Since all transactions are processed on the auctioning server, user information can be easily logged by the auctioning provider, potentially invading the privacy of the auctioneers or bidders. Auctioneer profiles can be easily captured and sold to marketing research companies. Sensitive user information (email or personal contact information) is typically maintained on the auctioning server, creating the possibility of an intruder accessing this information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JXTA Discovery
The first thing a peer must do is discover its surrounding environment. Peers discover resources, support themselves, access needed services, and expand their horizons in their surrounding environments. In the case of a RestoPeer, the first thing it must do is discover and join the RestoNet peergroup. There is, of course, no guarantee that the RestoNet peergroup already exists, so the RestoPeer must be prepared to create it as well.
JXTA discovery is closely related to the peergroup concept: discovery in JXTA is performed within the context of a peergroup. We have seen that every peer joins the NetPeerGroup. Discovery performed within the context of the NetPeerGroup enables any peer to potentially discover any advertisements published in the NetPeerGroup. Due to the large number of advertisements in the NetPeerGroup, it is impractical to perform discovery within the context of the NetPeerGroup; peers should attempt to discover peergroups within the NetPeerGroup context and then attempt to discover other resources within a smaller peergroup.
The discovery scope of a peer corresponds to the peergroup context in which discovery is performed. For example, in Figure 4-3, if discovery is performed within the context of Peergroup 2, only advertisements stored on peers that are members of the Peergroup 2 can be discovered. The peergroup context enables a peer to scope discovery operations and reduces the risk of overwhelming the network.
Figure 4-3: The discovery scope of JXTA peergroups
Note that a peer may belong to multiple peergroups (shown as intersecting peergroups in Figure 4-3). When publishing advertisements, the publishing peer defines the scope of discovery by selecting which peergroup the advertisement is published in. The same advertisement may be published in multiple peergroups. In Figure 4-3, Peer A publishes an advertisement in both Peergroup 2 and Peergroup 3. This means that only members of Peergroups 2 and 3 can discover the advertisement; members of Peergroup 1 cannot discover the advertisement. Each peergroup corresponds to a different discovery scope.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Service Implementation
Here's our first implementation of the RestoPeer class (the code that provides the restaurant service). A RestoPeer is responsible for discovering and joining the RestoNet peergroup; if the peer cannot find the RestoNet peergroup, the peer will create it.
The RestoPeer class has a simple structure:
  1. Discover the existing RestoNet peergroup advertisement.
    1. Look for any previously discovered advertisements in the local cache.
    2. Send the PDP request to discover the advertisement.
      This may be done using a broadcast-type mechanism or by contacting known rendezvous peers, either of which is a synchronous call to the developer. Behind the scenes, the API will create a new thread that will listen for responses. As these responses come back, the background thread will read them and insert the responses into the peer's local cache of advertisements.
    3. Wait a while for any responses to come back.
    4. Look again for responses in the local cache.
  2. If the existing RestoNet is not found, create a peergroup advertisement for it. Then create the peergroup based on that advertisement.
  3. If the existing RestoNet is found, use the discovered advertisement to join the peergroup.
Here's the code necessary to perform these steps:
import java.io.*;
import java.net.*;
import java.util.*;

import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.exception.PeerGroupException;
import net.jxta.discovery.DiscoveryService;
import net.jxta.id.IDFactory;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.protocol.ModuleImplAdvertisement;


// RestoPeer represents a restaurant that receives auction requests
// for food from HungryPeers. The RestoPeer will discover and join
// the RestoNet and publish itself as a provider for HungryPeers

public class RestoPeer {

    private PeerGroup netpg = null;     // The NetPeerGroup
    private PeerGroup restoNet = null;  // The RestoNet peergroup

    private String brand = "Chez JXTA"; // Brand of my restaurants
    private int timeout = 3000;         // Time-out; can be adjusted

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

    static String groupURL =
          "jxta:uuid-4d6172676572696e204272756e6f202002";

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

    // Start the JXTA application
    private void startJxta(  ) {
        try {
            // Discover and join (or start) the default peergroup
            netpg = PeerGroupFactory.newNetPeerGroup(  );
        } catch (PeerGroupException e) {
            // Couldn't initialize; can't co