📄 discoveryserviceimpl.java
字号:
/*
* Copyright (c) 2001 Sun Microsystems, Inc. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Sun Microsystems, Inc. for Project JXTA."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA",
* nor may "JXTA" appear in their name, without prior written
* permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of Project JXTA. For more
* information on Project JXTA, please see
* <http://www.jxta.org/>.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*
* $Id: DiscoveryServiceImpl.java,v 1.33 2002/06/18 20:45:58 hamada Exp $
*/
package net.jxta.impl.discovery;
import java.lang.reflect.Array;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import net.jxta.service.Service;
import net.jxta.discovery.DiscoveryService;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.resolver.ResolverService;
import net.jxta.resolver.QueryHandler;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.StructuredDocument;
import net.jxta.document.StructuredTextDocument;
import net.jxta.document.MimeMediaType;
import net.jxta.document.Document;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.protocol.ModuleImplAdvertisement;
import net.jxta.protocol.PeerAdvertisement;
import net.jxta.protocol.ResolverQueryMsg;
import net.jxta.protocol.ResolverResponseMsg;
import net.jxta.peergroup.PeerGroup;
import net.jxta.credential.Credential;
import net.jxta.credential.AuthenticationCredential;
import net.jxta.membership.Authenticator;
import net.jxta.membership.MembershipService;
import net.jxta.exception.PeerGroupException;
import net.jxta.exception.NoResponseException;
import net.jxta.exception.ServiceNotFoundException;
import net.jxta.exception.ResendQueryException;
import net.jxta.exception.DiscardQueryException;
import net.jxta.impl.protocol.DiscoveryQuery;
import net.jxta.impl.protocol.DiscoveryResponse;
import net.jxta.impl.protocol.ResolverQuery;
import net.jxta.impl.protocol.ResolverResponse;
import net.jxta.impl.cm.Cm;
/**
* DiscoveryService Service provides a mechanism to discover peers within the
* horizon of the resolver service. The horizon is normally restricted to the
* group's boundaries but this is not an absolute requirement. Use of the
* resolver service is not an absolute requirement either for a discovery
* service, but this is what this is part of the platform and
* default net peer group protocol set, which this code implements.
*
* The DiscoveryService service also provides a way to obtain information
* from a specified peer and request other peer advertisements, this
* method is particularly useful in the case of a portal where new
* relationships may be established starting from a predetermined peer
* (perhaps described in address book, or through an invitation)
*
* @since 1.0
*/
public class DiscoveryServiceImpl implements DiscoveryService, QueryHandler {
private final static Category LOG =
Category.getInstance(DiscoveryServiceImpl.class.getName());
private static int qid = 0;
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
/**
* The cache manager we're going to use to cache jxta advertisements
*/
protected Cm cm;
protected String[] dirname ={"Peers","Groups","Adv"};
private ResolverService resolver;
private PeerGroup group = null;
private String localPeerId = null;
private long seed = System.currentTimeMillis();
private Vector listeners = new Vector();
private Hashtable listenerTable = new Hashtable();
private ModuleImplAdvertisement implAdvertisement = null;
private String localPeerAdvStr = null;
private String handlerName = null;
private boolean lastIsRdv = false;
private MembershipService membership = null;
private Credential credential = null;
private MimeMediaType textXml = new MimeMediaType("text/xml");
private StructuredDocument credentialDoc = null;
private void updatePeerAdvStr() {
boolean newIsRdv = group.isRendezvous();
if (lastIsRdv != newIsRdv) {
localPeerAdvStr = advToString(group.getPeerAdvertisement());
lastIsRdv = newIsRdv;
}
}
/**
* Default constructor
*/
public DiscoveryServiceImpl() { }
/**
* Service objects are not manipulated directly to protect usage
* of the service. A Service interface is returned to access the service
* methods.
*
* @return Service public interface of the service
* @since JXTA 1.0
*/
public Service getInterface() {
return new DiscoveryServiceInterface(this);
}
/**
* Returns the advertisement for that service.
*
* @return Advertisement the advertisement.
* @since JXTA 1.0
*/
public Advertisement getImplAdvertisement() {
return implAdvertisement;
}
/**
* This method discovers PeerAdvertisements, GroupAdvertisements and
* jxta Advertisements. jxta Advertisements are documents that describe
* pipes, services, etc. The discovery scope can be narrowed down
* firstly by Name and Value pair where the match is an exact match,
* secondly by setting a upper limit where the responding peer will not
* exceed. DiscoveryServiceImpl can be performed in two ways 1. by
* specifying a null peerid, the discovery message is propagated on the
* local sub-net utilizing ip multicast. In addition to the multicast
* it is also propagated to rendezvous points. 2. by passing a peerid,
* the EndpointRouter will attempt to resolve destination peer's
* endpoints or route the message to other routers in attempt to reach
* the peer.
*
*@param attribute attribute name to narrow disocvery to
* Valid values for this parameter are null (don't care), or exact
* element name in the advertisement of interest (e.g. "Name")
*@param value value of attribute to narrow disocvery to
* valid values for this parameter are null (don't care), Exact value,
* or use of wild card(s) (e.g. if a Advertisement defines
* <Name>FooBar</name>, a value of "*bar", "foo*", or "*ooB*", will
* return the Advertisement
*@param threshold the upper limit of responses from one peer
*@param peerid id of a peer, specifying null results in a
* propagate within the group
*@param type Discovery type PEER, GROUP, ADV
*@param listener the listener which will be called back with found
* advertisements.
*@since JXTA 1.0
*/
public int getRemoteAdvertisements(String peer,
int type,
String attribute,
String value,
int threshold) {
// Just in case someone calls this before we've been started...
// Pretend the query got lost.
if (resolver == null) return nextQid();
updatePeerAdvStr();
DiscoveryQuery dquery = new DiscoveryQuery(type,
localPeerAdvStr,
attribute,
value,
threshold);
if ((attribute != null) && (value != null)) {
dquery.setAttr(attribute);
dquery.setValue(value);
if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("sending query: " + attribute + " = " + value);
}
// Private copy for thread safety
int myQueryID = nextQid();
ResolverQuery query = new ResolverQuery(handlerName,
credentialDoc,
localPeerId,
dquery.toString(),
myQueryID);
resolver.sendQuery(peer, query);
return myQueryID;
}
public int getRemoteAdvertisements(String peer,
int type,
String attribute,
String value,
int threshold,
DiscoveryListener listener) {
// Just in case someone calls this before we've been started...
// Pretend the query got lost.
if (resolver == null) return nextQid();
updatePeerAdvStr();
DiscoveryQuery dquery = new DiscoveryQuery(type,
localPeerAdvStr,
attribute,
value,
threshold);
if ((attribute != null) && (value != null)) {
dquery.setAttr(attribute);
dquery.setValue(value);
if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("sending query: " + attribute + " = " + value);
}
// Private copy for thread safety
int myQueryID = nextQid();
if (listener != null)
listenerTable.put(new Integer(myQueryID), listener);
ResolverQuery query = new ResolverQuery(handlerName,
credentialDoc,
localPeerId,
dquery.toString(),
myQueryID);
resolver.sendQuery(peer, query);
return myQueryID;
}
/**
* Retrieve Stored Peer, Group, and General Advertisements
*
*@param type Discovery type PEER, GROUP, ADV
*@param attribute attribute name to narrow disocvery to
* Valid values for this parameter are null (don't care), or exact
* element name in the advertisement of interest (e.g. "Name")
*@param value value of attribute to narrow disocvery to
* valid values for this parameter are null (don't care), Exact value,
* or use of wild card(s) (e.g. if a Advertisement defines
* <Name>FooBar</name>, a value of "*bar", "foo*", or "*ooB*", will
* return the Advertisement
*@return Enumeration of stored
* advertisements/structured documents
*@exception IOException - If an I/O error occurs
*@since JXTA 1.0
*/
public Enumeration getLocalAdvertisements(int type,
String attribute,
String value) throws IOException {
if ((type > 2) || (type < 0)) {
throw new IllegalArgumentException("Unknown Advertisement type");
}
return (search(type,
attribute,
value,
Integer.MAX_VALUE,
false,
null).elements());
}
// methods we must implement by implementing
// Service ,QueryHandler
/**
* Returns the group to which this service is attached.
*
* @return PeerGroup the group
* @since
*/
public PeerGroup getGroup() {
return group;
}
/**
* Supply arguments and starts this service if it hadn't started by itself.
*
* Currently this service starts by itself and does not expect
* arguments.
*
* @param arg A table of strings arguments.
* @return int status indication.
* @since
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -