You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@river.apache.org by ni...@apache.org on 2008/12/10 06:13:55 UTC

svn commit: r724979 [8/14] - in /incubator/river/jtsk/skunk/niclas1/services/outrigger: ./ src/ src/main/ src/main/java/ src/main/java/com/ src/main/java/com/sun/ src/main/java/com/sun/jini/ src/main/java/com/sun/jini/outrigger/ src/main/java/com/sun/j...

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/SpaceProxy2.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/SpaceProxy2.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/SpaceProxy2.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/SpaceProxy2.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,907 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import com.sun.jini.landlord.LandlordLease;
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.rmi.MarshalException;
+import java.rmi.MarshalledObject;
+import java.rmi.RemoteException;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import net.jini.admin.Administrable;
+import net.jini.core.entry.Entry;
+import net.jini.core.entry.UnusableEntryException;
+import net.jini.core.event.EventRegistration;
+import net.jini.core.event.RemoteEventListener;
+import net.jini.core.lease.Lease;
+import net.jini.core.transaction.Transaction;
+import net.jini.core.transaction.TransactionException;
+import net.jini.entry.UnusableEntriesException;
+import net.jini.id.ReferentUuid;
+import net.jini.id.ReferentUuids;
+import net.jini.id.Uuid;
+import net.jini.id.UuidFactory;
+import net.jini.security.Security;
+import net.jini.space.JavaSpace05;
+import net.jini.space.MatchSet;
+
+/**
+ * This class is the client-side proxy for the Outrigger
+ * implementation of a JavaSpaces<sup><font size=-2>TM</font></sup>
+ * service.  <code>OutriggerServerImpl</code> implements the
+ * <code>OutriggerSpace</code> interface, and each
+ * <code>SpaceProxy2</code> object holds a reference to the remote
+ * OutriggerSpace server it represents to the client. The client makes
+ * calls from the <code>JavaSpace</code> interface, which the
+ * <code>SpaceProxy2</code> translates into appropriate
+ * <code>OutriggerSpace</code> calls to the
+ * <code>OutriggerServerImpl</code> server.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see OutriggerSpace
+ */
+class SpaceProxy2 implements JavaSpace05, Administrable, ReferentUuid,
+                             Serializable
+{
+    static final long serialVersionUID = 1L;
+
+    /**
+     * The remote server this proxy works with.
+     * Package protected so it can be read by subclasses and proxy verifier
+     *
+     * @serial
+     */
+    final OutriggerServer space;
+
+    /**
+     * The <code>Uuid</code> that identifies the space this proxy is for.
+     * Package protected so it can be read by subclasses and proxy verifier
+     *
+     * @serial
+     */
+    final Uuid spaceUuid;
+
+    /**
+     * The value to use for maxServerQueryTimeout if no
+     * local value is provided. Package protected so it can be read by
+     * subclasses.
+     *
+     * @serial
+     */
+    final long serverMaxServerQueryTimeout;
+
+    /**
+     * Maximum time any sub-query should be allowed to run for.
+     */
+    private transient long maxServerQueryTimeout;
+
+
+    /**
+     * Value (as a long) of the
+     * <code>com.sun.jini.outrigger.maxServerQueryTimeout</code>
+     * property in this VM, or a non-positive number if it is not set.
+     */
+    private static final long maxServerQueryTimeoutPropertyValue =
+        getMaxServerQueryTimeoutPropertyValue();
+
+    /**
+     * Logger for logging information about operations carried out in
+     * the client. Note, we hard code "com.sun.jini.outrigger" so
+     * we don't drag in OutriggerServerImpl to outrigger-dl.jar.
+     */
+    private static final Logger logger =
+        Logger.getLogger( "com.sun.jini.outrigger.proxy" );
+
+    // --------------------------------------------------
+    //		Construction
+    // --------------------------------------------------
+
+    /**
+     * Create a new <code>SpaceProxy2</code> for the given space.
+     *
+     * @param space                       The <code>OutriggerServer</code> for the
+     *                                    space.
+     * @param spaceUuid                   The universally unique ID for the
+     *                                    space
+     * @param serverMaxServerQueryTimeout The value this proxy
+     *                                    should use for the <code>maxServerQueryTimeout</code>
+     *                                    if no local value is provided.
+     * @throws NullPointerException     if <code>space</code> or
+     *                                  <code>spaceUuid</code> is <code>null</code>.
+     * @throws IllegalArgumentException if
+     *                                  <code>serverMaxServerQueryTimeout</code> is not
+     *                                  larger than zero.
+     */
+    SpaceProxy2( OutriggerServer space, Uuid spaceUuid,
+                 long serverMaxServerQueryTimeout )
+    {
+        if( space == null )
+        {
+            throw new NullPointerException( "space must be non-null" );
+        }
+        if( spaceUuid == null )
+        {
+            throw new NullPointerException( "spaceUuid must be non-null" );
+        }
+        if( serverMaxServerQueryTimeout <= 0 )
+        {
+            throw new
+                IllegalArgumentException( "serverMaxServerQueryTimeout " +
+                                          "must be positive" );
+        }
+        this.space = space;
+        this.spaceUuid = spaceUuid;
+        this.serverMaxServerQueryTimeout = serverMaxServerQueryTimeout;
+        setMaxServerQueryTimeout();
+    }
+
+    public String toString()
+    {
+        return getClass().getName() + " for " + spaceUuid +
+               " (through " + space + ")";
+    }
+
+    // inherit doc comment
+    public boolean equals( Object other )
+    {
+        return ReferentUuids.compare( this, other );
+    }
+
+    // inherit doc comment
+    public int hashCode()
+    {
+        return spaceUuid.hashCode();
+    }
+
+    public Uuid getReferentUuid()
+    {
+        return spaceUuid;
+    }
+
+    /**
+     * Safely read the value of
+     * <code>com.sun.jini.outrigger.maxServerQueryTimeout</code>.
+     * If it can't be read return -1.
+     */
+    private static long getMaxServerQueryTimeoutPropertyValue()
+    {
+        try
+        {
+            final String propValue =
+                (String) Security.doPrivileged(
+                    new ReadProperityPrivilegedAction(
+                        "com.sun.jini.outrigger.maxServerQueryTimeout" ) );
+            if( propValue == null )
+            {
+                return -1;
+            }
+
+            // Note, if we throw NumberFormatException we return -1.
+            return Long.parseLong( propValue );
+        }
+        catch( Throwable t )
+        {
+            return -1;
+        }
+    }
+
+    /**
+     * PrivilegedAction for reading a property. Returns a string.
+     */
+    private static class ReadProperityPrivilegedAction
+        implements PrivilegedAction
+    {
+        /**
+         * Property to read
+         */
+        final private String propName;
+
+        /**
+         * Construct a ReadProperityPrivilegedAction that will read
+         * the specified property.
+         */
+        ReadProperityPrivilegedAction( String propName )
+        {
+            this.propName = propName;
+        }
+
+        public Object run()
+        {
+            try
+            {
+                return System.getProperty( propName );
+            }
+            catch( SecurityException e )
+            {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Set <code>maxServerQueryTimeout</code> based on the values
+     * of <code>serverMaxServerQueryTimeout</code> and
+     * <code>maxServerQueryTimeoutPropertyValue</code>.
+     */
+    private void setMaxServerQueryTimeout()
+    {
+        /* If the com.sun.jini.outrigger.maxServerQueryTimeout property
+       * was set in this VM, override the value set by the server
+       * when we were created.
+       */
+        if( maxServerQueryTimeoutPropertyValue > 0 )
+        {
+            maxServerQueryTimeout = maxServerQueryTimeoutPropertyValue;
+        }
+        else if( serverMaxServerQueryTimeout > 0 )
+        {
+            maxServerQueryTimeout = serverMaxServerQueryTimeout;
+        }
+        else
+            /* should never get here, the constructor and readObject
+            * check to make sure that serverMaxServerQueryTimeout
+            * is positive.
+            */
+        {
+            throw new
+                AssertionError( "serverMaxServerQueryTimeout invalid:" +
+                                serverMaxServerQueryTimeout );
+        }
+
+        if( logger.isLoggable( Level.CONFIG ) )
+        {
+            logger.log( Level.CONFIG,
+                        "Outrigger proxy using {0} ms for maxServerQueryTimeout",
+                        new Long( maxServerQueryTimeout ) );
+        }
+    }
+
+    /**
+     * Read this object back setting the <code>maxServerQueryTimeout</code>
+     * field and validate state.
+     */
+    private void readObject( ObjectInputStream in )
+        throws IOException, ClassNotFoundException
+    {
+        in.defaultReadObject();
+
+        if( space == null )
+        {
+            throw new InvalidObjectException( "null server reference" );
+        }
+
+        if( spaceUuid == null )
+        {
+            throw new InvalidObjectException( "null Uuid" );
+        }
+
+        if( serverMaxServerQueryTimeout <= 0 )
+        {
+            throw new
+                InvalidObjectException( "Bad serverMaxServerQueryTimeout " +
+                                        "value:" + serverMaxServerQueryTimeout );
+        }
+
+        setMaxServerQueryTimeout();
+    }
+
+    /**
+     * We should always have data in the stream, if this method
+     * gets called there is something wrong.
+     */
+    private void readObjectNoData() throws InvalidObjectException
+    {
+        throw new
+            InvalidObjectException( "SpaceProxy2 should always have data" );
+    }
+
+    // --------------------------------------------------
+    //		JavaSpace method implementations
+    // --------------------------------------------------
+
+    // inherit doc comment
+
+    public Lease write( Entry entry, Transaction txn, long lease )
+        throws TransactionException, RemoteException
+    {
+        if( entry == null )
+        {
+            throw new NullPointerException( "Cannot write null Entry" );
+        }
+        long[] leaseData = space.write( repFor( entry ), txn, lease );
+        if( leaseData == null || leaseData.length != 3 )
+        {
+            throw new AssertionError( "space.write returned malformed data" +
+                                      leaseData );
+        }
+        return newLease( UuidFactory.create( leaseData[ 1 ], leaseData[ 2 ] ),
+                         leaseData[ 0 ] );
+    }
+
+    public Entry read( Entry tmpl, Transaction txn, long timeout )
+        throws UnusableEntryException, TransactionException,
+               InterruptedException, RemoteException
+    {
+        // Figure out the max time this query should last
+        final long endTime = calcEndTime( timeout );
+
+        long remaining = timeout;
+        OutriggerServer.QueryCookie queryCookie = null;
+
+        // Loop util timeout or we get an answer (call at least once!)
+        do
+        {
+            final long serverTimeout =
+                Math.min( remaining, maxServerQueryTimeout );
+            logQuery( "read", serverTimeout, queryCookie, remaining );
+
+            final Object rslt =
+                space.read( repFor( tmpl ), txn, serverTimeout, queryCookie );
+            if( rslt == null )
+            {
+                // should never get null from a non-ifExists query
+                throw new AssertionError( "space.read() returned null" );
+            }
+            else if( rslt instanceof EntryRep )
+            {
+                // Got an answer, return it
+                return entryFrom( (EntryRep) rslt );
+            }
+            else if( rslt instanceof OutriggerServer.QueryCookie )
+            {
+                /* Will still want to go on if there is time, but pass
+             * the new cookie
+             */
+                queryCookie = (OutriggerServer.QueryCookie) rslt;
+            }
+            else
+            {
+                throw new AssertionError(
+                    "Unexpected return type from space.read()" );
+            }
+
+            /* Update remaining and loop, checking to see if the timeout has
+            * expired.
+            */
+            remaining = endTime - System.currentTimeMillis();
+        }
+        while( remaining > 0 );
+
+        /* If we get here then there must not have been an entry available
+       * to us before the endTime.
+       */
+        return null;
+    }
+
+    // inherit doc comment, use internal routine for common code
+    public Entry readIfExists( Entry tmpl, Transaction txn, long timeout )
+        throws UnusableEntryException, TransactionException,
+               InterruptedException, RemoteException
+    {
+        // Figure out the max time this query should last
+        final long endTime = calcEndTime( timeout );
+
+        long remaining = timeout;
+        OutriggerServer.QueryCookie queryCookie = null;
+
+        // Loop util timeout or we get an answer (call at least once!)
+        do
+        {
+            final long serverTimeout =
+                Math.min( remaining, maxServerQueryTimeout );
+            logQuery( "readIfExists", serverTimeout, queryCookie, remaining );
+
+            final Object rslt =
+                space.readIfExists( repFor( tmpl ), txn, serverTimeout,
+                                    queryCookie );
+            if( rslt == null )
+            {
+                // Must be no matches in the space at all
+                return null;
+            }
+            else if( rslt instanceof EntryRep )
+            {
+                // Got an answer, return it
+                return entryFrom( (EntryRep) rslt );
+            }
+            else if( rslt instanceof OutriggerServer.QueryCookie )
+            {
+                /* Will still want to go on if there is time, but pass
+             * the new cookie
+             */
+                queryCookie = (OutriggerServer.QueryCookie) rslt;
+            }
+            else
+            {
+                throw new AssertionError(
+                    "Unexpected return type from space.readIfExists()" );
+            }
+
+            /* Update remaining and loop, checking to see if the timeout has
+            * expired.
+            */
+            remaining = endTime - System.currentTimeMillis();
+        }
+        while( remaining > 0 );
+
+        /* If we get here then there must not have been an entry available
+       * to us before the endTime.
+       */
+        return null;
+    }
+
+    // inherit doc comment, use internal routine for common code
+    public Entry take( Entry tmpl, Transaction txn, long timeout )
+        throws UnusableEntryException, TransactionException,
+               InterruptedException, RemoteException
+    {
+        // Figure out the max time this query should last
+        final long endTime = calcEndTime( timeout );
+
+        long remaining = timeout;
+        OutriggerServer.QueryCookie queryCookie = null;
+
+        // Loop util timeout or we get an answer (call at least once!)
+        do
+        {
+            final long serverTimeout =
+                Math.min( remaining, maxServerQueryTimeout );
+            logQuery( "take", serverTimeout, queryCookie, remaining );
+
+            final Object rslt =
+                space.take( repFor( tmpl ), txn, serverTimeout, queryCookie );
+            if( rslt == null )
+            {
+                // should never get null from a non-ifExists query
+                throw new AssertionError( "space.take() returned null" );
+            }
+            else if( rslt instanceof EntryRep )
+            {
+                // Got an answer, return it
+                return entryFrom( (EntryRep) rslt );
+            }
+            else if( rslt instanceof OutriggerServer.QueryCookie )
+            {
+                /* Will still want to go on if there is time, but pass
+             * the new cookie
+             */
+                queryCookie = (OutriggerServer.QueryCookie) rslt;
+            }
+            else
+            {
+                throw new AssertionError(
+                    "Unexpected return type from space.take()" );
+            }
+
+            /* Update remaining and loop, checking to see if the timeout has
+            * expired.
+            */
+            remaining = endTime - System.currentTimeMillis();
+        }
+        while( remaining > 0 );
+
+        /* If we get here then there must not have been an entry available
+       * to us before the endTime.
+       */
+        return null;
+    }
+
+    // inherit doc comment, use internal routine for common code
+    public Entry takeIfExists( Entry tmpl, Transaction txn, long timeout )
+        throws UnusableEntryException, TransactionException,
+               InterruptedException, RemoteException
+    {
+        // Figure out the max time this query should last
+        final long endTime = calcEndTime( timeout );
+
+        long remaining = timeout;
+        OutriggerServer.QueryCookie queryCookie = null;
+
+        // Loop util timeout or we get an answer (call at least once!)
+        do
+        {
+            final long serverTimeout =
+                Math.min( remaining, maxServerQueryTimeout );
+            logQuery( "takeIfExists", serverTimeout, queryCookie, remaining );
+
+            final Object rslt =
+                space.takeIfExists( repFor( tmpl ), txn, serverTimeout,
+                                    queryCookie );
+            if( rslt == null )
+            {
+                // Must be no matches in the space at all
+                return null;
+            }
+            else if( rslt instanceof EntryRep )
+            {
+                // Got an answer, return it
+                return entryFrom( (EntryRep) rslt );
+            }
+            else if( rslt instanceof OutriggerServer.QueryCookie )
+            {
+                /* Will still want to go on if there is time, but pass
+             * the new cookie
+             */
+                queryCookie = (OutriggerServer.QueryCookie) rslt;
+            }
+            else
+            {
+                throw new AssertionError(
+                    "Unexpected return type from space.takeIfExists()" );
+            }
+
+            /* Update remaining and loop, checking to see if the timeout has
+            * expired.
+            */
+            remaining = endTime - System.currentTimeMillis();
+        }
+        while( remaining > 0 );
+
+        /* If we get here then there must not have been an entry available
+       * to us before the endTime.
+       */
+        return null;
+    }
+
+    // inherit doc comment
+    public Entry snapshot( Entry entry ) throws MarshalException
+    {
+        if( entry == null )
+        {
+            return null;
+        }
+        else
+        {
+            return new SnapshotRep( entry );
+        }
+    }
+
+    // inherit doc comment
+    public EventRegistration
+    notify( Entry tmpl, Transaction txn, RemoteEventListener listener,
+            long lease, MarshalledObject handback )
+        throws TransactionException, RemoteException
+    {
+        return space.notify( repFor( tmpl ), txn, listener, lease, handback );
+    }
+
+    public List write( List entries, Transaction txn, List leaseDurations )
+        throws RemoteException, TransactionException
+    {
+        final long[] leases = new long[leaseDurations.size()];
+        int j = 0;
+        for( Iterator i = leaseDurations.iterator(); i.hasNext(); )
+        {
+            final Object l = i.next();
+
+            if( l == null )
+            {
+                throw new NullPointerException(
+                    "leaseDurations contatins a null element" );
+            }
+
+            if( !( l instanceof Long ) )
+            {
+                throw new IllegalArgumentException(
+                    "leaseDurations contatins an element which is not a Long" );
+            }
+
+            leases[ j++ ] = ( (Long) l ).longValue();
+        }
+
+        long[] leaseData = space.write( repFor( entries, "entries" ), txn, leases );
+        if( leaseData == null )
+        {
+            throw new AssertionError( "space.write<multiple> returned null" );
+        }
+
+        final List rslt = new ArrayList( leaseData.length / 3 );
+        try
+        {
+            int m = 0;
+            while( m < leaseData.length )
+            {
+                final long duration = leaseData[ m++ ];
+                final long high = leaseData[ m++ ];
+                final long low = leaseData[ m++ ];
+                final Uuid uuid = UuidFactory.create( high, low );
+                rslt.add( newLease( uuid, duration ) );
+            }
+        }
+        catch( ArrayIndexOutOfBoundsException e )
+        {
+            throw new
+                AssertionError( "space.write<multiple> returned malformed data" );
+        }
+
+        return rslt;
+    }
+
+    public Collection take( Collection tmpls, Transaction txn,
+                            long timeout, long maxEntries )
+        throws UnusableEntriesException, TransactionException, RemoteException
+    {
+        // Figure out the max time this query should last
+        final long endTime = calcEndTime( timeout );
+
+        long remaining = timeout;
+        OutriggerServer.QueryCookie queryCookie = null;
+        final EntryRep[] treps = repFor( tmpls, "tmpls" );
+
+        final int limit;
+        if( maxEntries < 1 )
+        {
+            throw new IllegalArgumentException( "maxEntries must be positive" );
+        }
+        else if( maxEntries <= Integer.MAX_VALUE )
+        {
+            limit = (int) maxEntries;
+        }
+        else
+        {
+            limit = Integer.MAX_VALUE; // ok to return fewer than requested
+        }
+
+        // Loop util timeout or we get an answer (call at least once!)
+        do
+        {
+            final long serverTimeout =
+                Math.min( remaining, maxServerQueryTimeout );
+            logQuery( "take(multiple)", serverTimeout, queryCookie, remaining );
+
+
+            final Object rslt =
+                space.take( treps, txn, serverTimeout, limit, queryCookie );
+            if( rslt == null )
+            {
+                // should never get null from a non-ifExists query
+                throw new AssertionError( "space.take<multiple>() returned null" );
+            }
+            else if( rslt instanceof EntryRep[] )
+            {
+                EntryRep[] reps = (EntryRep[]) rslt;
+                // Got an answer, return it
+                final Collection entries = new LinkedList();
+                Collection exceptions = null;
+
+                for( int i = 0; i < reps.length; i++ )
+                {
+                    try
+                    {
+                        entries.add( entryFrom( reps[ i ] ) );
+                    }
+                    catch( UnusableEntryException e )
+                    {
+                        if( exceptions == null )
+                        {
+                            exceptions = new LinkedList();
+                        }
+
+                        exceptions.add( e );
+                    }
+                }
+
+                if( exceptions == null )
+                {
+                    return entries;
+                }
+                else
+                {
+                    throw new UnusableEntriesException(
+                        "some of the removed entries could not be unmarshalled",
+                        entries, exceptions );
+                }
+            }
+            else if( rslt instanceof OutriggerServer.QueryCookie )
+            {
+                /* Will still want to go on if there is time, but pass
+             * the new cookie
+             */
+                queryCookie = (OutriggerServer.QueryCookie) rslt;
+            }
+            else
+            {
+                throw new AssertionError(
+                    "Unexpected return type from space.take<multiple>()" );
+            }
+
+            /* Update remaining and loop, checking to see if the timeout has
+            * expired.
+            */
+            remaining = endTime - System.currentTimeMillis();
+        }
+        while( remaining > 0 );
+
+        /* If we get here then there must not have been any entries available
+       * to us before the endTime.
+       */
+        return Collections.EMPTY_LIST;
+    }
+
+    public EventRegistration
+    registerForAvailabilityEvent( Collection tmpls,
+                                  Transaction txn,
+                                  boolean visibilityOnly,
+                                  RemoteEventListener listener,
+                                  long leaseDuration,
+                                  MarshalledObject handback )
+        throws TransactionException, RemoteException
+    {
+        return space.registerForAvailabilityEvent(
+            repFor( tmpls, "tmpls" ), txn, visibilityOnly, listener,
+            leaseDuration, handback );
+    }
+
+
+    // inherit doc comment
+    public MatchSet contents( Collection tmpls,
+                              Transaction txn,
+                              long leaseDuration,
+                              long maxEntries )
+        throws RemoteException, TransactionException
+    {
+        final MatchSetData msd =
+            space.contents( repFor( tmpls, "tmpls" ), txn, leaseDuration, maxEntries );
+        return new MatchSetProxy( msd, this, space );
+    }
+
+    /* We break up lease creation into two methods. newLease takes
+     * care of converting from duration to expiration and we should
+     * never need to override (so we make it final), while
+     * constructLease takes care of invoking the right constructor for
+     * the given context (e.g. constrainable v. not) 
+     */
+
+    /**
+     * Create a new lease with the specified id and initial duration
+     */
+    final protected Lease newLease( Uuid uuid, long duration )
+    {
+        long expiration = duration + System.currentTimeMillis();
+
+        // We added two positive numbers, so if the result is negative
+        // we must have overflowed, so use Long.MAX_VALUE
+        if( expiration < 0 )
+        {
+            expiration = Long.MAX_VALUE;
+        }
+        return constructLease( uuid, expiration );
+    }
+
+    /**
+     * Create a new lease with the specified id and initial expiration
+     */
+    protected Lease constructLease( Uuid uuid, long expiration )
+    {
+        return new LandlordLease( uuid, space, spaceUuid, expiration );
+    }
+
+    // --------------------------------------------------
+    //          Administrable methods implementation
+    // --------------------------------------------------
+    // inherit doc comment
+    public Object getAdmin() throws RemoteException
+    {
+        return space.getAdmin();
+    }
+
+    // --------------------------------------------------
+    //		Private implementation
+    // --------------------------------------------------
+
+    /**
+     * Utility method to calculate the absolute end time of a query.
+     *
+     * @param timeout relative timeout of query.
+     * @return timeout plus the current time, or
+     *         <code>Long.MAX_VALUE</code> if timeout plus the current time
+     *         is larger than <code>Long.MAX_VALUE</code>.
+     */
+    private long calcEndTime( long timeout )
+    {
+        if( timeout < 0 )
+        {
+            throw new IllegalArgumentException( "timeout must be non-negative" );
+        }
+        final long now = System.currentTimeMillis();
+        if( Long.MAX_VALUE - timeout <= now )
+        {
+            return Long.MAX_VALUE;
+        }
+        else
+        {
+            return now + timeout;
+        }
+    }
+
+    static EntryRep[] repFor( Collection entries, String argName )
+        throws MarshalException
+    {
+        final EntryRep[] reps = new EntryRep[entries.size()];
+        int j = 0;
+        for( Iterator i = entries.iterator(); i.hasNext(); )
+        {
+            final Object e = i.next();
+            if( !( e == null || e instanceof Entry ) )
+            {
+                throw new IllegalArgumentException(
+                    argName + " contatins an element which is not an Entry" );
+            }
+
+            reps[ j++ ] = repFor( (Entry) e );
+        }
+
+        return reps;
+    }
+
+    /**
+     * Return an <code>EntryRep</code> object for the given
+     * <code>Entry</code>.
+     */
+    static EntryRep repFor( Entry entry ) throws MarshalException
+    {
+        if( entry == null )
+        {
+            return null;
+        }
+        if( entry instanceof SnapshotRep )    // snapshots are pre-calculated
+        {
+            return ( (SnapshotRep) entry ).rep();
+        }
+        return new EntryRep( entry );
+    }
+
+    /**
+     * Return an entry generated from the given rep.
+     */
+    static Entry entryFrom( EntryRep rep ) throws UnusableEntryException
+    {
+        if( rep == null )
+        {
+            return null;
+        }
+        return rep.entry();
+    }
+
+    /**
+     * Log query call to server
+     */
+    private void logQuery( String op, long serverTimeout,
+                           OutriggerServer.QueryCookie cookie, long remaining )
+    {
+        if( logger.isLoggable( Level.FINER ) )
+        {
+            logger.log( Level.FINER, "Outrigger calling {0} on server with " +
+                                     "timeout of {1} ms for serverTimeout, using QueryCookie " +
+                                     "{2}, {3} ms remaining on query",
+                        new Object[]{ op, new Long( serverTimeout ), cookie,
+                                      new Long( remaining ) } );
+        }
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableAvailabilityWatcher.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableAvailabilityWatcher.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableAvailabilityWatcher.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableAvailabilityWatcher.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.StreamCorruptedException;
+import java.rmi.MarshalledObject;
+import net.jini.core.event.RemoteEventListener;
+import net.jini.id.Uuid;
+import net.jini.id.UuidFactory;
+import net.jini.security.ProxyPreparer;
+
+/**
+ * Subclass of <code>AvailabilityRegistrationWatcher</code> for
+ * non-transactional persistent availability/visibility event
+ * registrations.
+ */
+class StorableAvailabilityWatcher extends AvailabilityRegistrationWatcher
+    implements StorableResource
+{
+    /**
+     * The listener that should be notified of matches
+     */
+    private StorableReference listener;
+
+    /**
+     * Used during log recovery to create a mostly empty
+     * <code>StorableAvailabilityWatcher</code>.
+     * <p>
+     * Note, we set the time stamp and tie-breaker here instead of
+     * getting them from the log. This means they will be inconstant
+     * with their value from the last VM we were in, but since they
+     * never leak out and events are read-only anyway this should not
+     * be a problem (this also allows us to keep the tie-breaker and
+     * time stamp in final fields).
+     *
+     * @param timestamp     the value that is used
+     *                      to sort <code>TransitionWatcher</code>s.
+     * @param startOrdinal  the highest ordinal associated
+     *                      with operations that are considered to have occurred
+     *                      before the operation associated with this watcher.
+     * @param currentSeqNum Sequence number to start with.
+     * @throws NullPointerException if the <code>notifier</code>
+     *                              argument is null.
+     */
+    StorableAvailabilityWatcher( long timestamp, long startOrdinal,
+                                 long currentSeqNum )
+    {
+        super( timestamp, startOrdinal, currentSeqNum );
+    }
+
+    /**
+     * Create a new <code>StorableAvailabilityWatcher</code>.
+     *
+     * @param timestamp      the value that is used
+     *                       to sort <code>TransitionWatcher</code>s.
+     * @param startOrdinal   the highest ordinal associated
+     *                       with operations that are considered to have occurred
+     *                       before the operation associated with this watcher.
+     * @param cookie         The unique identifier associated
+     *                       with this watcher. Must not be <code>null</code>.
+     * @param visibilityOnly pass <code>true</code> if client
+     *                       only wants visibility events
+     * @param handback       The handback object that
+     *                       should be sent along with event
+     *                       notifications to the the listener.
+     * @param eventID        The event ID for event type
+     *                       represented by this object.
+     * @param listener       The object to notify of
+     *                       matches.
+     * @throws NullPointerException if the <code>cookie</code>,
+     *                              or <code>listener</code> arguments are <code>null</code>.
+     */
+    StorableAvailabilityWatcher( long timestamp, long startOrdinal, Uuid cookie,
+                                 boolean visibilityOnly, MarshalledObject handback, long eventID,
+                                 RemoteEventListener listener )
+    {
+        super( timestamp, startOrdinal, cookie, visibilityOnly, handback,
+               eventID );
+
+        if( listener == null )
+        {
+            throw new NullPointerException( "listener must be non-null" );
+        }
+        this.listener = new StorableReference( listener );
+    }
+
+    boolean isInterested( EntryTransition transition, long ordinal )
+    {
+        if( ordinal <= startOrdinal )
+        {
+            return false;
+        }
+
+        if( transition.getTxn() != null )
+        {
+            return false;
+        }
+
+        if( !transition.isAvailable() )
+        {
+            return false;
+        }
+
+        if( visibilityOnly && !transition.isVisible() )
+        {
+            return false;
+        }
+
+        if( transition.hasProcessed( this ) )
+        {
+            return false;
+        }
+
+        transition.processedBy( this );
+        return true;
+    }
+
+    RemoteEventListener getListener( ProxyPreparer preparer )
+        throws ClassNotFoundException, IOException
+    {
+        return (RemoteEventListener) listener.get( preparer );
+    }
+
+    /**
+     * Overridden by subclasses if there is any cleanup work they need
+     * to do as part of <code>cancel</code> or
+     * <code>removeIfExpired</code>. Called after releasing the lock
+     * on <code>this</code>.  Will be called at most once.
+     *
+     * @param owner   A reference to the owner.
+     * @param expired <code>true</code> if being called from
+     *                <code>removeIfExpired</code> and false otherwise.
+     */
+    void cleanup( OutriggerServerImpl server, boolean expired )
+    {
+        if( expired )
+        {
+            server.scheduleCancelOp( cookie );
+        }
+        else
+        {
+            server.cancelOp( cookie, false );
+        }
+    }
+
+    /**
+     * Store the persistent fields
+     */
+    public void store( ObjectOutputStream out ) throws IOException
+    {
+        cookie.write( out );
+        out.writeLong( expiration );
+        out.writeLong( eventID );
+        out.writeBoolean( visibilityOnly );
+        out.writeObject( handback );
+        out.writeObject( listener );
+    }
+
+    /**
+     * Restore the persistent fields
+     */
+    public void restore( ObjectInputStream in )
+        throws IOException, ClassNotFoundException
+    {
+        cookie = UuidFactory.read( in );
+        expiration = in.readLong();
+        eventID = in.readLong();
+        visibilityOnly = in.readBoolean();
+        handback = (MarshalledObject) in.readObject();
+        listener = (StorableReference) in.readObject();
+        if( listener == null )
+        {
+            throw new StreamCorruptedException(
+                "Stream corrupted, should not be null" );
+        }
+    }
+}
+

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableEventWatcher.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableEventWatcher.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableEventWatcher.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableEventWatcher.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.StreamCorruptedException;
+import java.rmi.MarshalledObject;
+import net.jini.core.event.RemoteEventListener;
+import net.jini.id.Uuid;
+import net.jini.id.UuidFactory;
+import net.jini.security.ProxyPreparer;
+
+/**
+ * Subclass of <code>EventRegistrationWatcher</code> for non-transactional
+ * persistent event registrations.
+ */
+class StorableEventWatcher extends EventRegistrationWatcher
+    implements StorableResource
+{
+    /**
+     * The listener that should be notified of matches
+     */
+    private StorableReference listener;
+
+    /**
+     * Used during log recovery to create a mostly empty
+     * <code>StorableEventWatcher</code>.
+     * <p>
+     * Note, we set the time stamp and tie-breaker here instead of
+     * getting them from the log. This means they will be inconstant
+     * with their value from the last VM we were in, but since they
+     * never leak out and events are read-only anyway this should not
+     * be a problem (this also allows us to keep the tie-breaker and
+     * time stamp in final fields).
+     *
+     * @param timestamp     the value that is used
+     *                      to sort <code>TransitionWatcher</code>s.
+     * @param startOrdinal  the highest ordinal associated
+     *                      with operations that are considered to have occurred
+     *                      before the operation associated with this watcher.
+     * @param currentSeqNum Sequence number to start with.
+     * @throws NullPointerException if the <code>notifier</code>
+     *                              argument is null.
+     */
+    StorableEventWatcher( long timestamp, long startOrdinal,
+                          long currentSeqNum )
+    {
+        super( timestamp, startOrdinal, currentSeqNum );
+    }
+
+    /**
+     * Create a new <code>StorableEventWatcher</code>.
+     *
+     * @param timestamp    the value that is used
+     *                     to sort <code>TransitionWatcher</code>s.
+     * @param startOrdinal the highest ordinal associated
+     *                     with operations that are considered to have occurred
+     *                     before the operation associated with this watcher.
+     * @param cookie       The unique identifier associated
+     *                     with this watcher. Must not be <code>null</code>.
+     * @param handback     The handback object that
+     *                     should be sent along with event
+     *                     notifications to the the listener.
+     * @param eventID      The event ID for event type
+     *                     represented by this object.
+     * @param listener     The object to notify of
+     *                     matches.
+     * @throws NullPointerException if the <code>cookie</code>,
+     *                              or <code>listener</code> arguments are <code>null</code>.
+     */
+    StorableEventWatcher( long timestamp, long startOrdinal, Uuid cookie,
+                          MarshalledObject handback, long eventID,
+                          RemoteEventListener listener )
+    {
+        super( timestamp, startOrdinal, cookie, handback, eventID );
+
+        if( listener == null )
+        {
+            throw new NullPointerException( "listener must be non-null" );
+        }
+        this.listener = new StorableReference( listener );
+    }
+
+    boolean isInterested( EntryTransition transition, long ordinal )
+    {
+        return ( ( ordinal > startOrdinal ) &&
+                 ( transition.getTxn() == null ) &&
+                 ( transition.isNewEntry() ) );
+    }
+
+    RemoteEventListener getListener( ProxyPreparer preparer )
+        throws ClassNotFoundException, IOException
+    {
+        return (RemoteEventListener) listener.get( preparer );
+    }
+
+    /**
+     * Overridden by subclasses if there is any cleanup work they need
+     * to do as part of <code>cancel</code> or
+     * <code>removeIfExpired</code>. Called after releasing the lock
+     * on <code>this</code>.  Will be called at most once.
+     *
+     * @param owner   A reference to the owner.
+     * @param expired <code>true</code> if being called from
+     *                <code>removeIfExpired</code> and false otherwise.
+     */
+    void cleanup( TemplateHandle owner, boolean expired )
+    {
+        if( expired )
+        {
+            owner.getServer().scheduleCancelOp( cookie );
+        }
+        else
+        {
+            owner.getServer().cancelOp( cookie, false );
+        }
+    }
+
+
+    /**
+     * Store the persistent fields
+     */
+    public void store( ObjectOutputStream out ) throws IOException
+    {
+        cookie.write( out );
+        out.writeLong( expiration );
+        out.writeLong( eventID );
+        out.writeObject( handback );
+        out.writeObject( listener );
+    }
+
+    /**
+     * Restore the persistent fields
+     */
+    public void restore( ObjectInputStream in )
+        throws IOException, ClassNotFoundException
+    {
+        cookie = UuidFactory.read( in );
+        expiration = in.readLong();
+        eventID = in.readLong();
+        handback = (MarshalledObject) in.readObject();
+        listener = (StorableReference) in.readObject();
+        if( listener == null )
+        {
+            throw new StreamCorruptedException(
+                "Stream corrupted, should not be null" );
+        }
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableObject.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableObject.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableObject.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableObject.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+/**
+ * Interface that must be implemented by objects that must persist their
+ * state.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see LogOps
+ * @since 2.0
+ */
+public interface StorableObject
+{
+
+    /**
+     * Store the persistent fields
+     */
+    public void store( ObjectOutputStream out ) throws IOException;
+
+    /**
+     * Restore the persistent fields
+     */
+    public void restore( ObjectInputStream in )
+        throws IOException, ClassNotFoundException;
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableReference.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableReference.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableReference.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableReference.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.rmi.MarshalledObject;
+import java.rmi.RemoteException;
+import net.jini.security.ProxyPreparer;
+
+/**
+ * This class holds a proxy for some remote resource. When
+ * persisted the proxy is marshalled in its own
+ * {@link MarshalledObject} so this object can be unmarshalled
+ * even if the proxy can't be (say because it codebase is
+ * unavailable). The {@link #get} method can
+ * be used to retrieve the proxy on demand.
+ *
+ * @author Sun Microsystems, Inc.
+ */
+class StorableReference implements Externalizable
+{
+    /**
+     * The proxy in marshalled form
+     */
+    private MarshalledObject bytes;
+
+    /**
+     * A cached copy of the unmarshalled proxy
+     */
+    private transient Object obj;
+
+    /**
+     * True if the <code>obj</code> has been prepared
+     */
+    private transient boolean prepared;
+
+    private static final boolean DEBUG = false;
+    private static final long serialVersionUID = -3793675220968988873L;
+
+    /**
+     * Create a <code>StorableReference</code> that will hold
+     * <code>obj</code>.
+     */
+    public StorableReference( Object obj )
+    {
+        if( obj == null )
+        {
+            throw new NullPointerException( "obj cannot be null" );
+        }
+        this.obj = obj;
+        prepared = true;
+    }
+
+    /**
+     * Used by the object output stream.
+     */
+    public StorableReference()
+    {
+    }
+
+    /**
+     * Return the proxy.  If necessary deserialize the
+     * proxy and optionally prepare it. Will only deserialize the
+     * reference if it has not already been deserialized. Will
+     * only prepare the object if <code>preparer</code> is non-null
+     * and no previous call to get has succeeded. If this method
+     * throws an exception, preparation has not succeeded. If a
+     * previous call to this method has succeed, all future
+     * calls will succeed and return the same object as the
+     * first successful call.
+     *
+     * @param preparer the <code>ProxyPreparer</code> to
+     *                 be used to prepare the reference. May
+     *                 be <code>null</code>.
+     * @return the remote reference contained in this object
+     * @throws IOException            if the unmarshalling fails. Will
+     *                                also throw {@link RemoteException}
+     *                                if <code>preparer.prepareProxy</code>
+     *                                does.
+     * @throws ClassNotFoundException if unmarshalling fails
+     *                                with one.
+     * @throws SecurityException      if <code>preparer</code> does.
+     */
+    public synchronized Object get( ProxyPreparer preparer )
+        throws IOException, ClassNotFoundException
+    {
+        /* Even though we may be doing remote ops, it is
+       * ok that we are synchronized.  It does not
+       * matter if a competing thread waits on this
+       * lock, or waits doing the same remote operation
+       * the owner of the lock is doing (in fact it
+       * is better for the second thread to wait instead
+       * of duplicating the work of the first).
+       */
+
+        if( obj == null )
+        {
+            obj = bytes.get();
+        }
+
+        if( !prepared )
+        {
+            if( preparer != null )
+            {
+                obj = preparer.prepareProxy( obj );
+            }
+            prepared = true;
+        }
+
+        return obj;
+    }
+
+    /**
+     * @serialData
+     */
+    // inherit doc comment
+    public void writeExternal( ObjectOutput out ) throws IOException
+    {
+        synchronized( this )
+        {
+            if( bytes == null )
+            {
+                bytes = new MarshalledObject( obj );
+            }
+        }
+
+        out.writeObject( bytes );
+    }
+
+    // inherit doc comment
+    public void readExternal( ObjectInput in )
+        throws IOException, ClassNotFoundException
+    {
+        bytes = (MarshalledObject) in.readObject();
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableResource.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableResource.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableResource.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StorableResource.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import com.sun.jini.landlord.LeasedResource;
+
+/**
+ * Sub-interface of <code>StorableObject</code> that must be implemented by
+ * objects that represent leased resources and must persist their state.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see LogOps
+ * @since 2.0
+ */
+public interface StorableResource extends StorableObject, LeasedResource
+{
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/Store.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/Store.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/Store.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/Store.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+/**
+ * This interface defines the methods that any OutriggerServerImpl store must
+ * implement.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see OutriggerServerImpl
+ * @see LogOps
+ * @see Recover
+ */
+public interface Store
+{
+
+    /**
+     * Set up the store. Recovery (if any) will be completed
+     * before this method returns. That is, no calls will be made by
+     * <code>setupStore</code> on the <code>Recover</code> object
+     * after it returns.
+     *
+     * @param space object used for recovery of previous state (if any)
+     * @return object used to persist state
+     */
+    public LogOps setupStore( Recover space );
+
+    /**
+     * Destroy any persistent state and release
+     * any resources associated with this store.
+     */
+    public void destroy() throws java.io.IOException;
+
+    /**
+     * Close the store, release VM resources (stop independent
+     * threads, close files, etc.) but do not destroy any persistent
+     * state. This method is used when there is a failure
+     * in <code>OutriggerServerImpl</code> constructor.
+     */
+    public void close() throws java.io.IOException;
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredObject.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredObject.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredObject.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredObject.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.IOException;
+
+/**
+ * Interface for a stored resource. Objects implementing this interface
+ * are passed into calls to <code>Recover</code> objects.
+ *
+ * @see Recover
+ */
+public interface StoredObject
+{
+
+    /**
+     * Restore the state of a <code>StorableObject</code> object.
+     *
+     * @param object to restore
+     */
+    public void restore( StorableObject object )
+        throws IOException, ClassNotFoundException;
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredResource.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredResource.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredResource.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/StoredResource.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.io.IOException;
+
+/**
+ * Interface for a stored resource. Objects implementing this interface
+ * are passed into calls to <code>Recover</code> objects. This objects
+ * represented by this interface are resources that have expiration
+ * times (LeasedResource).
+ *
+ * @see Recover
+ */
+public interface StoredResource
+{
+
+    /**
+     * Restore the state of a <code>StorableResource</code>. The resource
+     * to be restored will have its expiration set before this method
+     * returns.
+     *
+     * @param obj resource to restore
+     * @see LogOps#renewOp
+     */
+    public void restore( StorableResource obj )
+        throws IOException, ClassNotFoundException;
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TakeIfExistsWatcher.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TakeIfExistsWatcher.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TakeIfExistsWatcher.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TakeIfExistsWatcher.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,339 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sun.jini.outrigger;
+
+import java.util.Set;
+import java.util.WeakHashMap;
+import net.jini.core.transaction.TransactionException;
+import net.jini.space.InternalSpaceException;
+
+/**
+ * Subclass of <code>QueryWatcher</code> for <code>takeIfExists</code>
+ * queries.  Resolves with the first matching transition where the
+ * entry is visible to the associated transaction and the entry is
+ * still available, or of the locked entry set goes empty.
+ */
+class TakeIfExistsWatcher extends SingletonQueryWatcher
+    implements IfExistsWatcher, Transactable
+{
+    /**
+     * The set of entries that would match but are currently
+     * unavailable (e.g. they are locked). We only keep
+     * the ids, not the entries themselves.
+     */
+    private final Set lockedEntries;
+
+    /**
+     * Set <code>true</code> once the query thread is
+     * done processing the backlog. Once this is
+     * <code>true</code> it is ok to resolve if
+     * <code>lockedEntries</code> is empty.
+     */
+    private boolean backlogFinished = false;
+
+    /**
+     * If non-null the transaction this query is
+     * being performed under. If <code>null</code>
+     * this query is not associated with a transaction.
+     */
+    private final Txn txn;
+
+    /**
+     * Set of entries (represented by <code>EntryHolder</code>s) that
+     * we would have liked to return, but have been provisionally
+     * removed.
+     */
+    private final WeakHashMap provisionallyRemovedEntrySet;
+
+    /**
+     * Create a new <code>TakeIfExistsWatcher</code>.
+     *
+     * @param expiration                   the initial expiration time
+     *                                     for this <code>TransitionWatcher</code> in
+     *                                     milliseconds since the beginning of the epoch.
+     * @param timestamp                    the value that is used
+     *                                     to sort <code>TransitionWatcher</code>s.
+     * @param startOrdinal                 the highest ordinal associated
+     *                                     with operations that are considered to have occurred
+     *                                     before the operation associated with this watcher.
+     * @param lockedEntries                Set of entries (by their IDs)
+     *                                     that match but are unavailable. Must be non-empty.
+     *                                     Keeps a reference to this object.
+     * @param provisionallyRemovedEntrySet If the watcher encounters
+     *                                     an entry that can not be read/taken because it has been
+     *                                     provisionally removed then its handle will be placed in
+     *                                     this <code>WeakHashMap</code> as a key (with null as the
+     *                                     value).  May be <code>null</code> in which case
+     *                                     provisionally removed entries will not be
+     *                                     recorded. Ensures that object is only accessed by one
+     *                                     thread at a time
+     * @param txn                          If the query is being performed under
+     *                                     a transaction the <code>Txn</code> object
+     *                                     associated with that transaction.
+     * @throws NullPointerException if <code>lockedEntries</code> is
+     *                              <code>null</code>.
+     */
+    TakeIfExistsWatcher( long expiration, long timestamp,
+                         long startOrdinal, Set lockedEntries,
+                         WeakHashMap provisionallyRemovedEntrySet, Txn txn )
+    {
+        super( expiration, timestamp, startOrdinal );
+
+        if( lockedEntries == null )
+        {
+            throw new NullPointerException( "lockedEntries must be non-null" );
+        }
+
+        this.lockedEntries = lockedEntries;
+        this.txn = txn;
+        this.provisionallyRemovedEntrySet = provisionallyRemovedEntrySet;
+    }
+
+    boolean isInterested( EntryTransition transition, long ordinal )
+    {
+        /* If we are unresolved pretty much all transitions are
+       * interesting because we may need to update
+       * lockedEntries.
+       *
+       * Note, !isResolved() without the lock will result only in
+       * false positives, not false negatives - it will only
+       * cause isInterested() to return false if we are resolved,
+       * we may still return true if we are resolved though.
+       */
+        return ( ordinal > startOrdinal ) && !isResolved();
+    }
+
+    synchronized void process( EntryTransition transition, long now )
+    {
+        if( isResolved() )
+        {
+            return; // Already done.
+        }
+
+        final EntryHandle handle = transition.getHandle();
+        final EntryRep rep = handle.rep();
+        final boolean isAvailable = transition.isAvailable();
+        final TransactableMgr transitionTxn = transition.getTxn();
+
+        /* If it at one time it was available to our transaction
+       * it may still be, try to get it.
+       */
+        if( isAvailable &&
+            ( ( null == transitionTxn ) || txn == transitionTxn ) )
+        {
+            /* Is it still available? */
+            if( getServer().attemptCapture( handle, txn, true, null,
+                                            provisionallyRemovedEntrySet, now, this ) )
+            {
+                // Got it
+                resolve( handle, null );
+            }
+            else
+            {
+                /* Must not have been able to get it. Either
+             * locked under a conflicting lock, in which
+             * case it should be in our lockedEntries set, or
+             * it has been removed, in which it still needs
+             * to be in our lockedEntries since it may have
+             * been replaced before being removed.
+             */
+                lockedEntries.add( rep.id() );
+            }
+        }
+        else if( isAvailable )
+        { // but it is not visible to txn
+            /* If we are here then at one time it must have been was
+            * available but not visible to us, implying that it was an
+            * entry written under a transaction and is interesting to
+            * us, but not yet visible. We need to add it lockedEntries
+            * even if has been removed since it could have gotten
+            * replaced before it was removed. If we did not
+            * add it we would be acting on the future.
+            */
+            lockedEntries.add( rep.id() );
+        }
+        else
+        {
+            /* Must not be available, transition must mark
+            * the resolution of the transaction in such away
+            * that the entry has been removed, remove it
+            * from the set and see if that makes the set empty.
+            */
+            lockedEntries.remove( rep.id() );
+            if( backlogFinished && lockedEntries.isEmpty() )
+            {
+                resolve( null, null );
+            }
+        }
+    }
+
+    synchronized boolean catchUp( EntryTransition transition, long now )
+    {
+        if( isResolved() )
+        {
+            return true; // Already done.
+        }
+
+        final EntryHandle handle = transition.getHandle();
+        final EntryRep rep = handle.rep();
+        final boolean isAvailable = transition.isAvailable();
+        final TransactableMgr transitionTxn = transition.getTxn();
+
+        /* If it at one time it was available to our transaction
+       * it may still be, try to get it.
+       */
+        if( isAvailable &&
+            ( ( null == transitionTxn ) || txn == transitionTxn ) )
+        {
+            /* Is it still available? Try to get it. attemptCapture will
+            * add the entry to lockedEntries for us if we could not
+            * get it and it is still in the space (but locked).
+            * Nothing will be added if it has been removed outright.
+            * This is ok even though we are peaking into the future -
+            * we won't act on that information until the future
+            * comes to pass.
+            */
+            if( getServer().attemptCapture( handle, txn, true,
+                                            lockedEntries, provisionallyRemovedEntrySet, now, this ) )
+            {
+                // Got it
+                resolve( handle, null );
+                return true;
+            }
+
+            // did not resolve
+            return false;
+        }
+
+        if( isAvailable )
+        { // but it is not visible to txn
+            /* If we are here then at one time it must have been was
+            * available but not visible to us, implying that it was
+            * an entry written under a transaction and is interesting
+            * to us, but not yet visible. We only add if it has not
+            * already been removed.  It might have gotten replaced
+            * before removal, but since we won't let this query get
+            * resolved with a definitive null before we get past the
+            * point in the journal where it was removed it is ok to
+            * never put it in (and if we did put it in it might never
+            * get removed since process() may have already processed
+            * the removal). We don't need to check to see it the
+            * entry has been provisionally removed since if has been
+            * provisional removal does not put in entries in the
+            * journal and if it is provisionally removed it has not
+            * yet been removed so the remove recored has not yet been
+            * created (must less processed).
+            */
+            synchronized( handle )
+            {
+                if( !handle.removed() )
+                {
+                    lockedEntries.add( rep.id() );
+                }
+
+                /* If it has been removed, there is no way it
+             * will be interesting to us again, ever.
+             */
+            }
+            // Either way, still not resolved.
+            return false;
+        }
+
+        /* Must not be available, transition must mark
+       * the resolution of the transaction in such away
+       * that the entry has been removed, remove it
+       * from the set (don't need to check for empty
+       * because we haven't gotten to the point
+       * where we can resolve with a definitive null.)
+       */
+        lockedEntries.remove( rep.id() );
+        return false;
+    }
+
+    /**
+     * Once the backlog is complete we can resolve if
+     * lockedEntries is/becomes empty.
+     */
+    public synchronized void caughtUp()
+    {
+        backlogFinished = true;
+
+        if( isResolved() )
+        {
+            return; // Don't much mater.
+        }
+
+        if( lockedEntries.isEmpty() )
+        {
+            resolve( null, null );
+        }
+    }
+
+    public synchronized boolean isLockedEntrySetEmpty()
+    {
+        if( !isResolved() )
+        {
+            throw new IllegalStateException( "Query not yet resolved" );
+        }
+        return lockedEntries.isEmpty();
+    }
+
+    /**
+     * If a transaction ends in the middle of a query we want
+     * to throw an exception to the client making the query
+     * not the <code>Txn</code> calling us here.)
+     */
+    public synchronized int prepare( TransactableMgr mgr,
+                                     OutriggerServerImpl space )
+    {
+        assert txn != null : "Transactable method called on a " +
+                             "non-transactional TakeIfExistsWatcher";
+
+        // only throw an exception if we are not resolved.
+        if( !isResolved() )
+        {
+            // Query still in progress, kill it
+            resolve( null, new TransactionException( "completed while " +
+                                                     "operation in progress" ) );
+        }
+
+        // If this object has made changes they have been recorded elsewhere
+        return NOTCHANGED;
+    }
+
+    /**
+     * This should never happen since we always return
+     * <code>NOTCHANGED</code> from <code>prepare</code>.
+     */
+    public void commit( TransactableMgr mgr, OutriggerServerImpl space )
+    {
+        throw new InternalSpaceException( "committing a blocking query" );
+
+    }
+
+    /**
+     * If a transaction ends in the middle of a query we want
+     * to throw an exception to the client making the query
+     * (not the <code>Txn</code> calling us here.)
+     */
+    public void abort( TransactableMgr mgr, OutriggerServerImpl space )
+    {
+        // prepare does the right thing, and should forever
+        prepare( mgr, space );
+    }
+}