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 [11/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/...

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TxnTable.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TxnTable.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TxnTable.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TxnTable.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,525 @@
+/*
+ * 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.logging.Levels;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+import net.jini.core.transaction.server.ServerTransaction;
+import net.jini.core.transaction.server.TransactionManager;
+import net.jini.security.ProxyPreparer;
+
+/**
+ * Keeps a mapping from {@link TransactionManager}/id pairs, to
+ * {@link Txn} objects. Some <code>Txn</code>s may be
+ * <i>broken</i>, that is the <code>TransactionManager</code> they are
+ * associated with can not be unmarshalled and prepared, and thus
+ * can't currently be used (but may be usable in the future).
+ *
+ * @author Sun Microsystems, Inc.
+ * @since 2.0
+ */
+class TxnTable
+{
+    /**
+     * Key class for the primary map (from manager/id pairs to
+     * <code>Txn</code>s.  We use a new class instead of
+     * <code>ServerTransaction</code> objects so we can make
+     * sure we don't call <code>equals</code> on unprepared
+     * managers.
+     */
+    private class Key
+    {
+        /**
+         * The manager for the transaction
+         */
+        private final TransactionManager manager;
+
+        /**
+         * The id for the transaction
+         */
+        private final long id;
+
+        /**
+         * True if it has been asserted that <code>manager</code> has been
+         * prepared. Note, we only put Keys in the table that have
+         * this flag set.
+         */
+        private final boolean prepared;
+
+        /**
+         * Create a new key from the specified manager and id.
+         *
+         * @param manager  the manager for the transaction
+         * @param id       the id for the transaction
+         * @param prepared should be <code>true</code> if the manager has
+         *                 been prepared and false otherwise
+         * @throws NullPointerException if manager is <code>null</code>.
+         */
+        private Key( TransactionManager manager, long id, boolean prepared )
+        {
+            if( manager == null )
+            {
+                throw new NullPointerException( "manager must be non-null" );
+            }
+            this.manager = manager;
+            this.id = id;
+            this.prepared = prepared;
+        }
+
+        // Inherit doc from super
+        public int hashCode()
+        {
+            return (int) id ^ manager.hashCode();
+        }
+
+        // Inherit doc from super
+        public boolean equals( Object other )
+        {
+            if( !( other instanceof Key ) )
+            {
+                return false;
+            }
+
+            final Key o = (Key) other;
+            if( id != o.id )
+            {
+                return false;
+            }
+
+            /* Either this or o should have prepared == true, call
+            * manager.equals on the one who has been prepared.
+            */
+            if( o.prepared )
+            // Common case, usually the passed in object is in the map
+            {
+                return o.manager.equals( manager );
+            }
+            else if( prepared )
+            {
+                return manager.equals( o );
+            }
+            else
+            {
+                throw new
+                    AssertionError( "TxnTable.Key equals call with two " +
+                                    "unprepared managers" );
+            }
+        }
+    }
+
+    /**
+     * Map of manager,id pairs (represented as <code>Keys</code>s)
+     * to non-broken <code>Txn</code>s. Only <code>Key</code>s that
+     * have their prepared flag set should go in this Map.
+     */
+    final private Map txns = new java.util.HashMap();
+
+    /**
+     * Map of transaction ids to the <code>List</code> of broken
+     * <code>Txn</code> objects that have the id. <code>null</code>
+     * if there are no broken <code>Txn</code>s.
+     */
+    private Map brokenTxns = null;
+
+    /**
+     * <code>ProxyPreparer</code> to use when unpacking
+     * transactions, may be <code>null</code>.
+     */
+    private final ProxyPreparer proxyPreparer;
+
+    /**
+     * An array of type <code>Txn</code> to pass to <code>toArray</code>
+     */
+    private static final Txn[] txnArray = new Txn[0];
+
+    /**
+     * The logger to use
+     */
+    static private final Logger logger =
+        Logger.getLogger( OutriggerServerImpl.txnLoggerName );
+
+    /**
+     * Create a new <code>TxnTable</code>.
+     *
+     * @param proxyPreparer the proxy preparer to use
+     *                      on recovered <code>TransactionManager</code>s.
+     */
+    TxnTable( ProxyPreparer proxyPreparer )
+    {
+        this.proxyPreparer = proxyPreparer;
+    }
+
+    /**
+     * Given a <code>TransactionManager</code>, <code>manager</code>,
+     * and a transaction id, return the associated <code>Txn</code>,
+     * or <code>null</code> if there is no <code>Txn</code> for
+     * this manager/id pair. The only method this method will
+     * call on <code>manager</code> is <code>hashCode</code>.
+     * The returned <code>Txn</code> object will not be broken.
+     *
+     * @param manager a <code>TransactionManager</code>.
+     * @param id      a transaction id.
+     * @return the <code>Txn</code> for the specified pair
+     *         or null if none can be found.
+     * @throws IOException            if there was one or more
+     *                                possible matches, but they are broken
+     *                                and the attempt to unpack them yielded
+     *                                an <code>IOException</code>.
+     * @throws ClassNotFoundException if there was one or more
+     *                                possible matches, but they are broken
+     *                                and the attempt to unpack them yielded
+     *                                a <code>ClassNotFoundException</code>.
+     * @throws SecurityException      if there was one or more
+     *                                possible matches, but they are broken
+     *                                and the attempt to unpack them yielded
+     *                                a <code>SecurityException</code>.
+     */
+    Txn get( TransactionManager manager, long id )
+        throws IOException, ClassNotFoundException
+    {
+        final Long idAsLong;
+        final Txn brokenTxnsForId[];
+        // Try the table of non-broken txns first
+        synchronized( this )
+        {
+            final Txn r = (Txn) txns.get( new Key( manager, id, false ) );
+            if( r != null )
+            {
+                return r;
+            }
+
+            // Check broken txns
+            if( brokenTxns == null )
+            // No broken Txns so txns is definitive
+            {
+                return null;
+            }
+
+            idAsLong = new Long( id );
+            final List txnsForId = (List) brokenTxns.get( idAsLong );
+            if( txnsForId == null )
+                /* Broken Txns, but none with the right ID
+             * so txns is definitive for this manager/id pair.
+             */
+            {
+                return null;
+            }
+
+            /* If we are here there are broken Txns with the
+            * specified id, we need to try and fix each one
+            * and check to see if there is a match. Make
+            * a copy of the list so we don't need to
+            * hold a lock while making fix attempts (which
+            * in general involve remote communications).
+            */
+            brokenTxnsForId = (Txn[]) txnsForId.toArray( txnArray );
+        }
+
+        /* try and fix each element of brokenTxnsForId until
+       * we find the right Txn, or until we run out of elements
+       */
+        Txn match = null;
+        Throwable t = null; // The first throwable we get, if any
+        final List fixed = new java.util.LinkedList(); // fixed Txns
+        for( int i = 0; i < brokenTxnsForId.length; i++ )
+        {
+            try
+            {
+                final ServerTransaction st =
+                    brokenTxnsForId[ i ].getTransaction( proxyPreparer );
+
+                /* We fixed a Txn, remember so we can move it
+             * to txns.
+             */
+                fixed.add( brokenTxnsForId[ i ] );
+
+                /* Did this match? Pass unprepared manager to
+             * prepared one!
+             */
+                if( st.mgr.equals( manager ) )
+                {
+                    // bingo!
+                    match = brokenTxnsForId[ i ];
+                    break;
+                }
+            }
+            catch( Throwable tt )
+            {
+                try
+                {
+                    if( logger.isLoggable( Levels.FAILED ) )
+                    {
+                        logger.log( Levels.FAILED, "Encountered " + tt +
+                                                   "while recovering/re-preparing " +
+                                                   "transaction, will retry latter",
+                                    tt );
+                    }
+                }
+                catch( Throwable ttt )
+                {
+                    // don't let a problem in logging kill the thread
+                }
+
+                if( t == null )
+                {
+                    t = tt;
+                }
+            }
+        }
+
+        /* Now that all the remote operations are done, re-acquire lock
+       * so we can move anything that was fixed.
+       */
+        if( !fixed.isEmpty() )
+        {
+            synchronized( this )
+            {
+                if( brokenTxns != null )
+                {
+                    final List txnsForId = (List) brokenTxns.get( idAsLong );
+                    if( txnsForId != null )
+                    {
+
+                        // Remove from brokenTxns
+                        txnsForId.removeAll( fixed );
+
+                        // can we get rid of txnsForId and brokenTxns?
+                        if( txnsForId.isEmpty() )
+                        {
+                            brokenTxns.remove( idAsLong );
+                            if( brokenTxns.isEmpty() )
+                            {
+                                brokenTxns = null;
+                            }
+                        }
+
+                        // Put in txns
+                        for( Iterator i = fixed.iterator(); i.hasNext(); )
+                        {
+                            put( (Txn) i.next() );
+                        }
+                    }
+                    else
+                    {
+                        /* if the list for this id is gone the fixed Txns
+                   * must have already been moved by someone else
+                   */
+                    }
+                }
+                else
+                {
+                    /* if brokenTxns is gone the fixed Txns must have already
+                  * been moved by someone else
+                  */
+                }
+            }
+        }
+
+        // Did we run out of candidates, or did we find a match?
+        if( match != null )
+        {
+            return match;
+        }
+
+        /* Was there some Txn that may have been a match
+       * but is still broken so we don't know?
+       * [this could happen if :
+       *    o the managers codebase changed so
+       *      old proxies can't be unmarshalled (but new ones can),
+       *    o the log is corrupted,
+       *    o a bad preparer has been supplied,
+       *    o etc., etc.
+       * ]
+       */
+        if( t != null )
+        {
+            /* We may have some recored of this manager/id pair,
+            * but we can't tell since one or more of the broken
+            * Txns that could be a match could not be fixed.
+            * Throw an exception to indicate an ambiguous result.
+            */
+            if( t instanceof IOException )
+            {
+                throw (IOException) t;
+            }
+            else if( t instanceof ClassNotFoundException )
+            {
+                throw (ClassNotFoundException) t;
+            }
+            else if( t instanceof Error )
+            {
+                throw (Error) t;
+            }
+            else if( t instanceof RuntimeException )
+            {
+                throw (RuntimeException) t;
+            }
+            else
+            {
+                throw new AssertionError( t );
+            }
+        }
+
+        /* If we are here there were one or more
+       * broken Txns with the same ID, but all them
+       * could be fixed and none of them had a manager that
+       * matched. Definitively return null, we have no
+       * record of this manager/id pair.
+       */
+        return null;
+    }
+
+    /**
+     * Atomically test if there is a <code>Txn</code> for the
+     * specified <code>ServerTransaction</code> in the table, creating
+     * a new <code>Txn</code>, and place in table if there is not. If
+     * there is already a <code>Txn</code> for the specified
+     * <code>ServerTransaction</code> return the existing one,
+     * otherwise return the new one. Does not check for matches
+     * against broken txns.
+     *
+     * @param tr <code>ServerTransaction</code> to add to the table.
+     *           The contained manager proxy should already been prepared
+     * @return the <code>Txn</code> for <code>tr</code>.
+     */
+    Txn put( ServerTransaction tr )
+    {
+        final Key k = new Key( tr.mgr, tr.id, true );
+        final long internalID = OutriggerServerImpl.nextID();
+
+        // Atomic test and set
+        synchronized( this )
+        {
+            Txn r = (Txn) txns.get( k );
+            if( r == null )
+            {
+                // not in table, put a new one in and return it.
+                r = new Txn( tr, internalID );
+                txns.put( k, r );
+            }
+
+            return r;
+        }
+    }
+
+    /**
+     * Used to put a formally broken <code>Txn</code> in the main table.
+     * Only puts it in the table if it is not already their.
+     *
+     * @param txn the <code>Txn</code> being moved, should have
+     *            been prepared
+     */
+    private void put( Txn txn )
+    {
+        final Key k = new Key( txn.getManager(), txn.getTransactionId(), true );
+        synchronized( this )
+        {
+            final Txn r = (Txn) txns.get( k );
+            if( r == null )
+            {
+                txns.put( k, txn );
+            }
+        }
+    }
+
+    /**
+     * Restore a <code>Txn</code> in the table as
+     * part of log recovery. An attempt will be made
+     * unpack and prepare the transaction manager.
+     * The <code>Txn</code> may be broken.
+     * This method is not synchronized.
+     *
+     * @param txn the <code>Txn</code> being recovered.
+     */
+    void recover( Txn txn )
+    {
+        // Try to get the transaction
+        ServerTransaction st = null;
+        try
+        {
+            st = txn.getTransaction( proxyPreparer );
+        }
+        catch( Throwable t )
+        {
+            // log, but otherwise ignore
+            try
+            {
+                if( logger.isLoggable( Levels.FAILED ) )
+                {
+                    logger.log( Levels.FAILED, "Encountered " + t + " while " +
+                                               "recovering/re-preparing transaction, " +
+                                               "will retry latter",
+                                t );
+                }
+            }
+            catch( Throwable tt )
+            {
+                // don't let a problem in logging kill the thread
+            }
+        }
+
+        if( st == null )
+        {
+            // txn is broken, put in brokenTxns
+            if( brokenTxns == null )
+            {
+                brokenTxns = new java.util.HashMap();
+            }
+
+            final Long id = new Long( txn.getTransactionId() );
+            List txnsForId = (List) brokenTxns.get( id );
+            if( txnsForId == null )
+            {
+                txnsForId = new java.util.LinkedList();
+                brokenTxns.put( id, txnsForId );
+            }
+
+            txnsForId.add( txn );
+        }
+        else
+        {
+            // Txn is ok, put it in txns
+            final Key k = new Key( st.mgr, st.id, true );
+            txns.put( k, txn );
+        }
+    }
+
+
+    /**
+     * Remove the mapping for the given
+     * <code>TransactionManager</code>, id pair. Will
+     * not remove broken <code>Txn</code>s.
+     *
+     * @param manager the <code>TransactionManager</code> for
+     *                transaction being removed.
+     * @parma id the manager assigned to the transaction being
+     * removed.
+     */
+    void remove( TransactionManager manager, long id )
+    {
+        final Key k = new Key( manager, id, false );
+        synchronized( this )
+        {
+            txns.remove( k );
+        }
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TypeTree.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TypeTree.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TypeTree.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/TypeTree.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,284 @@
+/*
+ * 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.ArrayList;
+import java.util.Collection;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.Vector;
+
+/**
+ * A type tree for entries.  It maintains, for each class, a list of
+ * known subclasses so that we can walk down the relevant subpart of
+ * the subtype tree for a template, looking for matching entries.  This
+ * list of subtypes is not current garbage collected -- if a subtype
+ * was once written, it's subtype entry will never be removed from this
+ * tree.  All operations are done via class name.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see OutriggerServerImpl
+ */
+class TypeTree
+{
+    /**
+     * For each type, a vector of known subtypes
+     */
+    private Hashtable subclasses = new Hashtable();
+
+    /**
+     * A generator used to randomize the order of iterator returns
+     *
+     * @see #RandomizedIterator
+     */
+    static final private Random numgen = new Random();
+
+    /**
+     * Name of the root bucket of the type tree
+     */
+    static final private String ROOT =
+        net.jini.core.entry.Entry.class.getName();
+
+    /**
+     * Return the vector of subclasses for the given class.
+     */
+    private Vector classVector( String whichClass )
+    {
+        return (Vector) subclasses.get( whichClass );
+    }
+
+    /**
+     * An iterator that will walk through a list of known types.
+     *
+     * @see #RandomizedIterator
+     */
+    private abstract class TypeTreeIterator implements Iterator
+    {
+        protected int cursor;        // the current position in the list
+        protected Object[] typearray;    // the list of types as an array
+
+        // inherit doc comment
+        public boolean hasNext()
+        {
+            if( cursor < typearray.length )
+            {
+                return true;
+            }
+
+            return false;
+        }
+
+        // inherit doc comment
+        public Object next() throws NoSuchElementException
+        {
+            Object val = null;
+
+            if( cursor >= typearray.length )
+            {
+                throw new NoSuchElementException( "TypeTreeIterator: next" );
+            }
+
+            try
+            {
+                val = typearray[ cursor ];
+                cursor++;
+            }
+            catch( ArrayIndexOutOfBoundsException e )
+            {
+                throw new NoSuchElementException( "TypeTreeIterator: next" +
+                                                  e.getMessage() );
+            }
+
+            return val;
+        }
+
+        /**
+         * Unimplemented operations
+         *
+         * @throws UnsupportedOperationException Always
+         */
+        public void remove() throws UnsupportedOperationException
+        {
+            throw new UnsupportedOperationException(
+                "TypeTreeIterator: remove not supported" );
+        }
+    }
+
+    /**
+     * This class implements a randomized iterator over the
+     * <code>TypeTree</code>.  Given a <code>className</code>, it
+     * maintains a randomized list of subtypes for the given
+     * <code>className</code>, including the class itself.
+     */
+    class RandomizedIterator extends TypeTreeIterator
+    {
+        /**
+         * Create a new <code>RandomizedIterator</code> for the given
+         * class.
+         */
+        RandomizedIterator( String className )
+        {
+            super();
+            init( className );
+        }
+
+
+        /*
+       * Traverse the given type tree and add to the list all the
+       * subtypes encountered within.
+       */
+        private void walkTree( Collection children, Collection list )
+        {
+            if( children != null )
+            {
+                list.addAll( children );
+                Object[] kids = children.toArray();
+                for( int i = 0; i < kids.length; i++ )
+                {
+                    walkTree( classVector( (String) kids[ i ] ), list );
+                }
+            }
+        }
+
+        /**
+         * Set up this iterator to walk over the subtypes of this class,
+         * including the class itself.  It then randomizes the list.
+         */
+        private void init( String className )
+        {
+            Collection types = new ArrayList();
+
+            if( className.equals( EntryRep.matchAnyClassName() ) )
+            {
+                // handle "match any" specially" -- search from ROOT
+                // Simplification suggested by
+                // Lutz Birkhahn <lu...@GMX.DE>
+                className = ROOT;
+            }
+            else
+            {
+                // add this class
+                types.add( className );
+            }
+
+            // add all subclasses
+            walkTree( classVector( className ), types );
+
+            // Convert it to an array and then randomize
+            typearray = types.toArray();
+            int randnum = 0;
+            Object tmpobj = null;
+
+            for( int i = 0; i < typearray.length; i++ )
+            {
+                randnum = numgen.nextInt( typearray.length - i );
+                tmpobj = typearray[ i ];
+                typearray[ i ] = typearray[ randnum ];
+                typearray[ randnum ] = tmpobj;
+            }
+        }
+    }
+
+    /**
+     * Return an iterator over the subtypes of the given class
+     * (including the type itself).  This implementation always returns
+     * an iterator that randomizes the order of the classes returned.
+     * In other words, it returns the names of all classes that are
+     * instances of the class that named, in a random ordering.
+     */
+    Iterator subTypes( String className )
+    {
+        return new RandomizedIterator( className );
+    }
+
+    /**
+     * Update the type tree with the given bits.  This will traverse the
+     * given EntryRep's list of superclasses, retrieve the subclass list
+     * at each list item and update it with the given EntryRep's type.
+     *
+     * SupClass List
+     * |
+     * V
+     * SupC1-->Sub1OfSupC1--Sub2OfSupC1...SubNOfSupC1--EntryRep
+     * |
+     * |
+     * SupC2-->Sub1OfSupC2--Sub2OfSupC2...SubNOfSupC2--EntryRep
+     * .
+     * .
+     * .
+     * SupCN-->Sub1OfSupCN--Sub2OfSupCN...SubNOfSupCN--EntryRep
+     */
+    void addTypes( EntryRep bits )
+    {
+        String classFor = bits.classFor();
+        String[] superclasses = bits.superclasses();
+
+        //The given EntryRep will add its className to the
+        //subtype list of all its supertypes.
+
+        String prevClass = classFor;
+        for( int i = 0; i < superclasses.length; i++ )
+        {
+            if( !addKnown( superclasses[ i ], prevClass ) )
+            {
+                return;
+            }
+            prevClass = superclasses[ i ];
+        }
+
+        // If we are here prevClass must have java.Object as its
+        // direct superclass (we don't store "java.Object" in
+        // EntryRep.superclasses since that would be redundant) and
+        // prevClass is not already in the the tree.  Place it in the
+        // "net.jini.core.entry.Entry" bucket so it does not get lost
+        // if it does not have any sub-classes.
+        //
+        // Fix suggested by Lutz Birkhahn <lu...@GMX.DE>
+        addKnown( ROOT, prevClass );
+    }
+
+    /**
+     * Add the subclass to the list of known subclasses of this superclass.
+     */
+    private boolean addKnown( String superclass, String subclass )
+    {
+        Vector v;
+
+        synchronized( subclasses )
+        {
+            v = classVector( superclass );
+            if( v == null )
+            {
+                v = new Vector();
+                subclasses.put( superclass, v );
+            }
+        }
+
+        synchronized( v )
+        {
+            if( v.contains( subclass ) )
+            {
+                return false;
+            }
+            v.addElement( subclass );
+        }
+        return true;
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WatchersForTemplateClass.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WatchersForTemplateClass.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WatchersForTemplateClass.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WatchersForTemplateClass.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,229 @@
+/*
+ * 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;
+
+/**
+ * Holds a collection of <code>TemplateHandle</code>s who's templates
+ * are all of exactly the same class. Unless otherwise noted all
+ * methods are thread safe. This method provides the linkage between
+ * <code>TemplateHandle</code>s and <code>TransitionWatchers</code>
+ * and for the most part is not visible to the clients of either.
+ */
+class WatchersForTemplateClass
+{
+    /**
+     * All the templates we know about
+     */
+    private final FastList contents = new FastList();
+
+    /**
+     * The object we are inside of
+     */
+    private final TransitionWatchers owner;
+
+    /**
+     * Create a new <code>WatchersForTemplateClass</code> object
+     * associated with the specified <code>TransitionWatchers</code> object.
+     *
+     * @param owner The <code>TransitionWatchers</code> that
+     *              this object will be a part of.
+     * @throws NullPointerException if <code>owner</code> is
+     *                              <code>null</code>.
+     */
+    WatchersForTemplateClass( TransitionWatchers owner )
+    {
+        if( owner == null )
+        {
+            throw new NullPointerException( "owner must be non-null" );
+        }
+        this.owner = owner;
+    }
+
+    /**
+     * Add a <code>TransitionWatcher</code> to the list
+     * of watchers looking for visibility transitions in
+     * entries that match the specified template. Associates
+     * a <code>TemplateHandle</code> using
+     * <code>TransitionWatcher.setTemplateHandle</code> method.
+     *
+     * @param watcher  The <code>TransitionWatcher</code> being added.
+     * @param template The <code>EntryRep</code> that represents
+     *                 the template of interest.
+     * @throws NullPointerException if either argument is
+     *                              <code>null</code>.
+     */
+    void add( TransitionWatcher watcher, EntryRep template )
+    {
+        /* We try to find an existing handle, but it is ok
+       * if we have more than one with the same template. It
+       * is bad if we add the watcher to a removed handle.
+       */
+        TemplateHandle handle = (TemplateHandle) contents.head();
+        for( ; handle != null; handle = (TemplateHandle) handle.next() )
+        {
+            if( template.equals( handle.rep() ) )
+            {
+                synchronized( handle )
+                {
+                    if( !handle.removed() )
+                    {
+                        /* Found one, add and break. Call
+                   * addTemplateHandle() before adding to handle
+                   * so if the handle calls the watcher it will
+                   * be in a complete state. Add inside the
+                   * lock so handle can't be removed.
+                   */
+                        if( watcher.addTemplateHandle( handle ) )
+                        {
+                            handle.addTransitionWatcher( watcher );
+                        } // else the watcher was removed, don't add to handle
+
+                        return; // found a handle and added the watcher
+                    }
+                }
+            }
+        }
+
+        /* If we are here we could not find a handle with the right
+       * template, create one, add the watcher to it, and it
+       * to contents.
+       */
+        handle = new TemplateHandle( template, this );
+
+        /* We need the sync both to prevent concurrent modification
+       * of handle (since we add it to contents first), and to
+       * make sure other threads see the changes we are about to make.
+       */
+        synchronized( handle )
+        {
+            /* First add handle to contents so handle is fully initialized
+            * before we start to pass it around use
+            */
+            contents.add( handle );
+            if( watcher.addTemplateHandle( handle ) )
+            {
+                handle.addTransitionWatcher( watcher );
+            }
+            else
+            {
+                // watcher is already dead, undo adding handle
+                contents.remove( handle );
+            }
+        }
+    }
+
+    /**
+     * Iterate over the watchers associated with
+     * this object calling <code>isInterested</code> on each
+     * and if it returns <code>true</code> adding the watcher to the
+     * passed set.
+     *
+     * @param set        The set to accumulate interested watchers
+     *                   into.
+     * @param transition The transition being processed.
+     * @param ordinal    The ordinal associated with <code>transition</code>.
+     * @throws NullPointerException if either argument is <code>null</code>.
+     */
+    void collectInterested( Set set, EntryTransition transition,
+                            long ordinal )
+    {
+        final EntryHandle entryHandle = transition.getHandle();
+        final EntryRep rep = entryHandle.rep();
+        final long entryHash = entryHandle.hash();
+        final int repNumFields = rep.numFields();
+
+        /* Look at each of handles, check to see if they match
+       * the changed entry and if they do ask them to
+       * put the appropriate watchers in the set.
+       */
+        for( TemplateHandle handle = (TemplateHandle) contents.head();
+             handle != null;
+             handle = (TemplateHandle) handle.next() )
+        {
+            // See the if handle mask is incompatible
+            EntryHandleTmplDesc desc = handle.descFor( repNumFields );
+
+            if( ( entryHash & desc.mask ) != desc.hash )
+            {
+                continue;
+            }
+
+            if( handle.matches( rep ) )
+            {
+                if( handle.removed() ) //no sync, ok if we check a removed one
+                {
+                    continue;
+                }
+                handle.collectInterested( set, transition, ordinal );
+            }
+        }
+    }
+
+    /**
+     * Return the <code>OutriggerServerImpl</code> this
+     * handle is part of.
+     *
+     * @return The <code>OutriggerServerImpl</code> this
+     *         handle is part of.
+     */
+    OutriggerServerImpl getServer()
+    {
+        return owner.getServer();
+    }
+
+    /**
+     * Visit each <code>TransitionWatcher</code> and check to see if
+     * it has expired, removing it if it has. Also reaps the
+     * <code>FastList</code> associated with this object.
+     *
+     * @param now an estimate of the current time expressed as
+     *            milliseconds since the beginning of the epoch.
+     */
+    void reap( long now )
+    {
+        // First remove empty handles
+        for( TemplateHandle handle = (TemplateHandle) contents.head();
+             handle != null;
+             handle = (TemplateHandle) handle.next() )
+        {
+            // Dump any expired watchers.
+            handle.reap( now );
+
+            /* Need to lock on the handle so no one will
+            * add a watcher between the check for empty and
+            * when it gets marked removed.
+            */
+            synchronized( handle )
+            {
+                if( handle.isEmpty() )
+                {
+                    contents.remove( handle );
+                    continue;
+                }
+            }
+        }
+
+        /* This provides the FastList with an opportunity to actually
+       * excise the items identified as "removed" from the list.
+       */
+        contents.reap();
+    }
+}
+

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WrittenEntry.java
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WrittenEntry.java?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WrittenEntry.java (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/WrittenEntry.java Tue Dec  9 21:13:53 2008
@@ -0,0 +1,122 @@
+/*
+ * 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 class is used to create a singly-linked list of written nodes
+ * for notification and searches.  When an entry is written, it is
+ * added to this list.  As each thread interested in recently-written
+ * entries works, it has a reference to the <code>WrittenEntry</code>
+ * object that mark the last entry the thread examined.  When it is
+ * done with that entry, it proceeds to the next.  As each of these
+ * references progresses, the <code>WrittenEntry</code> nodes in the
+ * list get left behind to be collected as garbage.
+ * <p>
+ * The list initially starts with the return value of <code>startNode</code>,
+ * and nodes are added using <code>add</code>.  The constructor is private to
+ * enforce this usage.
+ *
+ * @author Sun Microsystems, Inc.
+ * @see OutriggerServerImpl#write
+ * @see OutriggerServerImpl#getMatch(EntryRep,Transaction,long,boolean,boolean,RemoteEventListener,long)
+ * @see Notifier
+ */
+class WrittenEntry
+{
+    /**
+     * The time at which this entry was written.
+     */
+    private long timestamp;
+
+    /**
+     * The next node in the list.
+     */
+    private WrittenEntry next;
+
+    /**
+     * The EntryRep this node refers to.
+     */
+    private EntryRep rep;
+
+    /**
+     * Create a new time-stamped entry for the given EntryRep.  The comment
+     * for the class explains why this is private.
+     */
+    private WrittenEntry( EntryRep rep )
+    {
+        this.rep = rep;
+        timestamp = System.currentTimeMillis();
+    }
+
+    /**
+     * Return the node which is the head of the list.  It is time-stamped,
+     * and has an <code>EntryRep</code> of <code>null</code>.
+     */
+    static WrittenEntry startNode()
+    {
+        return new WrittenEntry( null );
+    }
+
+    /**
+     * Add a new entry after this one.  If this entry has already had a node
+     * added (possibly by another thread), <code>add</code> will skip ahead to
+     * the end of the list.
+     */
+    synchronized WrittenEntry add( EntryRep rep )
+    {
+        WrittenEntry entry = this;
+        for( entry = this; entry.next != null; entry = entry.next )
+        {
+            continue;
+        }
+        return ( entry.next = new WrittenEntry( rep ) );
+    }
+
+    /**
+     * Return the time stamp when this entry was written.
+     */
+    long timestamp()
+    {
+        return timestamp;
+    }
+
+    /**
+     * Return the EntryRep of this entry.  If this is the first node (the one
+     * returned by <code>startNode</code>), the EntryRep is <code>null</code>.
+     *
+     * @see #startNode
+     */
+    EntryRep rep()
+    {
+        return rep;
+    }
+
+    /**
+     * Return the next object in the list.
+     */
+    WrittenEntry next()
+    {
+        return next;
+    }
+
+    public String toString()
+    {
+        return
+            ( rep + " (" + timestamp + ") ->" + ( next == null ? " null" : "" ) );
+    }
+}

Added: incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/build.xml
URL: http://svn.apache.org/viewvc/incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/build.xml?rev=724979&view=auto
==============================================================================
--- incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/build.xml (added)
+++ incubator/river/jtsk/skunk/niclas1/services/outrigger/src/main/java/com/sun/jini/outrigger/build.xml Tue Dec  9 21:13:53 2008
@@ -0,0 +1,248 @@
+<!--
+ ! 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.
+ !-->
+
+<project name="outrigger" basedir="." default="all">
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## ENVIRONMENT SETTINGS						-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <property name="top" location="../../../../.."/>
+
+  <property name="pkg-path" value="com/sun/jini/${ant.project.name}"/>
+
+  <!-- ##								-->
+  <!-- ## Set java-source for use with the javac task:			-->
+  <!-- ##								-->
+
+  <property name="java-source" value="${pkg-path}/**/*.java"/>
+
+  <import file="${top}/build_common.xml"/>
+
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## TARGET: all							-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <target name="all"
+          description=""
+          depends="compile,
+		   this.stubs">
+
+  </target>
+
+
+  <!-- ################################################################ -->
+  <!-- ##                                                               -->
+  <!-- ## TARGET: clean                                                 -->
+  <!-- ##                                                               -->
+  <!-- ################################################################ -->
+
+  <target name="clean"
+          description="Removes all files and dirs created by the build."
+          depends="clean.jre.ext">
+
+    <delete dir="${build.classes}/${pkg-path}" quiet="true"/>
+
+  </target>
+
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## TARGET: this.jars						-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <target name="this.jars"
+          depends="outrigger.jar,
+		   outrigger-dl.jar">
+
+  </target>
+
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## TARGET: outrigger.jar						-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <target name="outrigger.jar"
+          depends="tools,
+		   store.jars">
+
+    <property name="outrigger.deps" location="${build.deps}/outrigger.deps"/>
+
+    <!-- ##								-->
+    <!-- ## Run ClassDep.						-->
+    <!-- ##								-->
+
+    <java classname="com.sun.jini.tool.ClassDep"
+          failonerror="true"
+          output="${outrigger.deps}">
+
+      <classpath refid="path.classdep"/>
+      <arg value="-cp"/>
+      <arg path="${build.classes}"/>
+      <arg value="-files"/>
+      <arg line="${jskprivate.include}"/>
+
+      <arg line="-in com.sun.jini.outrigger"/>
+
+      <arg value="com.sun.jini.outrigger.OutriggerPermission"/>
+      <arg value="com.sun.jini.outrigger.OutriggerServerWrapper_Stub"/>
+      <arg value="com.sun.jini.outrigger.PersistentOutriggerImpl"/>
+      <arg value="com.sun.jini.outrigger.TransientOutriggerImpl"/>
+
+    </java>
+
+    <!-- ##								-->
+    <!-- ## Generate the jar file.					-->
+    <!-- ##								-->
+
+    <delete file="${build.lib}/outrigger.jar" quiet="true"/>
+
+    <jar destfile="${build.lib}/outrigger.jar"
+         index="false"
+         manifest="${src.jini.manifest}/outrigger.mf">
+
+      <metainf dir="${src.jini.manifest}/outrigger/META-INF"/>
+
+      <fileset dir="${build.classes}" includesfile="${outrigger.deps}"/>
+
+    </jar>
+
+  </target>
+
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## TARGET: store.jars						-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <target name="store.jars">
+
+    <ant inheritAll="false" dir="snaplogstore"
+         target="outrigger-snaplogstore.jar"/>
+
+  </target>
+
+  <!-- ################################################################ -->
+  <!-- ##								-->
+  <!-- ## TARGET: outrigger-dl.jar					-->
+  <!-- ##								-->
+  <!-- ################################################################ -->
+
+  <target name="outrigger-dl.jar"
+          depends="tools">
+
+    <property name="outrigger-dl.deps" location="${build.deps}/outrigger-dl.deps"/>
+
+    <!-- ##								-->
+    <!-- ## Run ClassDep.						-->
+    <!-- ##								-->
+
+    <java classname="com.sun.jini.tool.ClassDep"
+          failonerror="true"
+          output="${outrigger-dl.deps}">
+
+      <classpath refid="path.classdep"/>
+      <arg value="-cp"/>
+      <arg path="${build.classes}"/>
+      <arg value="-files"/>
+      <arg line="${jskprivate.include}"/>
+
+      <arg line="-in com.sun.jini.landlord"/>
+      <arg line="-in com.sun.jini.outrigger"/>
+
+      <arg value="com.sun.jini.lookup.entry.BasicServiceType"/>
+      <arg value="com.sun.jini.outrigger.OutriggerPermission"/>
+      <arg value="com.sun.jini.outrigger.OutriggerQueryCookie"/>
+      <arg value="com.sun.jini.outrigger.OutriggerServerWrapper_Stub"/>
+      <arg value="com.sun.jini.outrigger.OutriggerAvailabilityEvent"/>
+      <arg value="com.sun.jini.outrigger.ProxyVerifier"/>
+      <arg value="net.jini.lookup.entry.ServiceInfo"/>
+      <arg value="net.jini.space.InternalSpaceException"/>
+
+    </java>
+
+    <!-- ##								-->
+    <!-- ## Generate the jar file.					-->
+    <!-- ##								-->
+
+    <delete file="${build.lib-dl}/outrigger-dl.jar" quiet="true"/>
+
+    <jar destfile="${build.lib-dl}/outrigger-dl.jar"
+         index="false">
+
+      <fileset dir="${build.classes}" includesfile="${outrigger-dl.deps}"/>
+
+    </jar>
+
+    <!-- ##								-->
+    <!-- ## Generate the Preferred List					-->
+    <!-- ##								-->
+
+    <preferredlistgen>
+
+      <plg-elements>
+
+        <arg line="-cp"/>
+        <arg path="${build.lib}/jsk-platform.jar"/>
+
+        <arg line="-jar"/>
+        <arg path="${build.lib-dl}/outrigger-dl.jar"/>
+
+        <arg line="-jar"/>
+        <arg path="${build.lib-dl}/jsk-dl.jar"/>
+
+        <arg line="-proxy com.sun.jini.outrigger.ConstrainableAdminProxy"/>
+        <arg line="-proxy com.sun.jini.outrigger.ConstrainableIteratorProxy"/>
+        <arg line="-proxy com.sun.jini.outrigger.ConstrainableParticipantProxy"/>
+        <arg line="-proxy com.sun.jini.outrigger.ConstrainableSpaceProxy2"/>
+
+      </plg-elements>
+
+    </preferredlistgen>
+
+  </target>
+
+
+  <!-- ################################################################ -->
+  <!-- ##                                                               -->
+  <!-- ## TARGET: this.stubs						-->
+  <!-- ##                                                               -->
+  <!-- ################################################################ -->
+
+  <target name="this.stubs"
+          description="Builds the RMI stubs for ${ant.project.name}."
+          depends="compile">
+
+    <rmic base="${build.classes}" stubversion="1.2">
+      <classpath refid="path.jini"/>
+      <include name="com/sun/jini/outrigger/OutriggerServerWrapper.class"/>
+    </rmic>
+
+  </target>
+
+</project>
+