JXTA

net.jxta.impl.discovery
Class DiscoveryServiceImpl

java.lang.Object
  extended by net.jxta.impl.discovery.DiscoveryServiceImpl
All Implemented Interfaces:
EventListener, DiscoveryService, Srdi.SrdiInterface, InternalQueryHandler, Module, RendezvousListener, QueryHandler, SrdiHandler, Service

public class DiscoveryServiceImpl
extends Object
implements DiscoveryService, InternalQueryHandler, RendezvousListener, SrdiHandler, Srdi.SrdiInterface

This Discovery Service implementation provides a mechanism to discover Advertisements using the Resolver service and SRDI.

This implementation uses the standard JXTA Peer Discovery Protocol (PDP).

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).

See Also:
DiscoveryService, DiscoveryQueryMsg, DiscoveryQuery, DiscoveryResponseMsg, DiscoveryResponse, ResolverService, JXTA Protocols Specification : Peer Discovery Protocol

Field Summary
protected  Cm cm
          The cache manager we're going to use to cache jxta advertisements
(package private) static String[] dirname
          adv types
 
Fields inherited from interface net.jxta.discovery.DiscoveryService
ADV, DEFAULT_EXPIRATION, DEFAULT_LIFETIME, GROUP, INFINITE_LIFETIME, NO_EXPIRATION, PEER
 
Fields inherited from interface net.jxta.platform.Module
START_AGAIN_PROGRESS, START_AGAIN_STALLED, START_DISABLED, START_OK
 
Constructor Summary
DiscoveryServiceImpl()
           
 
Method Summary
 void addDiscoveryListener(DiscoveryListener listener)
          Register a Discovery listener.
 void flushAdvertisement(Advertisement adv)
          Removes the specified Advertisement from the cache of locally stored Advertisements.
 void flushAdvertisements(String id, int type)
          Removes the specified Advertisement from the cache of locally stored Advertisements.
 long getAdvExpirationTime(Advertisement adv)
          Returns the maximum duration in milliseconds for which this document will be cached by peers other than the publisher.
 long getAdvExpirationTime(ID id, int type)
          Returns the maximum duration in milliseconds for which this document will be cached by peers other than the publisher.
 long getAdvLifeTime(Advertisement adv)
          Returns the maximum duration in milliseconds for which this document should be kept in local cache.
 long getAdvLifeTime(ID id, int type)
          Returns the maximum duration in milliseconds for which this document should be kept in local cache.
 Advertisement getImplAdvertisement()
          Returns the advertisement for this service.
 Service getInterface()
          Service objects are not manipulated directly to protect usage of the service.
 Enumeration<Advertisement> getLocalAdvertisements(int type, String attribute, String value)
          Retrieve locally stored Advertisements.
 int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold)
          Discover advertisements from remote peers.
 int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold, DiscoveryListener listener)
          Discover advertisements from remote peers.
 void init(PeerGroup pg, ID assignedID, Advertisement impl)
          Initialize the module, passing it its peer group and advertisement.
 void messageSendFailed(PeerID peerid, OutgoingMessageEvent e)
          Resolver calls this method when a failure to send a message to specified peer occurs
 int processQuery(ResolverQueryMsg query)
          Process the resolver query, and generate response it is the responsibility of the handler to send the response

result = processIncomingQuery(query); if (result !

 int processQuery(ResolverQueryMsg query, EndpointAddress srcAddress)
          Process the resolver query, and generate response it is the responsibility of the handler to send the response

result = processIncommingQuery(query); if (result !

 void processResponse(ResolverResponseMsg response)
          Called when messages are received by the ResolverService it calls back this method to deal with received responses
 void processResponse(ResolverResponseMsg response, EndpointAddress srcAddress)
          Called when messages are received by the ResolverService it calls back this method to deal with received responses
 boolean processSrdi(ResolverSrdiMsg message)
          Process the SrdiMessage message, returns true if the message was processed properly
 void publish(Advertisement adv)
          Publish an Advertisement.
 void publish(Advertisement adv, long lifetime, long expiration)
          Publish an Advertisement.
 void pushEntries(boolean all)
          Pushe SRDI entries.
protected  void pushSrdi(ID peer, int type, boolean all)
          push srdi entries
 void remotePublish(Advertisement adv)
          Publish an Advertisement via propagation to other peers on the network.
 void remotePublish(Advertisement adv, long expiration)
          Publish an Advertisement via propagation to other peers on the network.
 void remotePublish(String peerid, Advertisement adv)
          Publish an Advertisement to another peer on the network.
 void remotePublish(String peerid, Advertisement adv, long timeout)
          Publish an Advertisement to another peer on the network.
 boolean removeDiscoveryListener(DiscoveryListener listener)
          Remove a Discovery listener which was previously registered with getRemoteAdvertisements() or addDiscoveryListener().
 void rendezvousEvent(RendezvousEvent event)
          Called when an event occurs for the Rendezvous service
 int startApp(String[] arg)
          Complete any remaining initialization of the module.
 void stopApp()
          Stop a module.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

dirname

static final String[] dirname
adv types


cm

protected Cm cm
The cache manager we're going to use to cache jxta advertisements

Constructor Detail

DiscoveryServiceImpl

public DiscoveryServiceImpl()
Method Detail

getInterface

public Service getInterface()
Service objects are not manipulated directly to protect usage of the service. A Service interface is returned to access the service methods.

Specified by:
getInterface in interface Service
Returns:
Service public interface of the service

getImplAdvertisement

public Advertisement getImplAdvertisement()
Returns the advertisement for this service.

Specified by:
getImplAdvertisement in interface Service
Returns:
Advertisement the advertisement. This is always a ModuleImplAdvertisement.

getRemoteAdvertisements

public int getRemoteAdvertisements(String peer,
                                   int type,
                                   String attribute,
                                   String value,
                                   int threshold)
Discover advertisements from remote peers. This does not normally provide an exhaustive search. Instead it provides a "best efforts" search which will provide a selection of advertisements of matching the search criteria. The selection of advertisements returned may be random or predictable depending upon the network configuration and no particular behaviour should be assumed. In general the narrower the query specified the more exhaustive the responses will be.

Discovery can be performed in two ways :

The scope of advertisements returned can be narrowed by specifying an attribute and value pair. The attribute is a case-sensitive string matching the name of an Advertisement XML tag who's values will be matched by the value. Only a limited number of Advertisement XML fields are indexed. Advertisement.getIndexFields() will return the fields on which you may query for a particular Advertisement type.

The value is a case-insensitive string who's value is matched against the values of attribute fields of Advertisements. The value may be of several forms :

Specified by:
getRemoteAdvertisements in interface DiscoveryService
Parameters:
peer - If provided the query will be forwarded to the specified peer. If null then the query will be propagated through the network to peers with matching Advertisements.
type - Discovery type; PEER, GROUP or ADV.
attribute - indexed element name (see advertisement(s) for a list of indexed fields. A null attribute indicates any advertisement of specified type
value - value of attribute to narrow discovery 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 FooBar , a value of "*bar", "foo*", or "*ooB*", will return the Advertisement
threshold - The maximum number of matching advertisements which be returned by each responding peer. A threshold of 0, and type of PEER has a special behaviour.
Returns:
query ID for this discovery query.

getRemoteAdvertisements

public int getRemoteAdvertisements(String peer,
                                   int type,
                                   String attribute,
                                   String value,
                                   int threshold,
                                   DiscoveryListener listener)
Discover advertisements from remote peers. This does not normally provide an exhaustive search. Instead it provides a "best efforts" search which will provide a selection of advertisements of matching the search criteria. The selection of advertisements returned may be random or predictable depending upon the network configuration and no particular behaviour should be assumed. In general the narrower the query specified the more exhaustive the responses will be.

Discovery can be performed in two ways :

The scope of advertisements returned can be narrowed by specifying an attribute and value pair. The attribute is a case-sensitive string matching the name of an Advertisement XML tag who's values will be matched by the value. Only a limited number of Advertisement XML fields are indexed. Advertisement.getIndexFields() will return the fields on which you may query for a particular Advertisement type.

The value is a case-insensitive string who's value is matched against the values of attribute fields of Advertisements. The value may be of several forms :

Specified by:
getRemoteAdvertisements in interface DiscoveryService
Parameters:
peer - If provided the query will be forwarded to the specified peer. If null then the query will be propagated through the network to peers with matching Advertisements.
type - Discovery type; PEER, GROUP or ADV.
attribute - indexed element name (see Advertisement(s) for a list of indexed fields. A null attribute indicates any advertisement of specified type
value - value of attribute to narrow discovery to. Valid values for this parameter or null (don't care), Exact value, or use of wild card(s) (e.g. if a Advertisement defines FooBar, a value of "*bar", "foo*", or "*ooB*", will return the Advertisement
threshold - The maximum number of matching advertisements which be returned by each responding peer. A threshold of 0, and type of PEER has a special behaviour.
listener - The listener which will be called when advertisement which match this query are discovered or null if no callback is desired.
Returns:
query ID for this discovery query.

getLocalAdvertisements

public Enumeration<Advertisement> getLocalAdvertisements(int type,
                                                         String attribute,
                                                         String value)
                                                  throws IOException
Retrieve locally stored Advertisements. This is an exhaustive search of the locally cached results. All valid known matching results will be returned.

Specified by:
getLocalAdvertisements in interface DiscoveryService
Parameters:
type - Discovery type; PEER, GROUP or ADV.
attribute - indexed element name (see Advertisement(s) for a list of indexed fields. null indicates any advertisement of specified type
value - value of attribute to narrow discovery 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 FooBar , a value of "*bar", "foo*", or "*ooB*", will return the Advertisement
Returns:
Enumeration of stored advertisements.
Throws:
IOException - Thrown if an error occurs during retrieval.

init

public void init(PeerGroup pg,
                 ID assignedID,
                 Advertisement impl)
          throws PeerGroupException
Initialize the module, passing it its peer group and advertisement.

Note: when subclassing one of the existing PeerGroup implementations (which implement Module), it may not be recommended to overload the init method. See the documentation of the PeerGroup class being subclassed.

Specified by:
init in interface Module
Parameters:
pg - The PeerGroup from which this Module can obtain services. If this module is a Service, this is also the PeerGroup of which this module is a service.
assignedID - Identity of Module within group. modules can use it as a the root of their namespace to create names that are unique within the group but predictable by the same module on another peer. This is normally the ModuleClassID which is also the name under which the module is known by other modules. For a group it is the PeerGroupID itself. The parameters of a service, in the Peer configuration, are indexed by the assignedID of that service, and a Service must publish its run-time parameters in the Peer Advertisement under its assigned ID.
impl - The implementation advertisement for this Module. It is permissible to pass null if no implementation advertisement is available. This may happen if the implementation was selected by explicit class name rather than by following an implementation advertisement. Modules are not required to support that style of loading, but if they do, then their documentation should mention it.
Throws:
PeerGroupException - This module failed to initialize.

startApp

public int startApp(String[] arg)
Complete any remaining initialization of the module. The module should be fully functional after startApp() is completed. That is also the opportunity to supply arbitrary arguments (mostly to applications).

If this module is a PeerGroup service, it may be invoked several times depending on its return value.

Specified by:
startApp in interface Module
Parameters:
arg - An array of Strings forming the parameters for this Module.
Returns:
int A status indication which may be one of Module.START_OK, Module.START_AGAIN_PROGRESS, Module.START_AGAIN_STALLED, which indicates partial or complete success, or any other value (negative values are recommended for future compatibility), which indicates failure.

stopApp

public void stopApp()
Stop a module. This may be called any time after init() completes and should not assume that startApp() has been called or completed.

The Module cannot be forced to comply, but in the future we might be able to deny it access to anything after some timeout.

Detach from the resolver

Specified by:
stopApp in interface Module

flushAdvertisements

public void flushAdvertisements(String id,
                                int type)
                         throws IOException
Removes the specified Advertisement from the cache of locally stored Advertisements.

Specified by:
flushAdvertisements in interface DiscoveryService
Parameters:
id - The Advertisement.getID() value of the Advertisement to be removed.
type - Discovery type PEER, GROUP, ADV.
Throws:
IOException - If there is a problem removing the advertisement.

flushAdvertisement

public void flushAdvertisement(Advertisement adv)
                        throws IOException
Removes the specified Advertisement from the cache of locally stored Advertisements.

Specified by:
flushAdvertisement in interface DiscoveryService
Parameters:
adv - Advertisement to remove.
Throws:
IOException - If there is a problem removing the advertisement.

publish

public void publish(Advertisement adv)
             throws IOException
Publish an Advertisement. The Advertisement will expire automatically on the local peer after DEFAULT_LIFETIME and will expire on other peers after DEFAULT_EXPIRATION.

When an Advertisement is published, it is stored, and indexed in the peer's local cache. The Advertisement indexes are also shared with Rendezvous peers. Advertisement indexes may not be shared with other peers immediately, but may be updated as part of a periodic process. The Discovery Service currently publishes index updates every 30 seconds.

Specified by:
publish in interface DiscoveryService
Parameters:
adv - The Advertisement to publish.
Throws:
IOException - When an error occurs during Advertisement publication.

publish

public void publish(Advertisement adv,
                    long lifetime,
                    long expiration)
             throws IOException
Publish an Advertisement. The Advertisement will expire automatically after the specified time. A peer that discovers this advertisement will hold it for about expiration or lifetime milliseconds, whichever is smaller.

When an Advertisement is published, it is stored, and indexed in the peer's local cache. The Advertisement indexes are also shared with Rendezvous peers. Advertisement indexes may not be shared with other peers immediately, but may be updated as part of a periodic process. The Discovery Service currently publishes index updates every 30 seconds.

Specified by:
publish in interface DiscoveryService
Parameters:
adv - The Advertisement to publish.
lifetime - Duration in relative milliseconds that this advertisement will exist.
expiration - Duration in relative milliseconds that this advertisement will be cached by other peers.
Throws:
IOException - When an error occurs during Advertisement publication.

remotePublish

public void remotePublish(Advertisement adv)
Publish an Advertisement via propagation to other peers on the network. This does not result in the advertisement being stored locally. The Advertisement will be published with an expiration time of DEFAULT_EXPIRATION.

Specified by:
remotePublish in interface DiscoveryService
Parameters:
adv - Advertisement to publish.

remotePublish

public void remotePublish(Advertisement adv,
                          long expiration)
Publish an Advertisement via propagation to other peers on the network. This does not result in the advertisement being stored locally.

Specified by:
remotePublish in interface DiscoveryService
Parameters:
adv - The Advertisement to publish.
expiration - Duration in relative milliseconds that this Advertisement will be cached by other peers.

remotePublish

public void remotePublish(String peerid,
                          Advertisement adv)
Publish an Advertisement to another peer on the network. This does not result in the advertisement being stored locally. The Advertisement will be published with an expiration time of DEFAULT_EXPIRATION.

Specified by:
remotePublish in interface DiscoveryService
Parameters:
peerid - The ID of a peer, specifying null results in propagation within the group.
adv - The Advertisement to publish.

processResponse

public void processResponse(ResolverResponseMsg response)
Called when messages are received by the ResolverService it calls back this method to deal with received responses

Specified by:
processResponse in interface QueryHandler
Parameters:
response - ResolverQueryMsg response

processResponse

public void processResponse(ResolverResponseMsg response,
                            EndpointAddress srcAddress)
Called when messages are received by the ResolverService it calls back this method to deal with received responses

Specified by:
processResponse in interface InternalQueryHandler
Parameters:
response - ResolverQueryMsg response
srcAddress - source address

processQuery

public int processQuery(ResolverQueryMsg query)
Process the resolver query, and generate response it is the responsibility of the handler to send the response

 result = processIncomingQuery(query);
 if (result != null) {
   resolver.sendResponse(query.getSrc(), response);
   return ResolverService.OK;
  } else return ResolverService.Repropagate;
 

Specified by:
processQuery in interface QueryHandler
Parameters:
query - ResolverQueryMsg query
Returns:
int status, OK success, Repropagate to indicate a re-propagation is needed.

processQuery

public int processQuery(ResolverQueryMsg query,
                        EndpointAddress srcAddress)
Process the resolver query, and generate response it is the responsibility of the handler to send the response

 result = processIncommingQuery(query);
 if (result != null) {
   resolver.sendResponse(query.getSrc(), response);
   return resolver.OK;
  } else return resolver.Repropagate;
 

Specified by:
processQuery in interface InternalQueryHandler
Parameters:
query - ResolverQueryMsg query
srcAddress - source address
Returns:
int status, OK success, Repropagate to indicate a re-propagation is needed

addDiscoveryListener

public void addDiscoveryListener(DiscoveryListener listener)
Register a Discovery listener. The Discovery listener will be called whenever Advertisement responses are received from remote peers by the Discovery Service.

Specified by:
addDiscoveryListener in interface DiscoveryService
Parameters:
listener - the DiscoveryListener

removeDiscoveryListener

public boolean removeDiscoveryListener(DiscoveryListener listener)
Remove a Discovery listener which was previously registered with getRemoteAdvertisements() or addDiscoveryListener().

Specified by:
removeDiscoveryListener in interface DiscoveryService
Parameters:
listener - The listener to be removed.
Returns:
true if the listener was successfully removed, false otherwise

remotePublish

public void remotePublish(String peerid,
                          Advertisement adv,
                          long timeout)
Publish an Advertisement to another peer on the network. This does not result in the advertisement being stored locally.

Specified by:
remotePublish in interface DiscoveryService
Parameters:
peerid - id of a peer, specifying null results in a propagate within the group
adv - The Advertisement to publish.
timeout - Duration in relative milliseconds that this Advertisement will be cached by other peers.

getAdvExpirationTime

public long getAdvExpirationTime(ID id,
                                 int type)
Returns the maximum duration in milliseconds for which this document will be cached by peers other than the publisher. This value is either the stored lifetime or the remaining lifetime of the document, whichever is less.

Specified by:
getAdvExpirationTime in interface DiscoveryService
Parameters:
id - Document ID, Peer ID, or PeerGroup ID
type - Discovery type PEER, GROUP, ADV
Returns:
The number of milliseconds that other peers will be told to retain this Advertisement in their local caches. -1 is returned if the Advertisement is not known or already expired.

getAdvLifeTime

public long getAdvLifeTime(ID id,
                           int type)
Returns the maximum duration in milliseconds for which this document should be kept in local cache.

Specified by:
getAdvLifeTime in interface DiscoveryService
Parameters:
id - Document ID, Peer ID, or PeerGroup ID
type - Discovery type PEER, GROUP, ADV
Returns:
The number of milliseconds this Advertisement will remain in the local cache unless refreshed before that time. -1 is returned if the Advertisement is not known or already expired.

getAdvExpirationTime

public long getAdvExpirationTime(Advertisement adv)
Returns the maximum duration in milliseconds for which this document will be cached by peers other than the publisher. This value is either the stored lifetime or the remaining lifetime of the document, whichever is less.

Specified by:
getAdvExpirationTime in interface DiscoveryService
Parameters:
adv - Advertisement
Returns:
The number of milliseconds that other peers will be told to retain this Advertisement in their local caches. -1 is returned if the Advertisement is not known or already expired.

getAdvLifeTime

public long getAdvLifeTime(Advertisement adv)
Returns the maximum duration in milliseconds for which this document should be kept in local cache.

Specified by:
getAdvLifeTime in interface DiscoveryService
Parameters:
adv - Advertisement
Returns:
The number of milliseconds this Advertisement will remain in the local cache unless refreshed before that time. -1 is returned if the Advertisement is not known or already expired.

processSrdi

public boolean processSrdi(ResolverSrdiMsg message)
Process the SrdiMessage message, returns true if the message was processed properly

Specified by:
processSrdi in interface SrdiHandler
Parameters:
message - Description of the Parameter
Returns:
true if the message was processed properly

messageSendFailed

public void messageSendFailed(PeerID peerid,
                              OutgoingMessageEvent e)
Resolver calls this method when a failure to send a message to specified peer occurs

Specified by:
messageSendFailed in interface SrdiHandler
Parameters:
peerid - peerid failure occured on

pushEntries

public void pushEntries(boolean all)
Pushe SRDI entries.

Specified by:
pushEntries in interface Srdi.SrdiInterface
Parameters:
all - if true then push all entries otherwise just push those which have changed since the last push.

pushSrdi

protected void pushSrdi(ID peer,
                        int type,
                        boolean all)
push srdi entries

Parameters:
all - if true push all entries, otherwise just deltas
peer - peer id
type - if true sends all entries

rendezvousEvent

public void rendezvousEvent(RendezvousEvent event)
Called when an event occurs for the Rendezvous service

Specified by:
rendezvousEvent in interface RendezvousListener
Parameters:
event - the rendezvous event

JXSE