Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Peer Resolver Protocol API

The peer resolver protocol API can be thought of as rather misnamed. A resolver is classically defined for TCP/IP as a protocol for formatting requests to be sent to a domain name server to convert hostnames to an Internet address. However, a resolver is also defined as resolving a question, which is much closer to what the peer resolver protocol is actually used for. Simply, the JXTA resolver protocol is used to send a query to another peer and receive a response.

Simple P2P Messages, No Guarantees

The messages of the resolver are quite simple. They are also not guaranteed to reach their destinations nor are the results, if they exist, guaranteed to arrive back at the source of the query. The rendezvous may refuse or fail to transmit either message, or the answer may not exist. There is also no guarantee of an answer or even a notification that there is no answer.

Query Message

The query message is a standard wrapper of XML around a payload of information defined by the implementation. The implementation is specified by the handler name.

The wrapper contains a credential, the handler name, the source peer ID, a query ID, and the query. The DTD for the query is as follows:

<!ELEMENT ResolverQuery (Credential,
             HandlerName,
             SrcPeerID,
             QueryID,
             Query)>

<!ELEMENT Credential #PCDATA>
<!ELEMENT HandlerName #PCDATA>
<!ELEMENT SrcPeerID  #PCDATA>
<!ELEMENT QueryID   #PCDATA>
<!ELEMENT Query    #PCDATA>

Response Message

The response message is very similar to the query. The differences are in the credential and the response. The credential is the credential of the responding peer. Like the query message, the credential is the one created when the response peer joined the group. The credential could be checked to verify that the peer that answered the message was a valid member of the group.

The query ID in the response is identical to the query. This allows you to quickly match a query to a response if you perform multiple queries. Also, because queries can arrive out of order and may be repeated, the query ID can be used to order responses and consume duplicate messages.

The resolver finds your query handler using the specified handler name. The handler name should be the same as the query handler name. The handler interface has both a process query and a process response. The duality of the interface, and a single name, help promote the idea that all peers participate in both queries and responses.

Like the query, the payload is in a tag, this time called Response. The DTD for the XML is as follows:

<!ELEMENT ResolverResponse (Credential,
              HandlerName,
              QueryID,
              Response)>

<!ELEMENT Credential #PCDATA>
<!ELEMENT HandlerName #PCDATA>
<!ELEMENT QueryID   #PCDATA>
<!ELEMENT Response  #PCDATA>

Message Security

The credential is not a guarantee that the response message is from a valid peer. It would be very easy to copy a credential and masquerade as the response peer. To ensure that the message is not counterfeit, the message should either be encrypted or signed in a way that the signature contains verification of the peer, the message ID, and that the data has not been modified.

Resolver API Classes

The UML for key resolver classes can be seen in Figure 3.9. The classes and interfaces are as follows:

  • ResolverInterface—A class that implements the resolver management. This class is the focal point of functionality for sending queries and distributing responses. The class implements the ResolverService and the GenericResolver interfaces.

  • ResolverService—Interface that defines the interface to register and unregister query handler classes. The interface also extends the GenericResolver interface, which completes the resolver service by defining the methods used for sending queries and sending responses.

  • GenericResolver—Interface that defines the methods used for sending queries and sending responses.

  • QueryHandler—This is the interface to implement to handle queries and responses to queries.

  • ResolverQueryMsg—This is the message that is sent to other peers for processing. The ResolverQuery is the default implementation and extends ResolverQueryMsg.

  • ResolverResponseMsg—This is the message that is sent to other peers for processing. The ResolverResponse is the default implementation and extends ResolverResponseMsg.

Figure 3.9 Key classes in the Peer Resolver API.

Coding and Starting the Handler

To create the handler, you simply implement the QueryHandler interface. The interface only has two methods—processQuery and processResponse. The processQuery method is called when a peer receives a query and processResponse is called when the query returns.

The processQuery Method

The processQuery method is, as we have just pointed out, used by a peer to process a query message. The method is called from within the resolver after the query is received. The query message is passed to this method for processing.

The processQuery method is used called on the responder peer. In other words, this method is only called if you receive a query message from another peer. The process response method of this interface is only called when a response is received from a peer you have queried.

The return from the method is the message to be sent back to the peer that asked the question. The signature of the call is as follows:

ResolverResponseMsg processQuery(ResolverQueryMsg query) 
                throws NoResponseException,
                   ResendQueryException,
                   DiscardQueryException;

The exceptions thrown are quite important, because they result in very specific behavior of the resolver. Depending on the error, processQuery method throws NoResponseException, ResendQueryException, or a DiscardQueryException. The following are the exceptions that you can throw from the method and what the resolver will do in response:

  • NoResponseException—Throw when you do not have a response, but the response peer is interested in getting an answer for itself. The resolver system will propagate the query and resend it. Note that the query will only be propagated if the peer is a rendezvous.

  • ResendQueryException—Causes the resolver to resend the query.

  • DiscardQueryException—The query is discarded and not forwarded from the peer. Remember that the response peer is not required to return a response.

Note

Java veterans may notice that the processQuery exceptions are used as a form of logic control. Expect this to change because the cost of processing an exception is very high.

Traversing a try...catch block costs nothing in most JVM implementations. When an exception is thrown, there are several operations that involve manipulations and examination of the stack, lookups of catch locations, and catch types. Although simple to use, exception handling is very expensive. Exceptions, which should be rare errors, are rarely seen, so the cost is for a single exception is not noticeable. This is not the case for processQuery method.

Look for this method to change in a future version.

Processing Responses

The processResponse method in the QueryHandler interface is a little simpler than the processQuery method because this is a termination point of the query. There are no exceptions to throw to drive resolver behavior. However, because this is a handler, be careful about allowing an exception to be thrown here. By throwing an exception, you can cause the resolver to cease functioning:

void processResponse(ResolverResponseMsg response);

Example QueryHandler

The query handler has two methods to be implemented. In Listing 3.1, the processQuery method adds a time stamp to the payload of the query message. The processResponse method simply prints the message that was received. Because you always have an answer (the time stamp) you never throw an exception.

Listing 3.1 Sample implementation of a QueryHandler

class TestQueryHandler implements QueryHandler{
  protected String handlerName;
  protected String credential;
  protected SimpleDateFormat format  = new SimpleDateFormat (
                     "MM, dd, yyyy hh:mm:ss.S");
  
  public TestQueryHandler(String handlerName, String credential){
   this.handlerName = handlerName;
   this.credential = credential;
  }// end of constructor TestQueryHandler()

  public void processResponse(ResolverResponseMsg response) {
   System.out.println("Received a response");
     String textDoc = response.getResponse();
     System.out.println(textDoc);
   }// end of processResponse()
   
  public ResolverResponseMsg processQuery(ResolverQueryMsg query) 
                     throws NoResponseException, 
                         ResendQueryException,
                         DiscardQueryException,
                         IOException {
   System.out.println("Received a query");
   System.out.println(((ResolverQuery)query).toString());
   StructuredTextDocument doc = null;
   String textDoc = query.getQuery();
   doc = (StructuredTextDocument)StructuredDocumentFactory
      .newStructuredDocument
      ( new MimeMediaType( "text/xml" )
      ,new ByteArrayInputStream(textDoc.getBytes()) );

   // Use the original payload and add the time
   Element e = null;
   long now = System.currentTimeMillis();
   e = doc.createElement("timestamp 2",format.format( new Date(now)));
   doc.appendChild(e);
   // Return a generic response;
   ResolverResponseMsg message = null;
   String xml = serializeDoc(doc);
   message = new ResolverResponse( handlerName
                  , credential
                  , query.getQueryId()
                  , xml);
   return (ResolverResponseMsg)message;
  }// end of processQuery()
}// end of class TestQueryHandler 

Accessing and Setup of the Resolver

The resolver is found in your group. It is simple to just call the getResolverService method of the peer group you are using. The return type is a ResolverService, but actually you get an instance of ResolverServiceImpl. ResolverServiceImpl contains the actual methods used to submit the queries. The ResolverService interface specifies the adding and removal of query handlers.

The GenericResolver interface defines the methods for sending queries and responses. In GenericResolver, you really only use the method to initiate queries, while the method for sending responses is called by the internals of the resolver in response to the QueryHander.processQuery method:

ResolverServiceImpl resolver;
resolver = (ResolverServiceImpl)group.getResolverService();
TestQueryHandler handler = new TestQueryHandler(handlerName,credential);
resolver.registerHandler(handlerName, handler);

Getting Ready—Finding a Rendezvous Peer

The resolver only operates in terms of rendezvous peers. Queries must begin at rendezvous. If your current peer is configured as a rendezvous, there is no problem. If your peer is not a rendezvous, you will need to know about a rendezvous.

Note that there is no guarantee that a specific peer will answer. The peer that answers is the peer that actually sends the response. If the specified rendezvous peer has the answer, it will reply and take no further action. If the peer does not have an answer and throws NoResponseException or ResendQueryException, the query is forwarded to another rendezvous for processing.

One way to look at this is to imagine a group of 100 people. Among the group are 10 areas that are rendezvous for each of 10 people. One person at the rendezvous is responsible for communicating with the other ten rendezvous. We will call these peers rendezvous managers. Peer 1 asks rendezvous manager 1 a question. If any of the other eight peers have communicated the answer or the manager knows the answer, it returns the response to peer 1. If manager 1 does not know the answer, it contacts all the rendezvous managers it knows about for an answer.

The manager does not need to know about all of the other managers, just enough that know of others, and so on. In other words, if there is a chain of relationships between the managers that connects all ten, all rendezvous are visible to the first peer. The topology here is that of the small world effect we talked about in Chapter 1, "What Is P2P."

Using the Resolver

Using the resolver is fairly simple, but there are several steps. Listing 3.2 covers just about everything you need to send a query.

Note

The code in Listing 3.2 is from a simple test of the resolver that can be found online at http://www.samspublishing.com.

Create a document with the time, serialize that into an XML document, create a ResolverQuery object, and send it. As you can see, most of the effort is dedicated to building the message while the actual messaging is very simplistic.

Listing 3.2 Example Used to Start a Query

// Create a document with the time
StructuredTextDocument doc = null;
doc = (StructuredTextDocument)
   StructuredDocumentFactory.newStructuredDocument(
     new MimeMediaType("text/xml"),"Pong");
     
Element e = null;
     
long now = System.currentTimeMillis();
     
e = doc.createElement("timestamp 1", format.format( new Date(now)) );
doc.appendChild(e);
String credential = "Sams";
// Create the message;
ResolverQueryMsg message = null;
String xml = serializeDoc(doc);
message = new ResolverQuery( handlerName
              , credential
              , group.getPeerID().toString()
              , xml
              , 1);
System.out.println("Sending query");
// Note that the following may throw a RuntimeException
// if the peer is not found.
resolver.sendQuery(peerID, message);

Processing Responses

The rendezvous peer can operate in several different ways. First, the rendezvous can be given answers by other peers. This is what happens in the discovery process. When a peer does a remote publish of an advertisement, it publishes it to a rendezvous. Any remote query for advertisements in the discovery mechanism causes each rendezvous to look to see if it has that advertisement. If there is no copy of the advertisement, the query is forwarded to other peers.

The query could also cause the rendezvous to contact peers that are not rendezvous. This would occur in the handler. The peers that the rendezvous knows about could be contacted to get an answer. This rendezvous to peer mechanism takes place outside of the resolver mechanism. If none of these peers has an answer, the rendezvous can forward the query to another rendezvous that will repeat the process.

Remember that there is no direct addressing guaranteed in this process. You should use pipes if you want to get a response from a specific peer.

Removing a Handler

When you are no longer interested in receiving answers to queries, unregister your handler. This is very important to do as soon as possible because you could waste time on processing an answer multiple times. The following is the signature to unregister the handler. It simply takes the name of the handler you specified when you registered it:

QueryHandler unregisterHandler( String name )
  • + Share This
  • 🔖 Save To Your Account