com.sun.jini.outrigger
Class OutriggerServerImpl

java.lang.Object
  extended by com.sun.jini.outrigger.OutriggerServerImpl
All Implemented Interfaces:
DestroyAdmin, TimeConstants, Landlord, LocalLandlord, OutriggerAdmin, OutriggerServer, Recover, ServiceProxyAccessor, Remote, JoinAdmin, TransactionConstants, TransactionParticipant, ServerProxyTrust

public class OutriggerServerImpl
extends Object
implements OutriggerServer, TimeConstants, LocalLandlord, Recover, ServerProxyTrust

A basic implementation of a JavaSpacesTM service. This class is designed for use by both transient and persistent instances. Persistence is delegated to Store and LogOps objects which handles the details of implementing a particular persistence strategy. If transient a null value is used for the LogOps object.

OutriggerServerImpl maintains a list of types of entries it has seen and their subtypes using a TypeTree object. Each type of entry has an EntryHolder that is stored in the EntryHolderSet object named contents.

On write, the written entry's class and superclass are added to the known types, and its EntryRep is added to the space's contents.

On read, the find method searches through the entries of its type and subtypes, asking each entry holder if it has an entry that matches the template. If a match is found, the matching EntryRep is returned. If none of the appropriate holders has a match, it will return null.

On take we also use find with a boolean that says to remove the entry that matches.

Notification requires a separate Notifier queue and thread. When an entry is written, a reference to it is added to the queue of "unexamined entries". The notifier thread pulls entries off the queue and checks them against registered notification templates. When it has found all matches for the template, the Notifier thread adds the notifications for this write to its list of undelivered notifications, which it periodically attempts to deliver.

On notify, the template is added to the TemplateHolderSet named template. This stores TemplateHolder objects for each known type.

In this implementation, EntryRep ID's are approximate time stamps.

Author:
Sun Microsystems, Inc.

Nested Class Summary
private  class OutriggerServerImpl.AllReps
          An iterator that returns all the reps in the space that are of at least the given class.
private  class OutriggerServerImpl.ContentsQuery
          Object that keeps the current state of contents queries.
private  class OutriggerServerImpl.ContentsQueryReaper
          Entry reaping thread class
private  class OutriggerServerImpl.DestroyThread
          Termination thread code.
private  class OutriggerServerImpl.EntryReaper
          Entry reaping thread class
private  class OutriggerServerImpl.IteratorImpl
          Implementation of the remote iteration interface.
private  class OutriggerServerImpl.Reaper
          Base class for our house keeping threads.
private  class OutriggerServerImpl.TemplateReaper
          Template reaping thread class
 
Nested classes/interfaces inherited from interface com.sun.jini.outrigger.OutriggerServer
OutriggerServer.QueryCookie
 
Nested classes/interfaces inherited from interface com.sun.jini.landlord.Landlord
Landlord.RenewResults
 
Field Summary
private  ActivationID activationID
          Our activation ID, null if we are not activatable
private  ActivationSystem activationSystem
          A prepared reference to the activation system, null if we are not activatable.
private  AdminProxy adminProxy
          The admin proxy for this space.
static String COMPONENT_NAME
          Component name we use to find items in the configuration and loggers.
private  EntryHolderSet contents
          List of com.sun.jini.outrigger.EntryHolders for each specific type.
private  LeasePeriodPolicy contentsLeasePolicy
          Policy used to create and renew leases on event contents queries
private  Map contentsQueries
          A map from contents result cookies to ContentsQuery objects.
private  OutriggerServerImpl.ContentsQueryReaper contentsQueryReaperThread
          The reaper thread for expired contents queries
private  long crashCount
          The crash count.
private  LeasePeriodPolicy entryLeasePolicy
          Policy used to create and renew leases on entries
private  OutriggerServerImpl.EntryReaper entryReaperThread
          The reaper thread for removed entries.
private  LeasePeriodPolicy eventLeasePolicy
          Policy used to create and renew leases on event registrations
(package private) static String eventLoggerName
          Logger name for information related to events
private  Map eventRegistrations
          A map from event registration cookies to EventRegistrationRecord instances
private  ExpirationOpQueue expirationOpQueue
          Object that queues up lease expirations for future logging.
private  Exporter exporter
          Object we used to export ourselves.
private static SecureRandom idGen
          Our IDs 64 bits secure random numbers, this is SecureRandom instance we use to create them.
private  Map iterations
          The map of Uuid to active iterations
private static Logger iteratorLogger
          Logger for logging information to iterators
(package private) static String iteratorLoggerName
          Logger name for information related to iterators
private static Logger joinLogger
          Logger for logging information about join state
(package private) static String joinLoggerName
          Logger name for information related to join state
private  JoinStateManager joinStateManager
           
private  LeaseFactory leaseFactory
          Factory we use to create leases
private static Logger leaseLogger
          Logger for information related to leases and leasing
(package private) static String leaseLoggerName
          Logger name for information related to leases and leasing
private  LifeCycle lifeCycle
          Object to notify if we destroy ourselves, may be null
private static Logger lifecycleLogger
          Logger for information related to starting/restarting/destroying the service
(package private) static String lifecycleLoggerName
          Logger name for information related to starting/restarting/destroying the service
private  ProxyPreparer listenerPreparer
          ProxyPreparer for event listeners
private  LogOps log
          Log object to record state and operation information.
private  LoginContext loginContext
          The login context, for logging out
(package private) static String matchingLoggerName
          Logger name for information related to entry matching
private  long maxUnexportDelay
          When destroying the space, how long to wait for a clean unexport (which allows the destroy call to return) before giving up calling unexport(true)
private  int nextLimit
          Max number of entries to return in a next call
private  Notifier notifier
          The notification object
private  OperationJournal operationJournal
          Object that recored operations on entries and makes sure they get seen by the watchers in templates.
private static Logger opsLogger
          Logger for information related to top level operations
(package private) static String opsLoggerName
          Logger name for information related top level operations
private  OutriggerServer ourRemoteRef
          The remote ref (e.g. stub or dynamic proxy) for this server.
private  ParticipantProxy participantProxy
          The participant proxy for this space
static String PERSISTENCE_DIR_CONFIG_ENTRY
          The name of the configuration entry we use to get the the name of the log directory from.
private  ProxyPreparer recoveredListenerPreparer
          ProxyPreparer for event listeners that get recovered from the store.
private  ProxyPreparer recoveredTransactionManagerPreparer
          ProxyPreparer for transaction managers that get recovered from the store.
private  Map recoveredTxns
          The transactions recovered after restart.
private  OutriggerServerWrapper serverGate
          The wrapper that intercepts incoming remote calls for locking purposes and then delegates to us.
private  long sessionId
          Holds the basis/lower bound for all sequence numbers issued.
private  SpaceProxy2 spaceProxy
          The proxy for this space.
private  Store store
          Store - The reference to the persistent store, if any.
static String storeLoggerName
          Logger name for information related to persistence
private  int takeLimit
          Max number of entries to return in a take multiple call
private  OutriggerServerImpl.TemplateReaper templateReaperThread
          The reaper thread for expired notifications
private  TransitionWatchers templates
          Templates for which someone has registered interest
private  Uuid topUuid
          The Uuid for this service.
private  ProxyPreparer transactionManagerPreparer
          ProxyPreparer for transaction managers
private static Logger txnLogger
          Logger for information related to transactions
(package private) static String txnLoggerName
          Logger name for information related to transactions
private  TxnMonitor txnMonitor
          The monitor for ongoing transactions.
private  TxnTable txnTable
          The transactions in which this space is a participant.
private  HashMap typeHashes
          A list of hashes to check against class types.
private  TypeTree types
          A list of known subclasses of each class of entry.
private  long unexportRetryDelay
          Length of time to sleep between unexport attempts
 
Fields inherited from interface net.jini.core.transaction.server.TransactionConstants
ABORTED, ACTIVE, COMMITTED, NOTCHANGED, PREPARED, VOTING
 
Fields inherited from interface com.sun.jini.constants.TimeConstants
DAYS, HOURS, MINUTES, SECONDS
 
Constructor Summary
OutriggerServerImpl(ActivationID activationID, LifeCycle lifeCycle, String[] configArgs, boolean persistent, OutriggerServerWrapper wrapper)
          Create a new OutriggerServerImpl server (possibly a new incarnation of an activatable one).
 
Method Summary
 void abort(TransactionManager mgr, long id)
          Requests that the participant roll back any changes for the specified transaction and unlock any resources locked by the transaction.
 void addLookupAttributes(Entry[] attrSets)
          Add attribute sets for the service.
 void addLookupGroups(String[] groups)
          Add new groups to the set to join.
 void addLookupLocators(LookupLocator[] locators)
          Add locators for specific new lookup services to join.
private  void addWrittenRep(EntryHandle handle, EntryHolder holder, Txn txn)
          Add the written rep to the relevant data structures.
(package private)  boolean attemptCapture(EntryHandle handle, TransactableMgr txn, boolean takeIt, Set lockedEntrySet, WeakHashMap provisionallyRemovedEntrySet, long now, QueryWatcher watcher)
          Atomically check to see if the passed entry can be read/taken by the specified operation using the specified transaction and if it can read/take it and return true, otherwise return false.
private static Entry[] attributesFor()
          Create the service-owned attributes for an Outrigger server.
private  UnmarshalException brokenTxn(TransactionManager mgr, long id, Exception nested)
          Create, log, and throw a new UnmarshalException to represent a transaction recovery failure
 void cancel(Uuid cookie)
          Called by the lease when its cancel method is called.
 Map cancelAll(Uuid[] cookies)
          Called by the lease map when its cancelAll method is called.
(package private)  void cancelOp(Uuid cookie, boolean expired)
          Log a "cancel" operation.
private  boolean checkClass(String className, long value)
          Compare the given hash with the hash stored for the given class name, if any.
private  void checkForEmpty(EntryRep[] entries, String msg)
          Utility method to check for zero length arrays of entries and throw an exception if necessary
private  void checkForNull(Object value, String msg)
          Utility method to check for null argument values and throw an exception if necessary
private  void checkLimit(long limit)
          Utility method to check for non-postive limits
private  void checkTimeout(long timeout)
          Utility method to check for negative timeouts
 void close(Uuid iterationUuid)
          Forget about the indicated iteration
 void commit(TransactionManager mgr, long id)
          Requests that the participant make all of its PREPARED changes for the specified transaction visible outside of the transaction and unlock any resources locked by the transaction.
private  EntryRep[] completeTake(EntryHandle[] handles, int found, Txn txn)
           
private  EntryRep completeTake(EntryHandle handle, Txn txn)
           
 MatchSetData contents(EntryRep[] tmpls, Transaction tr, long leaseTime, long limit)
          Start a new contents query.
 Uuid contents(EntryRep tmpl, Transaction tr)
          Return the remote iterator object needed by JavaSpaceAdmin.contents.
private  EntryHolder.ContinuingQuery createQuery(EntryRep[] tmpls, String clazz, Txn txn, boolean takeIt, long now)
          Crerate a ContinuingQuery for the holder of the specified class.
private  void debug(Object obj, String str)
          Print out a debug description of obj, followed by the given str.
 void delete(Uuid iterationUuid, Uuid entryUuid)
          Delete the given entry if the given iteration is still valid and the entry was retured by the last call to nextReps.
 void destroy()
          Destroy this space, exiting when finished.
private  void destroyReaper(OutriggerServerImpl.Reaper r)
          Shutdown a reaper as part of a controlled tear-down
(package private) static void dump(EntryHolder holder, String name, EntryRep rep)
          Debug method: Dump out the bucket for the given holder, for an operation using the given rep.
(package private)  void dump(String name, EntryRep rep)
          Debug method: Dump out the bucket for the holder for the given rep.
(package private)  void enqueueDelivery(EventSender sender)
          Queue up an event for delivery.
private  Txn enterTxn(Transaction baseTr)
          This method takes a transactional semantic object baseTr (the transaction object passed to us by the client) and retrieves the associated Txn object (the internal representation for that transaction) from the space's records.
private  EntryHandle find(EntryRep tmplRep, Txn txn, boolean takeIt, Set conflictSet, Set lockedEntrySet, WeakHashMap provisionallyRemovedEntrySet)
          Find an entry that is at least whichClass that matches the template tmplRep (at least the template's type, and matches in values provided).
 Object getAdmin()
          Return a proxy that implements that JavaSpaceAdmin interface.
 Entry[] getLookupAttributes()
          Get the current attribute sets for the service.
 String[] getLookupGroups()
          Get the list of groups to join.
 LookupLocator[] getLookupLocators()
          Get the list of locators of specific lookup services to join.
private  Object getMatch(EntryRep tmpl, Transaction tr, long timeout, boolean takeIt, boolean ifExists, OutriggerServer.QueryCookie queryCookieFromClient)
          Do the heavy lifting for queries.
(package private)  Object getProxy()
           
 TrustVerifier getProxyVerifier()
          Returns a TrustVerifier that can be used to verify that a proxy can be trusted as a proxy for the service; that is, the isTrustedObject method of the returned verifier can be called with a candidate proxy.
(package private)  ProxyPreparer getRecoveredTransactionManagerPreparer()
          Return the proxy preparer for recovered transaction managers, or null if there is none.
private  Txn getRecoveredTxn(Long txnId)
           
 Object getServiceProxy()
          Returns a proxy object for this object.
(package private)  long getSessionId()
           
private  Txn getTxn(TransactionManager mgr, long id)
          Look in the table for the Txn object for the given manager/id pair.
private  LeasePeriodPolicy.Result grant(LeasedResource resource, long requestedDuration, LeasePeriodPolicy policy, String policyName)
          Utility method to calculate the lease duration/expiration for a new resource and set the resource's expiration.
private  void init(Configuration config, boolean persistent)
          The bulk of the work for creating an OutriggerServerImpl server.
private  void joinThread(Thread t)
          Join a thread as part of a controlled tear-down
private  RuntimeException logAndThrow(RuntimeException e, Logger logger)
          Log and throw the passed runtime exception
private  IllegalArgumentException logAndThrowIllegalArg(String msg)
          Log and throw a new IllegalArgumentException.
private  void logDestroyPhase(String part)
          log phase of destroy thread
private  void logDestroyProblem(String part, Throwable t)
          log exception encountered in destroy thread
 void modifyLookupAttributes(Entry[] attrSetTemplates, Entry[] attrSets)
          Modify the current attribute sets, using the same semantics as ServiceRegistration.modifyAttributes.
(package private)  void monitor(Collection toMonitor)
          Make sure the transactions listed here are monitored for a reasonable amount of time since they recently caused a conflict, although for a non-leased event.
private  void monitor(QueryWatcher watcher, Collection toMonitor)
          Make sure the transactions listed here are monitored for as long as the given query exists.
 EntryRep[] nextBatch(Uuid contentsQueryUuid, Uuid entryUuid)
          Return the next batch of entries associated with the specified contents query.
(package private) static long nextID()
          Generate a new ID.
 EntryRep[] nextReps(Uuid iterationUuid, int max, Uuid entryUuid)
          Fetch up to max EntryRep objects from the specified iteration.
 EventRegistration notify(EntryRep tmpl, Transaction tr, RemoteEventListener listener, long leaseTime, MarshalledObject handback)
          When entries are written that match this template notify the given listener.
 int prepare(TransactionManager mgr, long id)
          Requests that the participant prepare itself to commit the transaction, and to vote on the outcome of the transaction.
 int prepareAndCommit(TransactionManager mgr, long id)
          A combination of prepare and commit, which can be used by the manager when there is just one participant left to prepare and all other participants (if any) have responded with NOTCHANGED.
 Object read(EntryRep tmpl, Transaction txn, long timeout, OutriggerServer.QueryCookie cookie)
          Find an entry in the space that matches the passed template and is visible to the passed transaction.
 Object readIfExists(EntryRep tmpl, Transaction txn, long timeout, OutriggerServer.QueryCookie cookie)
          Find an entry in the space that matches the passed template and is visible to the passed transaction.
(package private)  void recordTransition(EntryTransition transition)
          Records a transition in the visibility of an entry.
 void recoverJoinState(StoredObject state)
          Recover the join state from the previous session.
 void recoverRegister(StoredResource registration, String type, StoredObject[] storedTemplates)
          Recover an event registration.
 void recoverSessionId(long sessionId)
          Recover the id from the previous session and determine the new basis value for the seq numbers issued by this session.
 void recoverTake(Uuid cookie, Long txnId)
          Recover a take operation.
 void recoverTransaction(Long txnId, StoredObject transaction)
          Recover a prepared transaction.
private  void recoverTxns()
          Process the recovered transactions.
 void recoverUuid(Uuid uuid)
          Recover the Uuid for the service as a whole.
 void recoverWrite(StoredResource entry, Long txnId)
          Recover a write operation.
 EventRegistration registerForAvailabilityEvent(EntryRep[] tmpls, Transaction tr, boolean visibilityOnly, RemoteEventListener listener, long leaseTime, MarshalledObject handback)
          When entries that match one or more of the passed templates transition from invisible to visible notify the give listener.
(package private)  void removeEventRegistration(EventRegistrationRecord reg)
          Remove the passed EventRegistrationRecord from event registrations map.
 void removeLookupGroups(String[] groups)
          Remove groups from the set to join.
 void removeLookupLocators(LookupLocator[] locators)
          Remove locators for specific lookup services from the set to join.
 long renew(Uuid cookie, long extension)
          Called by the lease when its renew method is called.
 Landlord.RenewResults renewAll(Uuid[] cookies, long[] extensions)
          Called by the lease map when its renewAll method is called.
(package private)  void scheduleCancelOp(Uuid cookie)
          Schedule a cancelOp.
private  ServerTransaction serverTransaction(Transaction baseTr)
          We assume that each Transaction object sent to the space is actually the ServerTransaction subtype.
 void setLookupGroups(String[] groups)
          Replace the list of groups to join with a new list.
 void setLookupLocators(LookupLocator[] locators)
          Replace the list of locators of specific lookup services to join with a new list.
private  EntryRep setupTmpl(EntryRep tmpl)
           
 JavaSpace space()
          Return the space administered by this object.
 Object take(EntryRep[] tmpls, Transaction tr, long timeout, int limit, OutriggerServer.QueryCookie queryCookieFromClient)
          Find and remove up to limit entries in the space that match one or more of the passed templates and are visible to the passed transaction.
 Object take(EntryRep tmpl, Transaction txn, long timeout, OutriggerServer.QueryCookie cookie)
          Find and remove an entry in the space that matches the passed template and is visible to the passed transaction.
 Object takeIfExists(EntryRep tmpl, Transaction txn, long timeout, OutriggerServer.QueryCookie cookie)
          Find and remove an entry in the space that matches the passed template and is visible to the passed transaction.
private  CannotJoinException throwNewCannotJoinException()
          Log and throw new CannotJoinException
private  NoSuchObjectException throwNewNoSuchObjectException(String msg, Logger logger)
          Log and throw new NoSuchObjectException
private  NoSuchObjectException throwNewNoSuchObjectException(String msg, Throwable t, Logger logger)
          Log and throw new NoSuchObjectException with a nested exception
private  UnknownLeaseException throwNewUnknownLeaseException(Object cookie)
          Log and throw a new UnknownLeaseException
private  void typeCheck(EntryRep rep)
          Check if an entry (or template) class definition has changed.
private  void unwindConstructor(Throwable cause)
          Undo any work a failed constructor might have done without destroying the service.
private  void unwindReaper(OutriggerServerImpl.Reaper r)
          Kill the given reaper as quickly and quietly
private static void waitOnProvisionallyRemovedEntries(WeakHashMap provisionallyRemovedEntrySet)
          Call waitOnCompleteRemoval on each of the EntryHandles in the passed set.
 long[] write(EntryRep[] entries, Transaction tr, long[] leaseTimes)
          Write a set of entires into the space.
 long[] write(EntryRep rep, Transaction tr, long lease)
          Write a new entry into the space.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

COMPONENT_NAME

public static final String COMPONENT_NAME
Component name we use to find items in the configuration and loggers.

See Also:
Constant Field Values

lifecycleLoggerName

static final String lifecycleLoggerName
Logger name for information related to starting/restarting/destroying the service

See Also:
Constant Field Values

opsLoggerName

static final String opsLoggerName
Logger name for information related top level operations

See Also:
Constant Field Values

txnLoggerName

static final String txnLoggerName
Logger name for information related to transactions

See Also:
Constant Field Values

leaseLoggerName

static final String leaseLoggerName
Logger name for information related to leases and leasing

See Also:
Constant Field Values

iteratorLoggerName

static final String iteratorLoggerName
Logger name for information related to iterators

See Also:
Constant Field Values

joinLoggerName

static final String joinLoggerName
Logger name for information related to join state

See Also:
Constant Field Values

matchingLoggerName

static final String matchingLoggerName
Logger name for information related to entry matching

See Also:
Constant Field Values

eventLoggerName

static final String eventLoggerName
Logger name for information related to events

See Also:
Constant Field Values

storeLoggerName

public static final String storeLoggerName
Logger name for information related to persistence

See Also:
Constant Field Values

lifecycleLogger

private static final Logger lifecycleLogger
Logger for information related to starting/restarting/destroying the service


opsLogger

private static final Logger opsLogger
Logger for information related to top level operations


txnLogger

private static final Logger txnLogger
Logger for information related to transactions


leaseLogger

private static final Logger leaseLogger
Logger for information related to leases and leasing


iteratorLogger

private static final Logger iteratorLogger
Logger for logging information to iterators


joinLogger

private static final Logger joinLogger
Logger for logging information about join state


PERSISTENCE_DIR_CONFIG_ENTRY

public static final String PERSISTENCE_DIR_CONFIG_ENTRY
The name of the configuration entry we use to get the the name of the log directory from.

See Also:
Constant Field Values

contents

private EntryHolderSet contents
List of com.sun.jini.outrigger.EntryHolders for each specific type.


types

private final TypeTree types
A list of known subclasses of each class of entry.


typeHashes

private final HashMap typeHashes
A list of hashes to check against class types.


templates

private TransitionWatchers templates
Templates for which someone has registered interest


eventRegistrations

private final Map eventRegistrations
A map from event registration cookies to EventRegistrationRecord instances


contentsQueries

private final Map contentsQueries
A map from contents result cookies to ContentsQuery objects.


recoveredTxns

private Map recoveredTxns
The transactions recovered after restart. This table is discarded after recovery


txnTable

private TxnTable txnTable
The transactions in which this space is a participant. Includes broken Txns.


crashCount

private final long crashCount
The crash count. This must be different each boot that forgets (implicitly aborts) pending transactions on shutdown.


templateReaperThread

private OutriggerServerImpl.TemplateReaper templateReaperThread
The reaper thread for expired notifications


entryReaperThread

private OutriggerServerImpl.EntryReaper entryReaperThread
The reaper thread for removed entries. Otherwise the entries are not garbage collected after removal since their "prev" links are never traversed which has the side effect of removing the associated object references.


contentsQueryReaperThread

private OutriggerServerImpl.ContentsQueryReaper contentsQueryReaperThread
The reaper thread for expired contents queries


operationJournal

private OperationJournal operationJournal
Object that recored operations on entries and makes sure they get seen by the watchers in templates.


notifier

private Notifier notifier
The notification object


expirationOpQueue

private ExpirationOpQueue expirationOpQueue
Object that queues up lease expirations for future logging. Only allocated if we have a store, otherwise left null


txnMonitor

private TxnMonitor txnMonitor
The monitor for ongoing transactions.


serverGate

private final OutriggerServerWrapper serverGate
The wrapper that intercepts incoming remote calls for locking purposes and then delegates to us. This is the object that gets exported.


lifeCycle

private final LifeCycle lifeCycle
Object to notify if we destroy ourselves, may be null


exporter

private Exporter exporter
Object we used to export ourselves.


ourRemoteRef

private OutriggerServer ourRemoteRef
The remote ref (e.g. stub or dynamic proxy) for this server.


topUuid

private Uuid topUuid
The Uuid for this service. Used in the SpaceProxy2 and AdminProxy to implement reference equality. We also derive our ServiceID from it.


spaceProxy

private SpaceProxy2 spaceProxy
The proxy for this space.


adminProxy

private AdminProxy adminProxy
The admin proxy for this space.


participantProxy

private ParticipantProxy participantProxy
The participant proxy for this space


sessionId

private long sessionId
Holds the basis/lower bound for all sequence numbers issued. Sequence numbers are included in the various notifications given by Outrigger. If Outrigger crashes and restarts, the sequence numbers issued by the new invocation must not overlap with those already issued. To ensure this, begin issuing sequence numbers in the new Outrigger process with values far in excess of anything previously issued.

For any given invocation of Outrigger, the numbers are "fully ordered." However, when Outrigger restarts after a crash, the numbers (when compared to the previous invocation) will appear to have a [large] gap.

[See the JavaSpaces Service Specification for detail on "fully ordered".]


entryLeasePolicy

private LeasePeriodPolicy entryLeasePolicy
Policy used to create and renew leases on entries


eventLeasePolicy

private LeasePeriodPolicy eventLeasePolicy
Policy used to create and renew leases on event registrations


contentsLeasePolicy

private LeasePeriodPolicy contentsLeasePolicy
Policy used to create and renew leases on event contents queries


leaseFactory

private LeaseFactory leaseFactory
Factory we use to create leases


joinStateManager

private JoinStateManager joinStateManager

idGen

private static final SecureRandom idGen
Our IDs 64 bits secure random numbers, this is SecureRandom instance we use to create them.


activationID

private ActivationID activationID
Our activation ID, null if we are not activatable


activationSystem

private ActivationSystem activationSystem
A prepared reference to the activation system, null if we are not activatable.


store

private Store store
Store - The reference to the persistent store, if any.


log

private LogOps log
Log object to record state and operation information. The store provides this object. Will be null if this is a transient server instance.


iterations

private final Map iterations
The map of Uuid to active iterations


loginContext

private final LoginContext loginContext
The login context, for logging out


transactionManagerPreparer

private ProxyPreparer transactionManagerPreparer
ProxyPreparer for transaction managers


listenerPreparer

private ProxyPreparer listenerPreparer
ProxyPreparer for event listeners


recoveredTransactionManagerPreparer

private ProxyPreparer recoveredTransactionManagerPreparer
ProxyPreparer for transaction managers that get recovered from the store. null if this is not a persistent space.


recoveredListenerPreparer

private ProxyPreparer recoveredListenerPreparer
ProxyPreparer for event listeners that get recovered from the store. null if this is not a persistent space.


nextLimit

private int nextLimit
Max number of entries to return in a next call


takeLimit

private int takeLimit
Max number of entries to return in a take multiple call


maxUnexportDelay

private long maxUnexportDelay
When destroying the space, how long to wait for a clean unexport (which allows the destroy call to return) before giving up calling unexport(true)


unexportRetryDelay

private long unexportRetryDelay
Length of time to sleep between unexport attempts

Constructor Detail

OutriggerServerImpl

OutriggerServerImpl(ActivationID activationID,
                    LifeCycle lifeCycle,
                    String[] configArgs,
                    boolean persistent,
                    OutriggerServerWrapper wrapper)
              throws IOException,
                     ConfigurationException,
                     LoginException,
                     ActivationException
Create a new OutriggerServerImpl server (possibly a new incarnation of an activatable one). Exports the server as well.

Parameters:
activationID - of the server, may be null.
lifeCycle - the object to notify when this service is destroyed, may be null.
configArgs - set of strings to be used to obtain a Configuration.
persistent - If true will throw an ConfigurationException if there is no persistence directory or store specified in the configuration.
wrapper - the wrapper that intercepts incoming remote calls before delegating them to this.
Throws:
IOException - if there is problem recovering data from disk, exporting the server, or unpacking data.
ConfigurationException - if the Configuration is malformed.
ActivationException - if activatable and there is a problem getting a reference to the activation system.
LoginException - if the loginContext specified in the configuration is non-null and throws an exception when login is attempted.
Method Detail

init

private void init(Configuration config,
                  boolean persistent)
           throws IOException,
                  ConfigurationException,
                  ActivationException
The bulk of the work for creating an OutriggerServerImpl server. Anything that needs to be done with a subject is done by this method. Assumes the serverGate and activationID fields have been set.

Parameters:
config - The configuration being used to configure this server.
persistent - If true will throw an ConfigurationException if there is no persistence directory or store specified in the configuration.
Throws:
IOException - if there is problem recovering data from disk, exporting the server, or unpacking data.
ConfigurationException - if the Configuration is malformed.
ActivationException

unwindConstructor

private void unwindConstructor(Throwable cause)
Undo any work a failed constructor might have done without destroying the service. Has to work even if the constructor failed part way through.

Parameters:
cause - The exception that caused the constructor to fail.

unwindReaper

private void unwindReaper(OutriggerServerImpl.Reaper r)
Kill the given reaper as quickly and quietly


recoverTxns

private void recoverTxns()
Process the recovered transactions. This includes forcing the state to PREPARED, placing the txn on the tnxs list (or brokenTxns list if the codebase is broken) and finally monitoring the txns.


getSessionId

long getSessionId()

cancelOp

void cancelOp(Uuid cookie,
              boolean expired)
Log a "cancel" operation. Called from EntryHolder and watchers.


scheduleCancelOp

void scheduleCancelOp(Uuid cookie)
Schedule a cancelOp.

Parameters:
cookie - The cookie to pass to cancelOp when it is called.

typeCheck

private void typeCheck(EntryRep rep)
                throws UnmarshalException
Check if an entry (or template) class definition has changed. If so, throw an exception. If it is a new class, then we remember it.

Throws:
UnmarshalException

checkClass

private boolean checkClass(String className,
                           long value)
                    throws UnmarshalException
Compare the given hash with the hash stored for the given class name, if any. If there is a hash for the class name and it does not match, throw an exception. If it does match return true. Otherwise, record the new hash and class name and return false.

Throws:
UnmarshalException

grant

private LeasePeriodPolicy.Result grant(LeasedResource resource,
                                       long requestedDuration,
                                       LeasePeriodPolicy policy,
                                       String policyName)
Utility method to calculate the lease duration/expiration for a new resource and set the resource's expiration. Handles various error conditions.


checkForEmpty

private void checkForEmpty(EntryRep[] entries,
                           String msg)
Utility method to check for zero length arrays of entries and throw an exception if necessary


checkForNull

private void checkForNull(Object value,
                          String msg)
Utility method to check for null argument values and throw an exception if necessary


checkTimeout

private void checkTimeout(long timeout)
Utility method to check for negative timeouts


checkLimit

private void checkLimit(long limit)
Utility method to check for non-postive limits


write

public long[] write(EntryRep rep,
                    Transaction tr,
                    long lease)
             throws TransactionException,
                    RemoteException
Description copied from interface: OutriggerServer
Write a new entry into the space.

Specified by:
write in interface OutriggerServer
Throws:
TransactionException - A transaction error occurred
RemoteException

write

public long[] write(EntryRep[] entries,
                    Transaction tr,
                    long[] leaseTimes)
             throws TransactionException,
                    RemoteException
Description copied from interface: OutriggerServer
Write a set of entires into the space.

Specified by:
write in interface OutriggerServer
Returns:
an array of longs that can be used to construct the leases on the client side. The array will have 3 elements for each lease, the first will be the duration, followed by the high order bits of the Uuid and then the lower order bits of the Uuid.
Throws:
TransactionException - A transaction error occurred
RemoteException

addWrittenRep

private void addWrittenRep(EntryHandle handle,
                           EntryHolder holder,
                           Txn txn)
Add the written rep to the relevant data structures. This is the common code between write and recoverWrite.

See Also:
write(com.sun.jini.outrigger.EntryRep, net.jini.core.transaction.Transaction, long), recoverWrite(com.sun.jini.outrigger.StoredResource, java.lang.Long)

recordTransition

void recordTransition(EntryTransition transition)
Records a transition in the visibility of an entry. This method should be called after the transition has been made visible in contents (including any subsidiary objects such as the appropriate EntryHandle).

Currently we only post transitions that increase the visibility of an entry, or those that resolve a lock. We don't post transitions that reflect the locking of an entry or straight takes. Some of the watchers exploit this fact, so if we ever start to post transitions take and/or new lock transition the watcher may need to be updated.

Parameters:
transition - an object describing the visibility transition of an entry.
Throws:
NullPointerException - if transition is null or if transition.getEntry is null.

enqueueDelivery

void enqueueDelivery(EventSender sender)
Queue up an event for delivery.

Parameters:
sender - An object that on request will attempt to deliver its event to the associated listener.
Throws:
NullPointerException - if sender is null

attemptCapture

boolean attemptCapture(EntryHandle handle,
                       TransactableMgr txn,
                       boolean takeIt,
                       Set lockedEntrySet,
                       WeakHashMap provisionallyRemovedEntrySet,
                       long now,
                       QueryWatcher watcher)
Atomically check to see if the passed entry can be read/taken by the specified operation using the specified transaction and if it can read/take it and return true, otherwise return false. If the entry can not be read/taken because of transaction conflicts the conflicting transaction(s) will be added to the list of transactions to monitor.

Parameters:
handle - The EntryHandle of the entry the caller wants to read/take.
txn - If non-null the transaction to perform this operation under. Note, if non-null and this is not active false will be returned.
takeIt - true if the caller is trying take the passed entry, false otherwise.
lockedEntrySet - If the entry can not be read/taken because of a transaction conflict and the value of this argument is non-null, the ID of the entry will be added to this set. This method assumes that any concurrent access to the set is being arbitrated by the set or by the caller of this method.
provisionallyRemovedEntrySet - If the entry can not be read/taken because it has been provisionally removed then its handle will be placed in the passed WeakHashMap as a key (with null as the value). May be null in which case provisionally removed entries will not be recorded. This method assumes that any concurrent access is being arbitrated by the set or by the caller.
now - an estimate of the current time in milliseconds since the beginning of the epoch.
watcher - The QueryWatcher requesting capture of the entry.
Returns:
true if the entry could be read/taken and false otherwise.
Throws:
NullPointerException - if entry is null.

notify

public EventRegistration notify(EntryRep tmpl,
                                Transaction tr,
                                RemoteEventListener listener,
                                long leaseTime,
                                MarshalledObject handback)
                         throws TransactionException,
                                RemoteException
Description copied from interface: OutriggerServer
When entries are written that match this template notify the given listener. Matching is done as for read.

Specified by:
notify in interface OutriggerServer
Throws:
TransactionException
RemoteException

registerForAvailabilityEvent

public EventRegistration registerForAvailabilityEvent(EntryRep[] tmpls,
                                                      Transaction tr,
                                                      boolean visibilityOnly,
                                                      RemoteEventListener listener,
                                                      long leaseTime,
                                                      MarshalledObject handback)
                                               throws TransactionException,
                                                      RemoteException
Description copied from interface: OutriggerServer
When entries that match one or more of the passed templates transition from invisible to visible notify the give listener. Matching is done as for read.

Specified by:
registerForAvailabilityEvent in interface OutriggerServer
Parameters:
tmpls - the templates that specify what entries should generate events
tr - if non-null entries that become visible to txn should generate events even if txn is never committed. Registration is terminated when txn leaves the active state
visibilityOnly - if true, events will be generated for this registration only when a matching Entry transitions from invisible to visible, otherwise events will be generated when a matching Entry makes any transition from unavailable to available
listener - object to notify when an entry becomes (re)visible
leaseTime - initial requested lease time for the registration
handback - object to be included with every notification
Returns:
An object with information on the registration
Throws:
TransactionException - if txn is non-null and not active or otherwise invalid
RemoteException

removeEventRegistration

void removeEventRegistration(EventRegistrationRecord reg)
Remove the passed EventRegistrationRecord from event registrations map.

Parameters:
reg - The EventRegistrationRecord object to remove.
Throws:
NullPointerException - if reg is null.

setupTmpl

private EntryRep setupTmpl(EntryRep tmpl)

cancel

public void cancel(Uuid cookie)
            throws UnknownLeaseException
Description copied from interface: Landlord
Called by the lease when its cancel method is called. Cancels the lease that is associated with the given cookie.

Specified by:
cancel in interface Landlord
Specified by:
cancel in interface LocalLandlord
Parameters:
cookie - the Uuid associated with the lease who's renew method was called
Throws:
UnknownLeaseException - if landlord does not know about a lease with the specified cookie

renew

public long renew(Uuid cookie,
                  long extension)
           throws UnknownLeaseException,
                  LeaseDeniedException
Description copied from interface: Landlord
Called by the lease when its renew method is called. Renews the lease that is associated with the given cookie.

Specified by:
renew in interface Landlord
Specified by:
renew in interface LocalLandlord
Parameters:
cookie - the Uuid associated with the lease who's renew method was called
extension - argument passed to the renew call
Returns:
The new duration the lease should have
Throws:
UnknownLeaseException - if landlord does not know about a lease with the specified cookie
LeaseDeniedException - if the landlord is unwilling to renew the lease

renewAll

public Landlord.RenewResults renewAll(Uuid[] cookies,
                                      long[] extensions)
Description copied from interface: Landlord
Called by the lease map when its renewAll method is called. Should renew the lease that is associated with each element of cookies

Specified by:
renewAll in interface Landlord
Parameters:
cookies - an array of Uuids, each universally and uniquely identifying a lease granted by this Landlord
extensions - an array of longs, each representing an a duration in milliseconds that the client wants the lease associated with the Uuid from the corresponding element of cookies renewed for
Returns:
A RenewResults object that contains the new duration of each lease that was successfully renewed or the exception encountered for each lease that could not be renewed

cancelAll

public Map cancelAll(Uuid[] cookies)
Description copied from interface: Landlord
Called by the lease map when its cancelAll method is called. Should cancel the lease that is associated with each element of cookies

Specified by:
cancelAll in interface Landlord
Parameters:
cookies - an array of Uuids, each universally and uniquely identifying a lease granted by this Landlord
Returns:
If all the leases specified in the cookies could be cancelled return null. Otherwise, return a Map that for each failed cancel attempt maps the corresponding cookie object to an exception describing the failure.

read

public Object read(EntryRep tmpl,
                   Transaction txn,
                   long timeout,
                   OutriggerServer.QueryCookie cookie)
            throws TransactionException,
                   RemoteException,
                   InterruptedException
Description copied from interface: OutriggerServer
Find an entry in the space that matches the passed template and is visible to the passed transaction. Depending on the state of the space and the arguments this call may block if no entry can be immediately returned. The proxy can specify the maximum period it is willing to wait for a response using the timeout parameter. The proxy may choose to breakup a query from the client with a very long timeout into a set of sub-queries. In such cases it may get a QueryCookie as response to the sub-queries, in these cases it should pass the QueryCookie to the next sub-query (if any) associated with the same request from the client.

If a match is found it is returned as an EntryRep. If txn is non-null the entry is read locked by the transaction, this allows other queries to read, but not take the entry. The lock will be released when the transaction is aborted or prepared.

If no match is found the call will block for up to the specified timeout for a match to appear. If there is still no match available the call will return a QueryCookie.

Specified by:
read in interface OutriggerServer
Parameters:
tmpl - The template that describes the entry being searched for. May be null if any visible entry is acceptable.
txn - The transaction the operation should be performed under. Maybe be null. If non-null and entry is found it will read locked/removed under this transaction.
timeout - The maximum number of milliseconds this call should block in the server before returning an answer (this not necessarily the timeout the client asked for.) A value of 0 indicates the initial search should be performed, but if no match can be found null or a QueryCookie (as appropriate) should be returned immediately.
cookie - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
RemoteException - if a network failure occurs.
InterruptedException - if the thread in the server is interrupted before the query can be completed.

take

public Object take(EntryRep tmpl,
                   Transaction txn,
                   long timeout,
                   OutriggerServer.QueryCookie cookie)
            throws TransactionException,
                   RemoteException,
                   InterruptedException
Description copied from interface: OutriggerServer
Find and remove an entry in the space that matches the passed template and is visible to the passed transaction. Depending on the state of the space and the arguments this call may block if no entry can be immediately returned. The proxy can specify the maximum period it is willing to wait for a response using the timeout parameter. The proxy may choose to breakup a query from the client with a very long timeout into a set of sub-queries. In such cases it may get a QueryCookie as response to the sub-queries, in these cases it should pass the QueryCookie to the next sub-query (if any) associated with the same request from the client.

If a match is found it is returned as an EntryRep. If txn is null the entry is removed from the space. If txn is non-null the entry is exclusively locked by the transaction and will be removed from the space if the transaction is committed.

If no match is found the call will block for up to the specified timeout for a match to appear. If there is still no match available the call will return a QueryCookie.

Specified by:
take in interface OutriggerServer
Parameters:
tmpl - The template that describes the entry being searched for. May be null if any visible entry is acceptable.
txn - The transaction the operation should be performed under. Maybe be null. If non-null and entry is found it will read locked/removed under this transaction.
timeout - The maximum number of milliseconds this call should block in the server before returning an answer (this not necessarily the timeout the client asked for.) A value of 0 indicates the initial search should be performed, but if no match can be found null or a QueryCookie (as appropriate) should be returned immediately.
cookie - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
RemoteException - if a network failure occurs.
InterruptedException - if the thread in the server is interrupted before the query can be completed.

readIfExists

public Object readIfExists(EntryRep tmpl,
                           Transaction txn,
                           long timeout,
                           OutriggerServer.QueryCookie cookie)
                    throws TransactionException,
                           RemoteException,
                           InterruptedException
Description copied from interface: OutriggerServer
Find an entry in the space that matches the passed template and is visible to the passed transaction. Depending on the state of the space and the arguments this call may block if no entry can be immediately returned. The proxy can specify the maximum period it is willing to wait for a response using the timeout parameter. The proxy may choose to breakup a query from the client with a very long timeout into a set of sub-queries. In such cases it may get a QueryCookie as response to the sub-queries, in these cases it should pass the QueryCookie to the next sub-query (if any) associated with the same request from the client.

If a match is found it is returned as an EntryRep. If txn is non-null the entry is read locked by the transaction, this allows other queries to read, but not take the entry. The lock will be released when the transaction is aborted or prepared.

If no match can be initially found the call will block until either the timeout expires or for a detectable period of time there are no entries in the space (visible to the transaction or not) that match the passed template. If at some point there are no matching entries in the space null will be returned. If the timeout expires and there are matching entries in the space but none are visible to the passed transaction a QueryCookie will be returned.

Specified by:
readIfExists in interface OutriggerServer
Parameters:
tmpl - The template that describes the entry being searched for. May be null if any visible entry is acceptable.
txn - The transaction the operation should be performed under. Maybe be null. If non-null and entry is found it will read locked/removed under this transaction.
timeout - The maximum number of milliseconds this call should block in the server before returning an answer (this not necessarily the timeout the client asked for.) A value of 0 indicates the initial search should be performed, but if no match can be found null or a QueryCookie (as appropriate) should be returned immediately.
cookie - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
RemoteException - if a network failure occurs.
InterruptedException - if the thread in the server is interrupted before the query can be completed.

takeIfExists

public Object takeIfExists(EntryRep tmpl,
                           Transaction txn,
                           long timeout,
                           OutriggerServer.QueryCookie cookie)
                    throws TransactionException,
                           RemoteException,
                           InterruptedException
Description copied from interface: OutriggerServer
Find and remove an entry in the space that matches the passed template and is visible to the passed transaction. Depending on the state of the space and the arguments this call may block if no entry can be immediately returned. The proxy can specify the maximum period it is willing to wait for a response using the timeout parameter. The proxy may choose to breakup a query from the client with a very long timeout into a set of sub-queries. In such cases it may get a QueryCookie as response to the sub-queries, in these cases it should pass the QueryCookie to the next sub-query (if any) associated with the same request from the client.

If a match is found it is returned as an EntryRep. If txn is null the entry is removed from the space. If txn is non-null the entry is exclusively locked by the transaction and will be removed from the space if the transaction is committed.

If no match can be initially found the call will block until either the timeout expires or for a detectable period of time there are no entries in the space (visible to the transaction or not) that match the passed template. If at some point there are no matching entries in the space null will be returned. If the timeout expires and there are matching entries in the space but none are visible to the passed transaction a QueryCookie will be returned.

Specified by:
takeIfExists in interface OutriggerServer
Parameters:
tmpl - The template that describes the entry being searched for. May be null if any visible entry is acceptable.
txn - The transaction the operation should be performed under. Maybe be null. If non-null and entry is found it will read locked/removed under this transaction.
timeout - The maximum number of milliseconds this call should block in the server before returning an answer (this not necessarily the timeout the client asked for.) A value of 0 indicates the initial search should be performed, but if no match can be found null or a QueryCookie (as appropriate) should be returned immediately.
cookie - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
RemoteException - if a network failure occurs.
InterruptedException - if the thread in the server is interrupted before the query can be completed.

take

public Object take(EntryRep[] tmpls,
                   Transaction tr,
                   long timeout,
                   int limit,
                   OutriggerServer.QueryCookie queryCookieFromClient)
            throws TransactionException,
                   RemoteException
Description copied from interface: OutriggerServer
Find and remove up to limit entries in the space that match one or more of the passed templates and are visible to the passed transaction. Depending on the state of the space and the arguments this call may block if no entry can be immediately returned. The proxy can specify the maximum period it is willing to wait for a response using the timeout parameter. The proxy may choose to breakup a query from the client with a very long timeout into a set of sub-queries. In such cases it may get a QueryCookie as response to the sub-queries, in these cases it should pass the QueryCookie to the next sub-query (if any) associated with the same request from the client.

If matchs are found they are returned as in an array of EntryRep. If txn is null the entries are removed from the space. If txn is non-null the entries are exclusively locked by the transaction and will be removed from the space if the transaction is committed.

If there are no matches the call will block for up to the specified timeout for a match to appear. If there is still no match available the call will return a QueryCookie.

Specified by:
take in interface OutriggerServer
Parameters:
tmpls - The templates that describes the entries being searched for
tr - The transaction the operation should be performed under. Maybe be null. If non-null and entries are found they will removed under this transaction.
timeout - The maximum number of milliseconds this call should block in the server before returning an answer (this not necessarily the timeout the client asked for.) A value of 0 indicates the initial search should be performed, but if no match can be found a QueryCookie should be returned immediately.
limit - The maximum number of entries that should be taken
queryCookieFromClient - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
RemoteException - if a network failure occurs.

completeTake

private EntryRep[] completeTake(EntryHandle[] handles,
                                int found,
                                Txn txn)
                         throws TransactionException
Throws:
TransactionException

completeTake

private EntryRep completeTake(EntryHandle handle,
                              Txn txn)
                       throws TransactionException
Throws:
TransactionException

createQuery

private EntryHolder.ContinuingQuery createQuery(EntryRep[] tmpls,
                                                String clazz,
                                                Txn txn,
                                                boolean takeIt,
                                                long now)
Crerate a ContinuingQuery for the holder of the specified class.


waitOnProvisionallyRemovedEntries

private static void waitOnProvisionallyRemovedEntries(WeakHashMap provisionallyRemovedEntrySet)
                                               throws InterruptedException
Call waitOnCompleteRemoval on each of the EntryHandles in the passed set.

Throws:
InterruptedException

getMatch

private Object getMatch(EntryRep tmpl,
                        Transaction tr,
                        long timeout,
                        boolean takeIt,
                        boolean ifExists,
                        OutriggerServer.QueryCookie queryCookieFromClient)
                 throws RemoteException,
                        InterruptedException,
                        TransactionException
Do the heavy lifting for queries. Find a match, optionally taking it, blocking as appropriate if a match can't be initially found.

Parameters:
tmpl - The template for the query, may be null if all entries match.
tr - The transaction the query is being performed under, or null if there is no transaction.
timeout - Maxium time to block in milliseconds.
takeIt - true if the entry found is to be removed.
ifExists - true if this query is to follow the rules for ifExists queries.
queryCookieFromClient - If this call is a continuation of an earlier query, the cookie from the last sub-query.
Throws:
RemoteException - if a network failure occurs.
TransactionException - if there is a problem with the specified transaction such as it can not be joined, or leaves the active state before the call is complete.
InterruptedException - if the thread in the server is interrupted before the query can be completed.
SecurityException - if the server decides the caller has insufficient privilege to carry out the operation.
IllegalArgumentException - if a negative timeout value is used
InternalSpaceException - if there is an internal problem with the server.

monitor

private void monitor(QueryWatcher watcher,
                     Collection toMonitor)
Make sure the transactions listed here are monitored for as long as the given query exists.


monitor

void monitor(Collection toMonitor)
Make sure the transactions listed here are monitored for a reasonable amount of time since they recently caused a conflict, although for a non-leased event.


dump

void dump(String name,
          EntryRep rep)
Debug method: Dump out the bucket for the holder for the given rep.


dump

static void dump(EntryHolder holder,
                 String name,
                 EntryRep rep)
Debug method: Dump out the bucket for the given holder, for an operation using the given rep.


find

private EntryHandle find(EntryRep tmplRep,
                         Txn txn,
                         boolean takeIt,
                         Set conflictSet,
                         Set lockedEntrySet,
                         WeakHashMap provisionallyRemovedEntrySet)
                  throws TransactionException
Find an entry that is at least whichClass that matches the template tmplRep (at least the template's type, and matches in values provided). whichClass is at least the type of the template. If takeIt is true the matching entry is removed (perhaps provisionally).

Throws:
TransactionException

nextID

static long nextID()
Generate a new ID. IDs are generated from a SecureRandom object so that it is next to impossible to forge an ID and so we don't have to remember/restore a counter cross restarts.


contents

public MatchSetData contents(EntryRep[] tmpls,
                             Transaction tr,
                             long leaseTime,
                             long limit)
                      throws TransactionException,
                             RemoteException
Description copied from interface: OutriggerServer
Start a new contents query. Returns a MatchSetData with the initial batch of entries and (if applicable) the Uuid and initial lease duration. If the entire result set is contained in the returned MatchSetData the Uuid will be null and the lease duration will be -1.

Specified by:
contents in interface OutriggerServer
Parameters:
tmpls - the templates to use for the iteration
tr - the transaction to perform the iteration under, may be null
leaseTime - the requested lease time
limit - the maximum number of entries to return
Returns:
A MatchSetData with the initial batch of entries and (if applicable) the Uuid and initial lease duration. Initial batch will be the empty array if there are no matching entries in the space
Throws:
TransactionException - if tr is non-null and can't be used
RemoteException

nextBatch

public EntryRep[] nextBatch(Uuid contentsQueryUuid,
                            Uuid entryUuid)
                     throws NoSuchObjectException
Description copied from interface: OutriggerServer
Return the next batch of entries associated with the specified contents query. If the returned array is not full then the query is complete.

Specified by:
nextBatch in interface OutriggerServer
Parameters:
contentsQueryUuid - the id of the contents query
entryUuid - the id of the last entry in the last batch. If this does not match what the server has on recored it will re-send the previous batch.
Returns:
an array of EntryReps representing the next batch of entries from the query. Query is complete if array is not full. Returns an empty array if there are no entries left
Throws:
NoSuchObjectException - if the server has no record of contentsQueryUuid

getServiceProxy

public Object getServiceProxy()
Description copied from interface: ServiceProxyAccessor
Returns a proxy object for this object. This value should not be null.

Specified by:
getServiceProxy in interface ServiceProxyAccessor
Returns:
a proxy object reference

getProxy

Object getProxy()

getAdmin

public Object getAdmin()
Return a proxy that implements that JavaSpaceAdmin interface.

Specified by:
getAdmin in interface OutriggerServer
See Also:
JavaSpaceAdmin

space

public JavaSpace space()
Description copied from interface: OutriggerAdmin
Return the space administered by this object.

Specified by:
space in interface OutriggerAdmin

contents

public Uuid contents(EntryRep tmpl,
                     Transaction tr)
              throws TransactionException,
                     RemoteException
Description copied from interface: OutriggerAdmin
Return the remote iterator object needed by JavaSpaceAdmin.contents.

Specified by:
contents in interface OutriggerAdmin
Throws:
TransactionException
RemoteException

nextReps

public EntryRep[] nextReps(Uuid iterationUuid,
                           int max,
                           Uuid entryUuid)
                    throws NoSuchObjectException
Description copied from interface: OutriggerAdmin
Fetch up to max EntryRep objects from the specified iteration.

Specified by:
nextReps in interface OutriggerAdmin
Parameters:
iterationUuid - The Uuid of the iteration to fetch entries from.
max - Advice on the number of entries to return
entryUuid - Uuid of the last entry received by the caller. If this does not match the ID of the last entry sent by the iterator will re-send that last batch in place of a new batch. May be null in which case a new batch will be sent. The first call to next() should have id set to null
Throws:
NoSuchObjectException

delete

public void delete(Uuid iterationUuid,
                   Uuid entryUuid)
            throws NoSuchObjectException
Description copied from interface: OutriggerAdmin
Delete the given entry if the given iteration is still valid and the entry was retured by the last call to nextReps.

Specified by:
delete in interface OutriggerAdmin
Parameters:
iterationUuid - The Uuid of a valid iteration.
entryUuid - the Uuid of the entry to be deleted.
Throws:
NoSuchObjectException

close

public void close(Uuid iterationUuid)
           throws NoSuchObjectException
Description copied from interface: OutriggerAdmin
Forget about the indicated iteration

Specified by:
close in interface OutriggerAdmin
Parameters:
iterationUuid - The Uuid iteration to close.
Throws:
NoSuchObjectException

destroy

public void destroy()
Destroy this space, exiting when finished. This unregisters itself and related objects, and then destroys the persistent state.

Specified by:
destroy in interface DestroyAdmin

destroyReaper

private void destroyReaper(OutriggerServerImpl.Reaper r)
Shutdown a reaper as part of a controlled tear-down


joinThread

private void joinThread(Thread t)
Join a thread as part of a controlled tear-down


logDestroyProblem

private void logDestroyProblem(String part,
                               Throwable t)
log exception encountered in destroy thread


logDestroyPhase

private void logDestroyPhase(String part)
log phase of destroy thread


getLookupAttributes

public Entry[] getLookupAttributes()
Description copied from interface: JoinAdmin
Get the current attribute sets for the service.

Specified by:
getLookupAttributes in interface JoinAdmin
Returns:
the current attribute sets for the service

addLookupAttributes

public void addLookupAttributes(Entry[] attrSets)
Description copied from interface: JoinAdmin
Add attribute sets for the service. The resulting set will be used for all future joins. The attribute sets are also added to all currently-joined lookup services.

Specified by:
addLookupAttributes in interface JoinAdmin
Parameters:
attrSets - the attribute sets to add

modifyLookupAttributes

public void modifyLookupAttributes(Entry[] attrSetTemplates,
                                   Entry[] attrSets)
Description copied from interface: JoinAdmin
Modify the current attribute sets, using the same semantics as ServiceRegistration.modifyAttributes. The resulting set will be used for all future joins. The same modifications are also made to all currently-joined lookup services.

Specified by:
modifyLookupAttributes in interface JoinAdmin
Parameters:
attrSetTemplates - the templates for matching attribute sets
attrSets - the modifications to make to matching sets
See Also:
ServiceRegistration.modifyAttributes(net.jini.core.entry.Entry[], net.jini.core.entry.Entry[])

getLookupGroups

public String[] getLookupGroups()
Description copied from interface: JoinAdmin
Get the list of groups to join. An empty array means the service joins no groups (as opposed to "all" groups).

Specified by:
getLookupGroups in interface JoinAdmin
Returns:
an array of groups to join. An empty array means the service joins no groups (as opposed to "all" groups).
See Also:
JoinAdmin.setLookupGroups(java.lang.String[])

addLookupGroups

public void addLookupGroups(String[] groups)
Description copied from interface: JoinAdmin
Add new groups to the set to join. Lookup services in the new groups will be discovered and joined.

Specified by:
addLookupGroups in interface JoinAdmin
Parameters:
groups - groups to join
See Also:
JoinAdmin.removeLookupGroups(java.lang.String[])

removeLookupGroups

public void removeLookupGroups(String[] groups)
Description copied from interface: JoinAdmin
Remove groups from the set to join. Leases are cancelled at lookup services that are not members of any of the remaining groups.

Specified by:
removeLookupGroups in interface JoinAdmin
Parameters:
groups - groups to leave
See Also:
JoinAdmin.addLookupGroups(java.lang.String[])

setLookupGroups

public void setLookupGroups(String[] groups)
Description copied from interface: JoinAdmin
Replace the list of groups to join with a new list. Leases are cancelled at lookup services that are not members of any of the new groups. Lookup services in the new groups will be discovered and joined.

Specified by:
setLookupGroups in interface JoinAdmin
Parameters:
groups - groups to join
See Also:
JoinAdmin.getLookupGroups()

getLookupLocators

public LookupLocator[] getLookupLocators()
Description copied from interface: JoinAdmin
Get the list of locators of specific lookup services to join.

Specified by:
getLookupLocators in interface JoinAdmin
Returns:
the list of locators of specific lookup services to join
See Also:
JoinAdmin.setLookupLocators(net.jini.core.discovery.LookupLocator[])

addLookupLocators

public void addLookupLocators(LookupLocator[] locators)
                       throws RemoteException
Description copied from interface: JoinAdmin
Add locators for specific new lookup services to join. The new lookup services will be discovered and joined.

Specified by:
addLookupLocators in interface JoinAdmin
Parameters:
locators - locators of specific lookup services to join
Throws:
RemoteException
See Also:
JoinAdmin.removeLookupLocators(net.jini.core.discovery.LookupLocator[])

removeLookupLocators

public void removeLookupLocators(LookupLocator[] locators)
                          throws RemoteException
Description copied from interface: JoinAdmin
Remove locators for specific lookup services from the set to join. Any leases held at the lookup services are cancelled.

Specified by:
removeLookupLocators in interface JoinAdmin
Parameters:
locators - locators of specific lookup services to leave
Throws:
RemoteException
See Also:
JoinAdmin.addLookupLocators(net.jini.core.discovery.LookupLocator[])

setLookupLocators

public void setLookupLocators(LookupLocator[] locators)
                       throws RemoteException
Description copied from interface: JoinAdmin
Replace the list of locators of specific lookup services to join with a new list. Leases are cancelled at lookup services that were in the old list but are not in the new list. Any new lookup services will be discovered and joined.

Specified by:
setLookupLocators in interface JoinAdmin
Parameters:
locators - locators of specific lookup services to join
Throws:
RemoteException
See Also:
JoinAdmin.getLookupLocators()

recoverSessionId

public void recoverSessionId(long sessionId)
Recover the id from the previous session and determine the new basis value for the seq numbers issued by this session. The typical usage for this routine is to read from permanent store somehow the previous sessionId (basis) for sequence numbers used by the last invocation of Outrigger. This value is then passed into this routine where a new basis is computed. That newly computed value should then be stored in persistent store so the next time we crash we can bump the value again. Once the store has recovered the new sessionId should be persisted by calling bootOp(...,sessionId)

Specified by:
recoverSessionId in interface Recover
Parameters:
sessionId - Value used by the previous invocation of Outrigger
See Also:
LogOps.bootOp(long, long)

recoverJoinState

public void recoverJoinState(StoredObject state)
                      throws Exception
Description copied from interface: Recover
Recover the join state from the previous session.

Specified by:
recoverJoinState in interface Recover
Parameters:
state - is the stored join state
Throws:
Exception
See Also:
LogOps.joinStateOp(com.sun.jini.outrigger.StorableObject)

recoverWrite

public void recoverWrite(StoredResource entry,
                         Long txnId)
                  throws Exception
Description copied from interface: Recover
Recover a write operation. The recovered entry is the stored form of the entry passed into writeOp. If the original write was done under a transaction, and the transaction was prepared txnId will be non-null.

Specified by:
recoverWrite in interface Recover
Parameters:
entry - stored from of the written entry
txnId - transaction identifier or null
Throws:
Exception - is thrown if any error occurs recovering the write
See Also:
LogOps.writeOp(com.sun.jini.outrigger.StorableResource, java.lang.Long)

recoverTake

public void recoverTake(Uuid cookie,
                        Long txnId)
                 throws Exception
Description copied from interface: Recover
Recover a take operation. If the original take was done under a transaction, and the transaction was prepared, txnId will be non-null.

Specified by:
recoverTake in interface Recover
Parameters:
cookie - identifier of the entry to take
txnId - transaction identifier or null
Throws:
Exception - is thrown if any error occurs recovering the take
See Also:
LogOps.takeOp(net.jini.id.Uuid, java.lang.Long)

recoverTransaction

public void recoverTransaction(Long txnId,
                               StoredObject transaction)
                        throws Exception
Description copied from interface: Recover
Recover a prepared transaction. The recovered transaction is the stored form of the transaction passed into prepareOp.

Specified by:
recoverTransaction in interface Recover
Parameters:
txnId - transaction identifier
transaction - stored from of the prepared transaction
Throws:
Exception - is thrown if any error occurs recovering the transaction
See Also:
LogOps.prepareOp(java.lang.Long, com.sun.jini.outrigger.StorableObject)

getRecoveredTxn

private Txn getRecoveredTxn(Long txnId)

recoverRegister

public void recoverRegister(StoredResource registration,
                            String type,
                            StoredObject[] storedTemplates)
                     throws Exception
Description copied from interface: Recover
Recover an event registration. The recovered registration is the stored form of the registration passed into registerOp. The recovered template is the stored form of the template.

Specified by:
recoverRegister in interface Recover
Parameters:
registration - stored from of the logged registration
type - of registration, same value that was passed into corresponding registerOp call
storedTemplates - stored from of the logged templates
Throws:
Exception - is thrown if any error occurs recovering the registration
See Also:
LogOps.registerOp(com.sun.jini.outrigger.StorableResource, java.lang.String, com.sun.jini.outrigger.StorableObject[])

recoverUuid

public void recoverUuid(Uuid uuid)
Description copied from interface: Recover
Recover the Uuid for the service as a whole. Will only be called if a Uuid has be stored during a previous incarnation.

Specified by:
recoverUuid in interface Recover
Parameters:
uuid - The Uuid being recovered.
See Also:
LogOps.uuidOp(net.jini.id.Uuid)

getProxyVerifier

public TrustVerifier getProxyVerifier()
Description copied from interface: ServerProxyTrust
Returns a TrustVerifier that can be used to verify that a proxy can be trusted as a proxy for the service; that is, the isTrustedObject method of the returned verifier can be called with a candidate proxy. The verifier should be able to verify all proxies for the service, including proxies for resources (such as leases and registrations).

Specified by:
getProxyVerifier in interface ServerProxyTrust
Returns:
a TrustVerifier that can be used to verify that a proxy can be trusted as a proxy for the service

enterTxn

private Txn enterTxn(Transaction baseTr)
              throws TransactionException,
                     RemoteException
This method takes a transactional semantic object baseTr (the transaction object passed to us by the client) and retrieves the associated Txn object (the internal representation for that transaction) from the space's records. If no Txn object is associated with the given semantic object, a new Txn object is created, associated and recorded.

Throws:
TransactionException
RemoteException

getTxn

private Txn getTxn(TransactionManager mgr,
                   long id)
            throws UnknownTransactionException,
                   UnmarshalException
Look in the table for the Txn object for the given manager/id pair. If there is one, return it. If there isn't one, throw UnknownTransactionException.

Throws:
UnknownTransactionException
UnmarshalException

brokenTxn

private UnmarshalException brokenTxn(TransactionManager mgr,
                                     long id,
                                     Exception nested)
                              throws UnmarshalException
Create, log, and throw a new UnmarshalException to represent a transaction recovery failure

Throws:
UnmarshalException

serverTransaction

private ServerTransaction serverTransaction(Transaction baseTr)
                                     throws UnknownTransactionException
We assume that each Transaction object sent to the space is actually the ServerTransaction subtype. This method does the downcast, and turns an error into the appropriate UnknownTransactionException exception.

Throws:
UnknownTransactionException

prepare

public int prepare(TransactionManager mgr,
                   long id)
            throws UnknownTransactionException,
                   UnmarshalException
Description copied from interface: TransactionParticipant
Requests that the participant prepare itself to commit the transaction, and to vote on the outcome of the transaction. The participant responds with either PREPARED, indicating that it is prepared; ABORT, indicating that it will abort, or NOTCHANGED, indicating that it did not have any state changed by the transaction (i.e., it was read-only). If the response is PREPARED, the participant must wait until it receives a commit or abort call from the transaction manager; it may query the transaction manager if needed as to the state of the transaction. If the response is ABORT, the participant should roll its state back to undo any changes that occurred due to operations performed under the transaction; it can then discard any information about the transaction. If the response is NOTCHANGED, the participant can immediately discard any knowledge of the transaction.

Specified by:
prepare in interface TransactionParticipant
Parameters:
mgr - the manager of the transaction
id - the transaction ID
Returns:
an int representing this participant's state
Throws:
UnknownTransactionException - if the transaction is unknown to the transaction manager, either because the transaction ID is incorrect or because the transaction is complete and its state has been discarded by the manager.
UnmarshalException

commit

public void commit(TransactionManager mgr,
                   long id)
            throws UnknownTransactionException,
                   UnmarshalException
Description copied from interface: TransactionParticipant
Requests that the participant make all of its PREPARED changes for the specified transaction visible outside of the transaction and unlock any resources locked by the transaction. All state associated with the transaction can then be discarded by the participant.

Specified by:
commit in interface TransactionParticipant
Parameters:
mgr - the manager of the transaction
id - the transaction ID
Throws:
UnknownTransactionException - if the transaction is unknown to the transaction manager, either because the transaction ID is incorrect or because the transaction is complete and its state has been discarded by the manager.
UnmarshalException

abort

public void abort(TransactionManager mgr,
                  long id)
           throws UnknownTransactionException,
                  UnmarshalException
Description copied from interface: TransactionParticipant
Requests that the participant roll back any changes for the specified transaction and unlock any resources locked by the transaction. All state associated with the transaction can then be discarded by the participant.

Specified by:
abort in interface TransactionParticipant
Parameters:
mgr - the manager of the transaction
id - the transaction ID
Throws:
UnknownTransactionException - if the transaction is unknown to the transaction manager, either because the transaction ID is incorrect or because the transaction is complete and its state has been discarded by the manager.
UnmarshalException

prepareAndCommit

public int prepareAndCommit(TransactionManager mgr,
                            long id)
                     throws UnknownTransactionException,
                            UnmarshalException
Description copied from interface: TransactionParticipant
A combination of prepare and commit, which can be used by the manager when there is just one participant left to prepare and all other participants (if any) have responded with NOTCHANGED. The participant's implementation of this method must be equivalent to:
        public int prepareAndCommit(TransactionManager mgr, long id)
            throws UnknownTransactionException, RemoteException
        {
            int result = prepare(mgr, id);
            if (result == PREPARED) {
                commit(mgr, id);
                result = COMMITTED;
            }
            return result;
        }
 

Specified by:
prepareAndCommit in interface TransactionParticipant
Parameters:
mgr - the manager of the transaction
id - the transaction ID
Returns:
an int representing its state
Throws:
UnknownTransactionException - if the transaction is unknown to the transaction manager, either because the transaction ID is incorrect or because the transaction is complete and its state has been discarded by the manager.
UnmarshalException
See Also:
TransactionParticipant.prepare(net.jini.core.transaction.server.TransactionManager, long), TransactionParticipant.commit(net.jini.core.transaction.server.TransactionManager, long)

getRecoveredTransactionManagerPreparer

ProxyPreparer getRecoveredTransactionManagerPreparer()
Return the proxy preparer for recovered transaction managers, or null if there is none.

Returns:
the proxy preparer for recovered transaction managers, or null if there is none.

debug

private final void debug(Object obj,
                         String str)
Print out a debug description of obj, followed by the given str.


attributesFor

private static Entry[] attributesFor()
Create the service-owned attributes for an Outrigger server.


logAndThrow

private RuntimeException logAndThrow(RuntimeException e,
                                     Logger logger)
Log and throw the passed runtime exception


logAndThrowIllegalArg

private IllegalArgumentException logAndThrowIllegalArg(String msg)
Log and throw a new IllegalArgumentException. Logs to the opsLogger.


throwNewUnknownLeaseException

private UnknownLeaseException throwNewUnknownLeaseException(Object cookie)
                                                     throws UnknownLeaseException
Log and throw a new UnknownLeaseException

Throws:
UnknownLeaseException

throwNewCannotJoinException

private CannotJoinException throwNewCannotJoinException()
                                                 throws CannotJoinException
Log and throw new CannotJoinException

Throws:
CannotJoinException

throwNewNoSuchObjectException

private NoSuchObjectException throwNewNoSuchObjectException(String msg,
                                                            Logger logger)
                                                     throws NoSuchObjectException
Log and throw new NoSuchObjectException

Throws:
NoSuchObjectException

throwNewNoSuchObjectException

private NoSuchObjectException throwNewNoSuchObjectException(String msg,
                                                            Throwable t,
                                                            Logger logger)
                                                     throws NoSuchObjectException
Log and throw new NoSuchObjectException with a nested exception

Throws:
NoSuchObjectException


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