net.jini.discovery
Class LookupDiscovery

java.lang.Object
  extended by net.jini.discovery.LookupDiscovery
All Implemented Interfaces:
DiscoveryGroupManagement, DiscoveryManagement

public class LookupDiscovery
extends Object
implements DiscoveryManagement, DiscoveryGroupManagement

This class is a helper utility class that encapsulates the functionality required of an entity that wishes to employ multicast discovery to find lookup services located within the entity's "multicast radius" (roughly, the number of hops beyond which neither the multicast requests from the entity, nor the multicast announcements from the lookup service, will propagate). This class helps make the process of acquiring references to lookup services - based on no information other than lookup service group membership - much simpler for both services and clients.

Author:
Sun Microsystems, Inc.
See Also:
ServiceRegistrar, DiscoveryChangeListener, DiscoveryManagement, DiscoveryGroupManagement, DiscoveryListener, DiscoveryEvent, DiscoveryPermission
Implementation Specifics:
The following implementation-specific items are discussed below:

Configuring LookupDiscovery

This implementation of LookupDiscovery supports the following configuration entries; where each configuration entry name is associated with the component name net.jini.discovery.LookupDiscovery. Note that the configuration entries specified here are specific to this implementation of LookupDiscovery. Unless otherwise stated, each entry is retrieved from the configuration only once per instance of this utility, where each such retrieval is performed in the constructor.

discoveryConstraints
  Type: MethodConstraints
  Default: null
  Description: Constraints to apply to the multicast request, multicast announcement and unicast discovery protocols. Multicast request constraints are derived by calling getConstraints on the obtained MethodConstraints instance with a Method object for the multicastRequest method; multicast announcement and unicast discovery constraints are similarly obtained by passing Method objects for the multicastAnnouncement and unicastDiscovery methods, respectively. A null value is interpreted as mapping all methods to empty constraints.

This class supports the use of the following constraint types to control discovery behavior:

  • DiscoveryProtocolVersion: this constraint can be used to control which version(s) of the multicast request, multicast announcement and unicast discovery protocols are used.
  • MulticastMaxPacketSize: this constraint can be used to control the maximum size of multicast request packets to send; it can also be used to specify the size of the buffer used to receive incoming multicast announcement packets.
  • MulticastTimeToLive: this constraint can be used to control the time to live (TTL) value set on outgoing multicast request packets.
  • UnicastSocketTimeout: this constraint can be used to control the read timeout set on sockets over which unicast discovery is performed.
  • ConnectionRelativeTime: this constraint can be used to control the relative connection timeout set on sockets over which unicast discovery is performed.
  • ConnectionAbsoluteTime: this constraint can be used to control the absolute connection timeout set on sockets over which unicast discovery is performed.
Constraints other than those listed above are passed on to the underlying implementations of versions 1 and 2 of the discovery protocols.
finalMulticastRequestInterval
  Type: long
  Default: 2*60*1000 (2 minutes)
  Description: With respect to when this utility is started, as well as when the set of groups to discover is changed, this entry represents the number of milliseconds to wait after sending the n-th multicast request where n is equal to the value of the multicastRequestMax entry of this component.
initialMulticastRequestDelayRange
  Type: long
  Default: 0 milliseconds
  Description: With respect to when this utility is started, this entry controls how long to wait before sending out the first multicast request. If the value is positive, the first request will be delayed by a random value between 0 and initialMulticastRequestDelayRange milliseconds. Subsequent request intervals are controlled by the multicastRequestInterval entry. Note that this entry only has effect when this utility is initialized. The first multicast request is not delayed if the groups to discover are subsequently changed.
multicastAnnouncementInterval
  Type: long
  Default: 2*60*1000 (2 minutes)
  Description: A lookup service will send out multicast packets announcing its existence every N milliseconds; for some value of N. The value of this entry controls how often this utility examines the multicast announcements from previously discovered lookup services for liveness.
multicastInterfaceRetryInterval
  Type: int
  Default: 5*60*1000 (5 minutes)
  Description: With respect to any network interface this utility is configured to use to send and receive multicast packets (see entry multicastInterfaces), if failure is encountered upon the initial attempt to set the interface or join the desired multicast group, this utility will retry the failed interface every multicastInterfaceRetryInterval milliseconds until success is encountered.
multicastInterfaces
  Type: NetworkInterface[]
  Default: new NetworkInterface[]   {all currently supported interfaces}
  Description: Each network interface that is represented by an element in the array corresponding to this configuration item will be used to send and receive multicast packets when this utility is participating in the multicast discovery process. When not set, this utility will use all of the network interfaces in the system. When this entry is set to a zero length array, multicast discovery is effectively disabled. And when set to null, the interface to which the operating system defaults will be used.
multicastRequestHost
  Type: String
  Default: InetAddress.getLocalHost().getHostAddress()
  Description: This entry specifies the host name to include in multicast requests if participating in version 2 of the multicast request protocol. The name cannot be null.
multicastRequestInterval
  Type: long
  Default: 5000
  Description: With respect to when this utility is started, as well as when the set of groups to discover is changed, this entry represents the number of milliseconds to wait after sending the n-th multicast request, and before sending the (n+1)-st request, where n is less than the value of the multicastRequestMax entry of this component.
multicastRequestMax
  Type: int
  Default: 7
  Description: The maximum number multicast requests to send when this utility is started for the first time, and whenever the groups to discover is changed.
registrarPreparer
  Type: ProxyPreparer
  Default: new BasicProxyPreparer()
  Description: Preparer for the proxies to the lookup services that are discovered and used by this utility.

This preparer should perform all operations required to use a newly received proxy to a lookup service, which may including verifying trust in the proxy, granting permissions, and setting constraints.

The following methods of the ServiceRegistrar returned by this preparer are invoked by this implementation of LookupDiscovery:

taskManager
  Type: TaskManager
  Default: new TaskManager(15, (15*1000), 1.0f)
  Description: The object that pools and manages the various threads executed by this utility. The default manager creates a maximum of 15 threads, waits 15 seconds before removing idle threads, and uses a load factor of 1.0 when determining whether to create a new thread. This object should not be shared with other components in the application that employs this utility.
unicastDelayRange
  Type: long
  Default: 0 milliseconds
  Description: Controls how long this utility will wait before sending out unicast discovery requests. If the value is positive, any unicast discovery request that it initiates will be delayed by a random value between 0 and unicastDelayRange milliseconds. A typical use of this entry would be to achieve a more uniform distribution of unicast discovery requests to a lookup service, when a large number of LookupDiscovery instances simultaneously receive multicast announcements from the lookup service.
wakeupManager
  Type: WakeupManager
  Default: new WakeupManager(new WakeupManager.ThreadDesc(null,true))
  Description: Object used to schedule unicast discovery requests that are delayed using the unicastDelayRange configuration entry of this utility. This entry is processed only if unicastDelayRange has a positive value.

Logging

This implementation of LookupDiscovery uses the Logger named net.jini.discovery.LookupDiscovery to log information at the following logging levels:

net.jini.discovery.LookupDiscovery
Level Description
SEVERE when this utility is configured to use either the default network interface assigned by the system, or a specific list of network interfaces, if one of those interfaces is bad or not configured for multicast, or if a runtime exception occurs while either sending multicast requests, or while configuring one of the interfaces to receive multicast announcements, that fact will be logged at this level
INFO when any exception other than an InterruptedIOException, InterruptedException or UnsupportedConstraintException occurs in a thread or task while attempting to marshal an outgoing multicast request
INFO when any exception other than an InterruptedIOException or SocketTimeoutException occurs in a non-interrupted thread while attempting to receive an incoming multicast packet
INFO when any exception other than an InterruptedIOException occurs while attempting unicast discovery
INFO when this utility is configured to use either the default network interface assigned by the system, or a specific list of network interfaces, with respect to any such interface, if failure is encountered upon the initial attempt to set the interface or join the desired multicast group, the interface will be periodically retried, and successful recovery will be logged at this level
INFO when any exception occurs while attempting to prepare a proxy
CONFIG when the multicastInterfaces entry is configured to be null, multicast packets will be sent and received through the default network interface assigned by the system, and that fact will be logged at this level
CONFIG when the multicastInterfaces entry is configured to be a zero length array, multicast discovery will be disabled, and and that fact will be logged at this level
CONFIG when the multicastInterfaces entry contains a specific list of network interfaces, multicast packets will be sent and received through only the network interfaces contained in that list, and those interfaces will be logged at this level
CONFIG when the multicastInterfaces entry is excluded from the configuration, multicast packets will be sent and received through all interfaces in the system, and those interfaces will be logged at this level
FAILED when an UnknownHostException occurs while determining the multicastRequestHost, but the caller does not have permissions to retrieve the local host name. The original UnknownHostException with the host name information is logged
HANDLED when this utility is configured to use all network interfaces enabled in the system, if one of those interfaces is bad or not configured for multicast, or if a runtime exception occurs while either sending multicast requests, or while configuring one of the interfaces to receive multicast announcements, that fact will be logged at this level
HANDLED when any exception occurs while attempting to unmarshal an incoming multicast announcement
HANDLED when an UnsupportedConstraintException occurs while marshalling an outgoing multicast request, indicating that the provider that threw the exception will not be used for encoding that request
HANDLED when an IOException occurs upon attempting to close the socket after the thread that listens for multicast responses is asked to terminate
HANDLED when an exception is handled during unicast discovery
FINE when this utility is configured to use all network interfaces enabled in the system, with respect to any such interface, if failure is encountered upon the initial attempt to set the interface or join the desired multicast group, the interface will be periodically retried, and successful recovery will be logged at this level
FINEST whenever any thread or task is started
FINEST whenever any thread (except the Notifier thread) or task completes successfully
FINEST whenever a discovered, discarded, or changed event is sent
FINEST whenever a proxy is prepared


Nested Class Summary
private static class LookupDiscovery.AnnouncementInfo
          Holder class for the time and sequence number of the last received announcement.
private  class LookupDiscovery.AnnouncementListener
          Thread that listens for multicast announcements from lookup services.
private  class LookupDiscovery.AnnouncementTimerThread
          This thread monitors the multicast announcements sent from the lookup service(s) that have already been discovered by this class, looking for indications that those announcements have terminated.
private static class LookupDiscovery.CheckGroupsMarker
          Marker object placed in pendingDiscoveries set to indicate to UnicastDiscoveryTask that the groups of the lookup service which sent the contained announcement need to be verified.
private static class LookupDiscovery.CheckReachabilityMarker
          Marker object placed in pendingDiscoveries set to indicate to UnicastDiscoveryTask that reachability of the lookup service which sent the contained unicast response needs to be verified.
private  class LookupDiscovery.DecodeAnnouncementTask
          Task which decodes received multicast announcement packets.
private  class LookupDiscovery.Notifier
          Thread that retrieves data structures of type NotifyTask from a queue and, based on the contents of the data structure, sends the appropriate event (discovered/discarded/changed) to each registered listener.
private static class LookupDiscovery.NotifyTask
          Data structure containing task data processed by the Notifier Thread
private  class LookupDiscovery.Requestor
          Thread that periodically sends out multicast requests for a limited period of time, and then exits.
private  class LookupDiscovery.ResponseListener
          Thread that listens for multicast responses to the multicast requests sent out by the Requestor Thread class.
private  class LookupDiscovery.UnicastDiscoveryTask
          Task which retrieves elements from the set of pendingDiscoveries and performs the appropriate processing based on the object type of the element.
 
Field Summary
static String[] ALL_GROUPS
          Convenience constant used to request that attempts be made to discover all lookup services that are within range, and which belong to any group.
private  LookupDiscovery.AnnouncementListener announceeThread
          Thread that handles incoming multicast announcements.
private  LookupDiscovery.AnnouncementTimerThread announcementTimerThread
          Thread that monitors multicast announcements from already-discovered lookup services and, upon determining that those announcements have stopped, queues a reachability test with the UnicastDiscoveryTask which will ultimately result in the lookup service being discarded if the reachability test indicates that the lookup service is actually down.
private static int CHANGED
           
private static String COMPONENT_NAME
           
private static int DEFAULT_MAX_PACKET_SIZE
          Default maximum size of multicast packets to send and receive.
private static int DEFAULT_MULTICAST_TTL
          Default time to live value to use for sending multicast packets.
private static int DEFAULT_SOCKET_TIMEOUT
          Default timeout to set on sockets used for unicast discovery.
private static int DISCARDED
           
private static int DISCOVERED
          Constants used to tell the notifierThread the type of event to send
private  WakeupManager discoveryWakeupMgr
           
private  long finalMulticastRequestInterval
           
private  Set groups
          The groups to discover.
private  long initialMulticastRequestDelayRange
           
private  boolean initialRequestorStarted
           
private  boolean isDefaultWakeupMgr
           
private  ArrayList listeners
          Set of listeners to be sent discovered/discarded/changed events.
private static Logger logger
           
private static int MAX_N_TASKS
          Maximum number of concurrent tasks that can be run in any task manager created by this class.
private  DiscoveryConstraints multicastAnnouncementConstraints
           
private  long multicastAnnouncementInterval
           
private  DiscoveryConstraints multicastRequestConstraints
           
private  String multicastRequestHost
           
private  long multicastRequestInterval
           
private  int multicastRequestMax
           
private  int nicRetryInterval
           
private  NetworkInterface[] nics
           
private static int NICS_USE_ALL
          Constants used to indicate the set of network interfaces being used
private static int NICS_USE_LIST
           
private static int NICS_USE_NONE
           
private static int NICS_USE_SYS
           
private  int nicsToUse
          Flag that indicates how the set of network interfaces was configured
static String[] NO_GROUPS
          Convenience constant used to request that discovery by group membership be halted (or not started, if the group discovery mechanism is simply being instantiated).
private  LookupDiscovery.Notifier notifierThread
          Thread that handles pending notifications.
private  Set pendingDiscoveries
          Set that takes one of the following: Socket (discovery from multicast request/response exchange) LookupLocator (discovery from multicast announcement) CheckGroupsMarker (discarded/changed from announcement) CheckReachabilityMarker (announcements stopped, tests reachability) Each element of this set represents a potential (or pending) discovered, discarded, or changed event.
private  LinkedList pendingNotifies
          Notifications to be sent to listeners.
private  Discovery protocol2
           
private  InvocationConstraints rawUnicastDiscoveryConstraints
           
private  HashMap regInfo
          Map from ServiceID to multicast announcement time stamps; used by the process that monitors multicast announcements from already-discovered lookup services, and determines when those announcements have stopped.
private  ProxyPreparer registrarPreparer
           
private  Map registrars
          Map from ServiceID to UnicastResponse.
private  Collection requestors
          Collection that contains instances of the Requestor Thread class, each of which participate in multicast discovery by periodically sending out multicast discovery requests for a finite period of time.
private  LookupDiscovery.ResponseListener respondeeThread
          Thread that manages incoming multicast responses.
private  SecurityContext securityContext
          Security context that contains the access control context to restore for callbacks, etc.
private  TaskManager taskManager
          Task manager for running UnicastDiscoveryTasks and DecodeAnnouncementTasks.
private  boolean terminated
          Flag indicating whether or not this class is still functional.
private  List tickets
           
private  long unicastDelayRange
           
 
Constructor Summary
LookupDiscovery(String[] groups)
          Construct a new lookup discovery object, set to discover the given set of groups.
LookupDiscovery(String[] groups, Configuration config)
          Constructs a new lookup discovery object, set to discover the given set of groups, and having the given Configuration.
 
Method Summary
 void addDiscoveryListener(DiscoveryListener l)
          Register a listener as interested in receiving DiscoveryEvent notifications.
 void addGroups(String[] newGroups)
          Add a set of groups to the set to be discovered.
private  void addNotify(ArrayList notifies, Map groupsMap, int eventType)
          Add a notification task to the pending queue, and start an instance of the Notifier thread if one isn't already running.
private  void beginDiscovery(String[] groups, Configuration config)
          Using the given Configuration, initializes the current instance of this utility, and initiates the discovery process for the given set of groups.
private  void checkAnnouncementConstraints(MulticastAnnouncement ann)
           
private static void checkGroups(String[] groups)
          Determines if the caller has discovery permission for each group.
private static String[] collectionToStrings(Collection c)
          Converts a collection to an array of strings.
private  MulticastAnnouncement decodeMulticastAnnouncement(DatagramPacket pkt)
          Decodes received multicast announcement packet.
private  Map deepCopy(HashMap groupsMap)
          Creates and returns a deep copy of the input parameter.
 void discard(ServiceRegistrar reg)
          Discard a registrar from the set of registrars already discovered.
private  UnicastResponse doUnicastDiscovery(Socket socket, DiscoveryConstraints unicastDiscoveryConstraints)
           
private  UnicastResponse doUnicastDiscovery(Socket socket, DiscoveryConstraints unicastDiscoveryConstraints, Discovery disco)
          Performs unicast discovery over given socket based on protocol in use, applying configured security constraints (if any).
private  DatagramPacket[] encodeMulticastRequest(MulticastRequest req)
          Encodes outgoing multicast requests based on protocol in use, applying configured security constraints (if any).
private  String[] getActualGroups(ServiceRegistrar reg)
          This method retrieves from the given ServiceRegistrar, the current groups in which that registrar is a member.
private  Discovery getDiscovery(int version)
          Returns Discovery instance for the given version, or throws DiscoveryProtocolException if the version is unsupported.
 String[] getGroups()
          Return the set of group names this LookupDiscovery instance is trying to discover.
private static String getLocalHost()
          Returns the local host name.
 ServiceRegistrar[] getRegistrars()
          Returns an array of instances of ServiceRegistrar, each corresponding to a proxy to one of the currently discovered lookup services.
private  ServiceID[] getServiceIDs()
          Returns the service IDs of the lookup service(s) discovered to date.
private static boolean groupSetsEqual(String[] groupSet0, String[] groupSet1)
          Determines if two sets of registrar member groups have identical contents.
private  boolean groupsOverlap(String[] possibilities)
          Indicate whether any of the group names in the given array match any of the groups of interest.
private  void init(Configuration config)
           
private  Map mapRegToGroups(ServiceRegistrar reg, String[] curGroups)
          Convenience method that creates and returns a mapping of a single ServiceRegistrar instance to a set of groups.
private  void maybeAddNewRegistrar(UnicastResponse resp)
          If the lookup service associated with the given UnicastResponse is not in the set of already-discovered lookup services, this method adds it to that set, and each registered listener is notified.
private  void maybeDiscardRegistrars()
          Determine if any of the already-discovered registrars are no longer members of any of the groups to discover, and discard those registrars that are no longer members of any of those groups.
private  void maybeSendEvent(UnicastResponse response, String[] newGroups)
          After a possible change in the member groups of the ServiceRegistrar corresponding to the given UnicastResponse parameter, this method determines whether or not the registrar's member groups have changed in such a way that either a changed event or a discarded event is warranted.
private  void notifyOnGroupChange(ServiceRegistrar reg, String[] oldGroups, String[] newGroups)
          After a possible change in the member groups of the given ServiceRegistrar parameter, this method compares the registrar's original set of member groups to its new set of member groups.
private  void nukeThreads()
          Terminates (interrupts) all currently-running threads.
private static void prepareSocket(Socket s, DiscoveryConstraints dc)
           
private static boolean registrarsEqual(UnicastResponse resp1, UnicastResponse resp2)
          Returns true if the registrars contained in the given (possibly null) UnicastResponse instances are equals() to one another.
 void removeDiscoveryListener(DiscoveryListener l)
          Indicate that a listener is no longer interested in receiving DiscoveryEvent notifications.
 void removeGroups(String[] oldGroups)
          Remove a set of groups from the set to be discovered.
private  boolean removeGroupsInt(String[] oldGroups)
          Remove the specified groups from the set of groups to discover, and return true if any were actually removed.
private  void requestGroups(Collection req)
          Called at startup and whenever the set of groups to discover is changed.
private  void restoreContextAddTask(TaskManager.Task t)
           
private  WakeupManager.Ticket restoreContextScheduleRunnable(LookupDiscovery.UnicastDiscoveryTask t)
           
private  void sendChanged(ServiceRegistrar reg, String[] curGroups)
          Convenience method that sends a changed event containing only one registrar to all registered listeners that are interested in such events.
private  void sendDiscarded(ServiceRegistrar reg, String[] curGroups)
          Convenience method that sends a discarded event containing only one registrar to all registered listeners.
private static void sendPacket(MulticastSocket mcSocket, DatagramPacket[] packet)
          Sends the given packet data on the given MulticastSocket through the network interface that is currently set.
private  void sendPacketByNIC(MulticastSocket mcSocket, DatagramPacket[] packet)
          Sends the given packet data on the given MulticastSocket through each of the network interfaces corresponding to elements of the array configured when this utility was constructed.
 void setGroups(String[] newGroups)
          Change the set of groups to be discovered to correspond to the given set.
 void terminate()
          Terminate the discovery process.
private  void terminateTaskMgr()
          This method removes all pending and active tasks from the TaskManager for this instance.
private  void testArrayForNullElement(String[] groupArray)
          This method is used by the public methods of this class that are specified to throw a NullPointerException when the given array of group names contains one or more null elements; in which case, this method throws a NullPointerException which should be allowed to propagate outward.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

COMPONENT_NAME

private static final String COMPONENT_NAME
See Also:
Constant Field Values

logger

private static final Logger logger

ALL_GROUPS

public static final String[] ALL_GROUPS
Convenience constant used to request that attempts be made to discover all lookup services that are within range, and which belong to any group. Must define this constant here as well as in DiscoveryGroupManagement for compatibility with earlier releases.


NO_GROUPS

public static final String[] NO_GROUPS
Convenience constant used to request that discovery by group membership be halted (or not started, if the group discovery mechanism is simply being instantiated). Must define this constant here as well as in DiscoveryGroupManagement for compatibility with earlier releases.


MAX_N_TASKS

private static final int MAX_N_TASKS
Maximum number of concurrent tasks that can be run in any task manager created by this class.

See Also:
Constant Field Values

DEFAULT_MAX_PACKET_SIZE

private static final int DEFAULT_MAX_PACKET_SIZE
Default maximum size of multicast packets to send and receive.

See Also:
Constant Field Values

DEFAULT_MULTICAST_TTL

private static final int DEFAULT_MULTICAST_TTL
Default time to live value to use for sending multicast packets.

See Also:
Constant Field Values

DEFAULT_SOCKET_TIMEOUT

private static final int DEFAULT_SOCKET_TIMEOUT
Default timeout to set on sockets used for unicast discovery.

See Also:
Constant Field Values

terminated

private boolean terminated
Flag indicating whether or not this class is still functional.


listeners

private ArrayList listeners
Set of listeners to be sent discovered/discarded/changed events.


groups

private Set groups
The groups to discover. Empty set -- NO_GROUPS, null -- ALL_GROUPS


registrars

private Map registrars
Map from ServiceID to UnicastResponse.


pendingDiscoveries

private Set pendingDiscoveries
Set that takes one of the following:

Each element of this set represents a potential (or pending) discovered, discarded, or changed event. Instances of UnicastDiscoveryTask retrieve the next available element from this set and, based on the object type of the element, determines the processing to perform and what event type to send to the registered listeners.


notifierThread

private LookupDiscovery.Notifier notifierThread
Thread that handles pending notifications.


pendingNotifies

private LinkedList pendingNotifies
Notifications to be sent to listeners.


taskManager

private TaskManager taskManager
Task manager for running UnicastDiscoveryTasks and DecodeAnnouncementTasks.


discoveryWakeupMgr

private WakeupManager discoveryWakeupMgr

isDefaultWakeupMgr

private boolean isDefaultWakeupMgr

tickets

private List tickets

announceeThread

private LookupDiscovery.AnnouncementListener announceeThread
Thread that handles incoming multicast announcements.


requestors

private Collection requestors
Collection that contains instances of the Requestor Thread class, each of which participate in multicast discovery by periodically sending out multicast discovery requests for a finite period of time.


respondeeThread

private LookupDiscovery.ResponseListener respondeeThread
Thread that manages incoming multicast responses. Runs only when there are Requestor threads running.


securityContext

private final SecurityContext securityContext
Security context that contains the access control context to restore for callbacks, etc.


regInfo

private HashMap regInfo
Map from ServiceID to multicast announcement time stamps; used by the process that monitors multicast announcements from already-discovered lookup services, and determines when those announcements have stopped.


announcementTimerThread

private LookupDiscovery.AnnouncementTimerThread announcementTimerThread
Thread that monitors multicast announcements from already-discovered lookup services and, upon determining that those announcements have stopped, queues a reachability test with the UnicastDiscoveryTask which will ultimately result in the lookup service being discarded if the reachability test indicates that the lookup service is actually down.


registrarPreparer

private ProxyPreparer registrarPreparer

protocol2

private Discovery protocol2

multicastRequestMax

private int multicastRequestMax

multicastRequestInterval

private long multicastRequestInterval

finalMulticastRequestInterval

private long finalMulticastRequestInterval

multicastRequestHost

private String multicastRequestHost

multicastRequestConstraints

private DiscoveryConstraints multicastRequestConstraints

nics

private NetworkInterface[] nics

nicRetryInterval

private int nicRetryInterval

multicastAnnouncementInterval

private long multicastAnnouncementInterval

unicastDelayRange

private long unicastDelayRange

initialMulticastRequestDelayRange

private long initialMulticastRequestDelayRange

initialRequestorStarted

private boolean initialRequestorStarted

multicastAnnouncementConstraints

private DiscoveryConstraints multicastAnnouncementConstraints

rawUnicastDiscoveryConstraints

private InvocationConstraints rawUnicastDiscoveryConstraints

DISCOVERED

private static final int DISCOVERED
Constants used to tell the notifierThread the type of event to send

See Also:
Constant Field Values

DISCARDED

private static final int DISCARDED
See Also:
Constant Field Values

CHANGED

private static final int CHANGED
See Also:
Constant Field Values

NICS_USE_ALL

private static final int NICS_USE_ALL
Constants used to indicate the set of network interfaces being used

See Also:
Constant Field Values

NICS_USE_SYS

private static final int NICS_USE_SYS
See Also:
Constant Field Values

NICS_USE_LIST

private static final int NICS_USE_LIST
See Also:
Constant Field Values

NICS_USE_NONE

private static final int NICS_USE_NONE
See Also:
Constant Field Values

nicsToUse

private int nicsToUse
Flag that indicates how the set of network interfaces was configured

Constructor Detail

LookupDiscovery

public LookupDiscovery(String[] groups)
                throws IOException
Construct a new lookup discovery object, set to discover the given set of groups. The set is represented as an array of strings. This array may be empty, which is taken as the empty set, and discovery is not performed. The reference passed in may be null, which is taken as no set, and in which case discovery of all reachable lookup services is performed. Otherwise, the array contains the names of groups to discover. The caller must have DiscoveryPermission for each group (or for all groups, if the array is null).

Parameters:
groups - the set of group names to discover (null for no set, empty for no discovery)
Throws:
NullPointerException - input array contains at least one null element
IOException - an exception occurred in starting discovery
See Also:
NO_GROUPS, ALL_GROUPS, setGroups(java.lang.String[]), DiscoveryPermission

LookupDiscovery

public LookupDiscovery(String[] groups,
                       Configuration config)
                throws IOException,
                       ConfigurationException
Constructs a new lookup discovery object, set to discover the given set of groups, and having the given Configuration.

The set of groups to discover is represented as an array of strings. This array may be empty, which is taken as the empty set, and discovery is not performed. The reference passed in may be null, which is taken as no set, and in which case discovery of all reachable lookup services is performed. Otherwise, the array contains the names of groups to discover. The caller must have DiscoveryPermission for each group (or for all groups, if the array is null).

Parameters:
groups - the set of group names to discover (null for no set, empty for no discovery)
config - an instance of Configuration, used to obtain the objects needed to configure the current instance of this class
Throws:
NullPointerException - input array contains at least one null element or null is input for the configuration
IOException - an exception occurred in starting discovery
ConfigurationException - indicates an exception occurred while retrieving an item from the given Configuration
See Also:
NO_GROUPS, ALL_GROUPS, setGroups(java.lang.String[]), DiscoveryPermission, Configuration, ConfigurationException
Method Detail

addDiscoveryListener

public void addDiscoveryListener(DiscoveryListener l)
Register a listener as interested in receiving DiscoveryEvent notifications.

Specified by:
addDiscoveryListener in interface DiscoveryManagement
Parameters:
l - the listener to register
Throws:
NullPointerException - this exception occurs when null is input to the listener parameter l.
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
DiscoveryEvent, removeDiscoveryListener(net.jini.discovery.DiscoveryListener)

removeDiscoveryListener

public void removeDiscoveryListener(DiscoveryListener l)
Indicate that a listener is no longer interested in receiving DiscoveryEvent notifications.

Specified by:
removeDiscoveryListener in interface DiscoveryManagement
Parameters:
l - the listener to unregister
Throws:
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
addDiscoveryListener(net.jini.discovery.DiscoveryListener)

getRegistrars

public ServiceRegistrar[] getRegistrars()
Returns an array of instances of ServiceRegistrar, each corresponding to a proxy to one of the currently discovered lookup services. For each invocation of this method, a new array is returned.

Specified by:
getRegistrars in interface DiscoveryManagement
Returns:
array of instances of ServiceRegistrar, each corresponding to a proxy to one of the currently discovered lookup services
Throws:
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
ServiceRegistrar, DiscoveryManagement.removeDiscoveryListener(net.jini.discovery.DiscoveryListener)

discard

public void discard(ServiceRegistrar reg)
Discard a registrar from the set of registrars already discovered. This does not prevent that registrar from being rediscovered; it is intended to be used to clear unreachable entries from the set.

If the registrar has been discovered using this LookupDiscovery object, each listener registered with this object will have its discarded method called with the given registrar as parameter.

Specified by:
discard in interface DiscoveryManagement
Parameters:
reg - the registrar to discard
Throws:
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
DiscoveryListener.discarded(net.jini.discovery.DiscoveryEvent)

terminate

public void terminate()
Terminate the discovery process.

Specified by:
terminate in interface DiscoveryManagement

getGroups

public String[] getGroups()
Return the set of group names this LookupDiscovery instance is trying to discover. If this method returns the empty array, that value is guaranteed to be referentially equal to LookupDiscovery.NO_GROUPS.

Specified by:
getGroups in interface DiscoveryGroupManagement
Returns:
the set of groups to be discovered (null for all, empty for no discovery)
Throws:
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
NO_GROUPS, ALL_GROUPS, setGroups(java.lang.String[])

addGroups

public void addGroups(String[] newGroups)
               throws IOException
Add a set of groups to the set to be discovered. The caller must have DiscoveryPermission for each group.

Specified by:
addGroups in interface DiscoveryGroupManagement
Parameters:
newGroups - the groups to add
Throws:
IOException - the multicast request protocol failed to start
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
UnsupportedOperationException - there is no set of groups to add to
See Also:
DiscoveryPermission

setGroups

public void setGroups(String[] newGroups)
               throws IOException
Change the set of groups to be discovered to correspond to the given set. The set is represented as an array of strings. This array may be empty, which is taken as the empty set, and discovery is not performed. The reference passed in may be null, which is taken as no set, and in which case discovery of all reachable lookup services is performed. Otherwise, the array contains the names of groups to discover. The caller must have DiscoveryPermission for each group (or for all groups, if the array is null).

Specified by:
setGroups in interface DiscoveryGroupManagement
Parameters:
newGroups - the new set of groups to discover (null for all, empty array for no discovery)
Throws:
IOException - an exception occurred when starting multicast discovery
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
See Also:
LookupDiscovery(java.lang.String[], net.jini.config.Configuration), ALL_GROUPS, NO_GROUPS, DiscoveryPermission, getGroups()

removeGroups

public void removeGroups(String[] oldGroups)
Remove a set of groups from the set to be discovered.

Specified by:
removeGroups in interface DiscoveryGroupManagement
Parameters:
oldGroups - groups to remove
Throws:
IllegalStateException - this exception occurs when this method is called after the terminate method has been called.
UnsupportedOperationException - there is no set of groups from which to remove
See Also:
DiscoveryGroupManagement.addGroups(java.lang.String[])

sendPacketByNIC

private void sendPacketByNIC(MulticastSocket mcSocket,
                             DatagramPacket[] packet)
                      throws InterruptedIOException
Sends the given packet data on the given MulticastSocket through each of the network interfaces corresponding to elements of the array configured when this utility was constructed.

Parameters:
mcSocket - the MulticastSocket on which the data will be sent
packet - DatagramPacket array whose elements are the data to send
Throws:
InterruptedIOException

sendPacket

private static void sendPacket(MulticastSocket mcSocket,
                               DatagramPacket[] packet)
                        throws IOException
Sends the given packet data on the given MulticastSocket through the network interface that is currently set.

Parameters:
mcSocket - the MulticastSocket on which the data will be sent
packet - DatagramPacket array whose elements are the data to send
Throws:
IOException

getLocalHost

private static String getLocalHost()
                            throws UnknownHostException
Returns the local host name.

Throws:
UnknownHostException

checkGroups

private static void checkGroups(String[] groups)
Determines if the caller has discovery permission for each group.


collectionToStrings

private static final String[] collectionToStrings(Collection c)
Converts a collection to an array of strings.


groupSetsEqual

private static boolean groupSetsEqual(String[] groupSet0,
                                      String[] groupSet1)
Determines if two sets of registrar member groups have identical contents. Assumes there are no duplicates, and the sets can never be null.

Parameters:
groupSet0 - String array containing the group names from the first set used in the comparison
groupSet1 - String array containing the group names from the second set used in the comparison
Returns:
true if the contents of each set is identical; false otherwise

registrarsEqual

private static boolean registrarsEqual(UnicastResponse resp1,
                                       UnicastResponse resp2)
Returns true if the registrars contained in the given (possibly null) UnicastResponse instances are equals() to one another.


removeGroupsInt

private boolean removeGroupsInt(String[] oldGroups)
Remove the specified groups from the set of groups to discover, and return true if any were actually removed.


getServiceIDs

private ServiceID[] getServiceIDs()
Returns the service IDs of the lookup service(s) discovered to date.


groupsOverlap

private boolean groupsOverlap(String[] possibilities)
Indicate whether any of the group names in the given array match any of the groups of interest.

Parameters:
possibilities - the set of group names to compare to the set of groups to discover (must not be null)

requestGroups

private void requestGroups(Collection req)
                    throws IOException
Called at startup and whenever the set of groups to discover is changed. This method executes the multicast request protocol by starting the ResponseListener thread to listen for multicast responses; and starting a Requestor thread to send out multicast requests for the set of groups contained in the given Collection.

Throws:
IOException

prepareSocket

private static void prepareSocket(Socket s,
                                  DiscoveryConstraints dc)
                           throws SocketException
Throws:
SocketException

maybeAddNewRegistrar

private void maybeAddNewRegistrar(UnicastResponse resp)
If the lookup service associated with the given UnicastResponse is not in the set of already-discovered lookup services, this method adds it to that set, and each registered listener is notified.

Parameters:
resp - the UnicastResponse associated with the lookup service to add

maybeDiscardRegistrars

private void maybeDiscardRegistrars()
Determine if any of the already-discovered registrars are no longer members of any of the groups to discover, and discard those registrars that are no longer members of any of those groups.


addNotify

private void addNotify(ArrayList notifies,
                       Map groupsMap,
                       int eventType)
Add a notification task to the pending queue, and start an instance of the Notifier thread if one isn't already running.


nukeThreads

private void nukeThreads()
Terminates (interrupts) all currently-running threads.


terminateTaskMgr

private void terminateTaskMgr()
This method removes all pending and active tasks from the TaskManager for this instance. It also clears the set of pendingDiscoveries, and closes all associated sockets.


maybeSendEvent

private void maybeSendEvent(UnicastResponse response,
                            String[] newGroups)
After a possible change in the member groups of the ServiceRegistrar corresponding to the given UnicastResponse parameter, this method determines whether or not the registrar's member groups have changed in such a way that either a changed event or a discarded event is warranted.

Note that even if the contents of the new set of groups initially indicate that the corresponding registrar is a candidate for a discarded or a changed event, further analysis must be performed. This is because there is no guarantee that the new set of member groups have not been "split" across the multicast announcements sent by the lookup service; and so there is no guarantee that the contents of the new group set actually reflect a change that warrants an event. To guarantee that the new group set accurately reflects the registrar's member groups, this method makes a remote call to the registrar to retrieve its actual member groups.

There is one situation where it is not necessary to query the registrar for its current member groups. That situation is when the set of groups input to the newGroups parameter is equivalent to NO_GROUPS. If that new group set is equivalent to NO_GROUPS, it is guaranteed that the registrar's member groups have not been split across the multicast announcements.

Parameters:
response - instance of UnicastResponse corresponding to the registrar whose current and previous member groups are to be compared
newGroups - String array containing the new member groups of the registrar corresponding to the response parameter (just after a possible change)

notifyOnGroupChange

private void notifyOnGroupChange(ServiceRegistrar reg,
                                 String[] oldGroups,
                                 String[] newGroups)
After a possible change in the member groups of the given ServiceRegistrar parameter, this method compares the registrar's original set of member groups to its new set of member groups.

If the criteria shown below is satisfied, either a discarded event or a changed event will be sent to any registered listeners. The criteria is based on whether the old and new groups are equal, and whether one or more elements of the new group set also belong to the set of groups to discover (the new groups are "still of interest"). The criteria is as follows:

if (old groups and new groups)

Parameters:
reg - instance of ServiceRegistrar corresponding to the registrar whose current and previous member groups are to be compared; and whose corresponding service ID is used as the key into the various data structures that contain pertinent information about that registrar
oldGroups - String array containing the member groups of the reg parameter prior to being changed
newGroups - String array containing the current member groups of the reg parameter (just after a possible change)

sendDiscarded

private void sendDiscarded(ServiceRegistrar reg,
                           String[] curGroups)
Convenience method that sends a discarded event containing only one registrar to all registered listeners. This method must be called from within a block that is synchronized on the registrars map.

Parameters:
reg - instance of ServiceRegistrar corresponding to the registrar to include in the event
curGroups - String array containing the current member groups of the registrar referenced by the reg parameter

sendChanged

private void sendChanged(ServiceRegistrar reg,
                         String[] curGroups)
Convenience method that sends a changed event containing only one registrar to all registered listeners that are interested in such events. This method must be called from within a block that is synchronized on the registrars map.

Parameters:
reg - instance of ServiceRegistrar corresponding to the registrar to include in the event
curGroups - String array containing the current member groups of the registrar referenced by the reg parameter

deepCopy

private Map deepCopy(HashMap groupsMap)
Creates and returns a deep copy of the input parameter. This method assumes the input map is a HashMap of the registrar-to-groups mapping; and returns a clone not only of the map, but of each key-value pair contained in the mapping.

Parameters:
groupsMap - mapping from a set of registrars to the member groups of each registrar
Returns:
clone of the input map, and of each key-value pair contained in the input map

getActualGroups

private String[] getActualGroups(ServiceRegistrar reg)
This method retrieves from the given ServiceRegistrar, the current groups in which that registrar is a member. If the registrar is un-reachable, then this method will discard the registrar.

Parameters:
reg - instance of ServiceRegistrar referencing the registrar whose member groups are to be retrieved and returned
Returns:
String array containing the current member groups of the registrar referenced by the reg parameter

mapRegToGroups

private Map mapRegToGroups(ServiceRegistrar reg,
                           String[] curGroups)
Convenience method that creates and returns a mapping of a single ServiceRegistrar instance to a set of groups.

Parameters:
reg - instance of ServiceRegistrar corresponding to the registrar to use as the key to the mapping
curGroups - String array containing the current member groups of the registrar referenced by the reg parameter; and which is used as the value of the mapping
Returns:
Map instance containing a single mapping from a given registrar to its current member groups

testArrayForNullElement

private void testArrayForNullElement(String[] groupArray)
This method is used by the public methods of this class that are specified to throw a NullPointerException when the given array of group names contains one or more null elements; in which case, this method throws a NullPointerException which should be allowed to propagate outward.

Throws:
NullPointerException - this exception occurs when one or more of the elements of the groupArray parameter is null.

beginDiscovery

private void beginDiscovery(String[] groups,
                            Configuration config)
                     throws IOException,
                            ConfigurationException
Using the given Configuration, initializes the current instance of this utility, and initiates the discovery process for the given set of groups.

Parameters:
groups - the set of group names to discover
config - an instance of Configuration, used to obtain the objects needed to configure this utility
Throws:
NullPointerException - input array contains at least one null element or null is input for the configuration
IOException - an exception occurred when initiating discovery processing
ConfigurationException - indicates an exception occurred while retrieving an item from the given Configuration

init

private void init(Configuration config)
           throws IOException,
                  ConfigurationException
Throws:
IOException
ConfigurationException

decodeMulticastAnnouncement

private MulticastAnnouncement decodeMulticastAnnouncement(DatagramPacket pkt)
                                                   throws IOException
Decodes received multicast announcement packet. Constraint checking is delayed.

Throws:
IOException

checkAnnouncementConstraints

private void checkAnnouncementConstraints(MulticastAnnouncement ann)
                                   throws IOException
Throws:
IOException

encodeMulticastRequest

private DatagramPacket[] encodeMulticastRequest(MulticastRequest req)
                                         throws IOException
Encodes outgoing multicast requests based on protocol in use, applying configured security constraints (if any).

Throws:
IOException

restoreContextAddTask

private void restoreContextAddTask(TaskManager.Task t)

restoreContextScheduleRunnable

private WakeupManager.Ticket restoreContextScheduleRunnable(LookupDiscovery.UnicastDiscoveryTask t)

doUnicastDiscovery

private UnicastResponse doUnicastDiscovery(Socket socket,
                                           DiscoveryConstraints unicastDiscoveryConstraints,
                                           Discovery disco)
                                    throws IOException,
                                           ClassNotFoundException
Performs unicast discovery over given socket based on protocol in use, applying configured security constraints (if any).

Throws:
IOException
ClassNotFoundException

doUnicastDiscovery

private UnicastResponse doUnicastDiscovery(Socket socket,
                                           DiscoveryConstraints unicastDiscoveryConstraints)
                                    throws IOException,
                                           ClassNotFoundException
Throws:
IOException
ClassNotFoundException

getDiscovery

private Discovery getDiscovery(int version)
                        throws DiscoveryProtocolException
Returns Discovery instance for the given version, or throws DiscoveryProtocolException if the version is unsupported.

Throws:
DiscoveryProtocolException


Copyright 2007-2010, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.