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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020