📄 resolvertest.java
字号:
/*
* ResolverTest.java
*
*/
package com.sams.jxta.resolverTest;
import java.util.Date;
import net.jxta.resolver.*;
import java.io.StringWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.util.Enumeration;
import java.lang.reflect.InvocationTargetException;
import net.jxta.exception.*;
import net.jxta.protocol.*;
import java.text.SimpleDateFormat;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.exception.PeerGroupException;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.discovery.DiscoveryService;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.impl.peergroup.Platform;
import net.jxta.impl.peergroup.GenericPeerGroup;
import net.jxta.document.Advertisement;
import net.jxta.resolver.QueryHandler;
import net.jxta.document.*;
import net.jxta.protocol.*;
import net.jxta.impl.protocol.*;
import net.jxta.impl.resolver.*;
/**
* This is a quick and simple example to primarly illustrate how to start project jxta
* from an application, and how to create a DiscoveryListener interface
* This is meant as an on going effort, if you can add to the
* example to help others understand, and integrate project jxta,
* feel free to do so, please refer to the "todo" section in README .
*/
public class ResolverTest implements Runnable{
// classInit supplies these
static PeerGroup platformGroup = null;
static PeerGroup netPeerGroup = null;
static PeerGroupAdvertisement groupAdvertisement = null;
private DiscoveryService discovery;
private int myqueryid;
protected PeerGroupAdvertisement pgadv;
protected SimpleDateFormat format = new SimpleDateFormat ("MM, dd, yyyy hh:mm:ss.S");
public ResolverTest() {
}
private void startJxta() {
try {
// create, and Start the default jxta NetPeerGroup
netPeerGroup = PeerGroupFactory.newNetPeerGroup();
} catch (PeerGroupException e) {
// could not instanciate the group, print the stack and exit
System.out.println("fatal error : group creation failure");
e.printStackTrace();
System.exit(1);
}
// this is how to obtain the group advertisement
groupAdvertisement = netPeerGroup.getPeerGroupAdvertisement();
}
// Start the application
public void startApplication(String args[]){
try{
PeerGroup group = netPeerGroup;// This needs to be a smaller group.
ResolverServiceImpl resolver;
String credential = "Sams";
String handlerName = "TestQueryHandler";
String rdvPeer = "Resolver";
resolver = (ResolverServiceImpl)group.getResolverService();
TestQueryHandler handler = new TestQueryHandler(handlerName,credential);
resolver.registerHandler(handlerName, handler);
// 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);
// Return a generic response;
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.
// TODO: Need to discover peers.
/*
resolver.sendQuery("urn:jxta:uuid-59616261646162614A78746150325033F603C339E3AD440596AEAC96F72C13C403",
message);
resolver.sendQuery("urn:jxta:uuid-59616261646162614A78746150325033EFD297B8006348CFA1B2A68169ADDCC403",
message);
*/
// Send query to a specific rendezvous
resolver.sendQuery("urn:jxta:uuid-59616261646162614A78746150325033C2567EF932A64F0DB1DBBBB1F441DFC103",
message);
// Broadcast to all members of the group
//resolver.sendQuery(null, message);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* QueryHandler for resolver test.
*/
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()
/**
* call back method, when messages are received by the ResolverService
* it calls back this method to deal with received responses
* @param response ResolverQueryMsg reponse
*
* @version $Revision: 1.1 $
* @since JXTA 1.0
*/
public void processResponse(ResolverResponseMsg response) {
System.out.println("Received a response");
//String textDoc = response.getResponse();
//System.out.println(textDoc);
System.out.println(((ResolverResponse)response).toString());
}// End of processResponse()
/**
* Process the resolver query, and generate response
* @return GenericResolverMsg Response to the query
* @param query ResolverQueryMsg query
*
* @exception NoResponseException is thrown when the resolver service
* does not have an response and is not interested by the response.
* @exception ResendQueryException is thrown when the resolver service
* does not have a response, but is interested by the response. In that
* case, the resolver service is responsible for forward the response
* to the original peer that has issued the query.
* @exception DiscardQueryException is thrown when the resolver service
* has decided that the query should simply be ignored.
* @exception IOException is thrown when the service resolver was not able to
* process the query
*
* @version $Revision: 1.1 $
* @since JXTA 1.0
*/
public ResolverResponseMsg processQuery(ResolverQueryMsg query) throws NoResponseException, ResendQueryException, DiscardQueryException {
System.out.println("Received a query");
System.out.println(((ResolverQuery)query).toString());
StructuredTextDocument doc = null;
String textDoc = query.getQuery();
try{
doc = (StructuredTextDocument)StructuredDocumentFactory.newStructuredDocument(new MimeMediaType( "text/xml" ),
new ByteArrayInputStream(textDoc.getBytes()) );
}catch(java.io.IOException ioe){
System.err.println("Unable to decode XML for query");
ioe.printStackTrace();
}
// 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
/**
* Utility to convert a document to a string.
*/
public static String serializeDoc(StructuredTextDocument doc) {
StringWriter out = new StringWriter();
try {
doc.sendToWriter(out);
return out.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* This thread basically loops for ever discovering peers
* every minute, and displaying the results.
*/
public void run() {
try {
// Add ourselves as a DiscoveryListener for DiscoveryResponse events
discovery.addDiscoveryListener(new CMSDiscoveryListener());
myqueryid = discovery.getRemoteAdvertisements(null,
DiscoveryService.PEER,
null,null, 1);
while (true) {
// wait a bit before sending a discovery message
try {
Thread.sleep(10 * 1000);
} catch(Exception e) {
}
System.out.println("Sending a Discovery Message");
// look for any peer
myqueryid = discovery.getRemoteAdvertisements(null,
DiscoveryService.PEER,
null,
null, 5);
}
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* by implementing DiscoveryListener we must define this method
* to deal to discovery responses
*/
public void event(DiscoveryEvent ev) {
DiscoveryResponseMsg res = ev.getResponse();
// let's get the responding peer's advertisement
String aRes = res.getPeerAdv();
try {
InputStream is = new ByteArrayInputStream( (aRes).getBytes() );
pgadv = (PeerGroupAdvertisement)AdvertisementFactory.newAdvertisement(new MimeMediaType( "text/xml" ), is);
System.out.println(" [ Got a Discovery Response ["+
res.getResponseCount()+ " elements] ");
} catch (java.io.IOException ioe) {
System.out.println("error parsing remote peer's advertisement");
ioe.printStackTrace();
return;
}
// now out the goodies
Enumeration enum = res.getResponses();
String str=null;
Advertisement adv=null;
while (enum.hasMoreElements()) {
try {
str = (String) enum.nextElement();
// print out the response
// System.out.println(str);
// the following illustrates how to create
// the advertisement object from a response
adv =(Advertisement)
AdvertisementFactory.newAdvertisement(new MimeMediaType("text/xml"), new ByteArrayInputStream(str.getBytes()));
} catch (java.io.IOException e) {
// got a bad response. continue to the next response
System.out.println("error parsing response element");
e.printStackTrace();
continue;
}
}
}
static public void main(String args[]) {
// Initialize
System.out.println("Initializing ResolverTest");
ResolverTest myapp = new ResolverTest();
System.out.println("Starting JXTA");
myapp.startJxta();
// Start the monitor
//Thread thread = new Thread(this);
//thread.start();
System.out.println("Start the application");
myapp.startApplication(args);
}
class CMSDiscoveryListener implements DiscoveryListener {
public void discoveryEvent(DiscoveryEvent e) {
DiscoveryResponseMsg msg = e.getResponse();
System.out.println("QueryValue:'"+msg.getQueryValue()+"'");
//if (myQueryID == e.getQueryID()) {
int advCount = msg.getResponseCount();
Enumeration enum = msg.getResponses();
for ( ; enum.hasMoreElements();) {
Object obj = enum.nextElement();
System.out.println("Type:"+obj.getClass().getName());
}
//}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -