001    /*
002     *  Licensed to the Apache Software Foundation (ASF) under one
003     *  or more contributor license agreements.  See the NOTICE file
004     *  distributed with this work for additional information
005     *  regarding copyright ownership.  The ASF licenses this file
006     *  to you under the Apache License, Version 2.0 (the
007     *  "License"); you may not use this file except in compliance
008     *  with the License.  You may obtain a copy of the License at
009     *  
010     *    http://www.apache.org/licenses/LICENSE-2.0
011     *  
012     *  Unless required by applicable law or agreed to in writing,
013     *  software distributed under the License is distributed on an
014     *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     *  KIND, either express or implied.  See the License for the
016     *  specific language governing permissions and limitations
017     *  under the License. 
018     *  
019     */
020    package org.apache.directory.server.xdbm.search.impl;
021    
022    
023    import org.apache.directory.server.core.entry.ServerEntry;
024    import org.apache.directory.server.xdbm.AbstractIndexCursor;
025    import org.apache.directory.server.xdbm.ForwardIndexEntry;
026    import org.apache.directory.server.xdbm.Index;
027    import org.apache.directory.server.xdbm.IndexCursor;
028    import org.apache.directory.server.xdbm.IndexEntry;
029    import org.apache.directory.server.xdbm.Store;
030    import org.apache.directory.shared.ldap.cursor.InvalidCursorPositionException;
031    
032    
033    /**
034     * A Cursor traversing candidates matching a Substring assertion expression.
035     *
036     * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
037     * @version $Rev$
038     */
039    public class SubstringCursor extends AbstractIndexCursor<String, ServerEntry>
040    {
041        private static final String UNSUPPORTED_MSG =
042            "SubstringCursors may not be ordered and do not support positioning by element.";
043        private final boolean hasIndex;
044        private final IndexCursor<String,ServerEntry> wrapped;
045        private final SubstringEvaluator evaluator;
046        private final ForwardIndexEntry<String,ServerEntry> indexEntry =
047            new ForwardIndexEntry<String,ServerEntry>();
048        private boolean available = false;
049    
050    
051        @SuppressWarnings("unchecked")
052        public SubstringCursor( Store<ServerEntry> db,
053                                final SubstringEvaluator substringEvaluator ) throws Exception
054        {
055            evaluator = substringEvaluator;
056            hasIndex = db.hasUserIndexOn( evaluator.getExpression().getAttribute() );
057    
058            if ( hasIndex )
059            {
060                wrapped = ( ( Index<String,ServerEntry> ) db.getUserIndex( evaluator.getExpression().getAttribute() ) )
061                    .forwardCursor();
062            }
063            else
064            {
065                /*
066                 * There is no index on the attribute here.  We have no choice but
067                 * to perform a full table scan but need to leverage an index for the
068                 * wrapped Cursor.  We know that all entries are listed under
069                 * the ndn index and so this will enumerate over all entries.  The
070                 * substringEvaluator is used in an assertion to constrain the
071                 * result set to only those entries matching the pattern.  The
072                 * substringEvaluator handles all the details of normalization and
073                 * knows to use it, when it itself detects the lack of an index on
074                 * the node's attribute.
075                 */
076                wrapped = db.getNdnIndex().forwardCursor();
077            }
078        }
079    
080    
081        public boolean available()
082        {
083            return available;
084        }
085    
086    
087        public void beforeValue( Long id, String value ) throws Exception
088        {
089            throw new UnsupportedOperationException( UNSUPPORTED_MSG );
090        }
091    
092    
093        public void afterValue( Long id, String value ) throws Exception
094        {
095            throw new UnsupportedOperationException( UNSUPPORTED_MSG );
096        }
097    
098    
099        public void before( IndexEntry<String, ServerEntry> element ) throws Exception
100        {
101            throw new UnsupportedOperationException( UNSUPPORTED_MSG );
102        }
103    
104    
105        public void after( IndexEntry<String, ServerEntry> element ) throws Exception
106        {
107            throw new UnsupportedOperationException( UNSUPPORTED_MSG );
108        }
109    
110    
111        public void beforeFirst() throws Exception
112        {
113            checkNotClosed( "beforeFirst()" );
114            if ( evaluator.getExpression().getInitial() != null && hasIndex )
115            {
116                ForwardIndexEntry<String,ServerEntry> indexEntry = new ForwardIndexEntry<String,ServerEntry>();
117                indexEntry.setValue( evaluator.getExpression().getInitial() );
118                wrapped.before( indexEntry );
119            }
120            else
121            {
122                wrapped.beforeFirst();
123            }
124    
125            clear();
126        }
127    
128    
129        private void clear()
130        {
131            available = false;
132            indexEntry.setObject( null );
133            indexEntry.setId( null );
134            indexEntry.setValue( null );
135        }
136    
137    
138        public void afterLast() throws Exception
139        {
140            checkNotClosed( "afterLast()" );
141    
142            // to keep the cursor always *after* the last matched tuple
143            // This fixes an issue if the last matched tuple is also the last record present in the 
144            // index. In this case the wrapped cursor is positioning on the last tuple instead of positioning after that
145            wrapped.afterLast();
146            clear();
147        }
148    
149    
150        public boolean first() throws Exception
151        {
152            beforeFirst();
153            return next();
154        }
155    
156    
157        private boolean evaluateCandidate( IndexEntry<String,ServerEntry> indexEntry ) throws Exception
158        {
159            if ( hasIndex )
160            {
161                return evaluator.getPattern().matcher( indexEntry.getValue() ).matches();
162            }
163            else
164            {
165                return evaluator.evaluate( indexEntry );
166            }
167        }
168    
169    
170        public boolean last() throws Exception
171        {
172            afterLast();
173            return previous();
174        }
175    
176    
177        public boolean previous() throws Exception
178        {
179            while ( wrapped.previous() )
180            {
181                checkNotClosed( "previous()" );
182                IndexEntry<String,ServerEntry> entry = wrapped.get();
183                if ( evaluateCandidate( entry ) )
184                {
185                    available = true;
186                    this.indexEntry.setId( entry.getId() );
187                    this.indexEntry.setValue( entry.getValue() );
188                    this.indexEntry.setObject( entry.getObject() );
189                    return true;
190                }
191            }
192    
193            clear();
194            return false;
195        }
196    
197    
198        public boolean next() throws Exception
199        {
200            while ( wrapped.next() )
201            {
202                checkNotClosed( "next()" );
203                IndexEntry<String,ServerEntry> entry = wrapped.get();
204                if ( evaluateCandidate( entry ) )
205                {
206                    available = true;
207                    this.indexEntry.setId( entry.getId() );
208                    this.indexEntry.setValue( entry.getValue() );
209                    this.indexEntry.setObject( entry.getObject() );
210                    return true;
211                }
212            }
213    
214            clear();
215            return false;
216        }
217    
218    
219        public IndexEntry<String, ServerEntry> get() throws Exception
220        {
221            checkNotClosed( "get()" );
222            if ( available )
223            {
224                return indexEntry;
225            }
226    
227            throw new InvalidCursorPositionException( "Cursor has yet to be positioned." );
228        }
229    
230    
231        public boolean isElementReused()
232        {
233            return wrapped.isElementReused();
234        }
235    
236    
237        public void close() throws Exception
238        {
239            super.close();
240            wrapped.close();
241            clear();
242        }
243    }