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 over entry candidates matching a LessEq assertion filter.  This
035     * Cursor operates in two modes.  The first is when an index exists for the
036     * attribute the assertion is built on.  The second is when the user index for
037     * the assertion attribute does not exist.  Different Cursors are used in each
038     * of these cases where the other remains null.
039     *
040     * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
041     * @version $$Rev$$
042     */
043    public class LessEqCursor<V> extends AbstractIndexCursor<V, ServerEntry>
044    {
045        private static final String UNSUPPORTED_MSG =
046            "LessEqCursors only support positioning by element when a user index exists on the asserted attribute.";
047    
048        /** An less eq evaluator for candidates */
049        private final LessEqEvaluator lessEqEvaluator;
050    
051        /** Cursor over attribute entry matching filter: set when index present */
052        private final IndexCursor<V,ServerEntry> userIdxCursor;
053    
054        /** NDN Cursor on all entries in  (set when no index on user attribute) */
055        private final IndexCursor<V,ServerEntry> ndnIdxCursor;
056    
057        /**
058         * Used to store indexEntry from ndnCandidate so it can be saved after
059         * call to evaluate() which changes the value so it's not referring to
060         * the NDN but to the value of the attribute instead.
061         */
062        IndexEntry<V, ServerEntry> ndnCandidate;
063    
064        /** used in both modes */
065        private boolean available = false;
066    
067    
068        @SuppressWarnings("unchecked")
069        public LessEqCursor( Store<ServerEntry> db, LessEqEvaluator lessEqEvaluator ) throws Exception
070        {
071            this.lessEqEvaluator = lessEqEvaluator;
072    
073            String attribute = lessEqEvaluator.getExpression().getAttribute();
074            if ( db.hasUserIndexOn( attribute ) )
075            {
076                userIdxCursor = ( ( Index<V,ServerEntry> ) db.getUserIndex( attribute ) ).forwardCursor();
077                ndnIdxCursor = null;
078            }
079            else
080            {
081                ndnIdxCursor = ( IndexCursor<V,ServerEntry> ) db.getNdnIndex().forwardCursor();
082                userIdxCursor = null;
083            }
084        }
085    
086    
087        public boolean available()
088        {
089            return available;
090        }
091    
092    
093        public void beforeValue( Long id, V value ) throws Exception
094        {
095            checkNotClosed( "beforeValue()" );
096            if ( userIdxCursor != null )
097            {
098                /*
099                 * First we need to check and make sure this element is within
100                 * bounds as mandated by the assertion node.  To do so we compare
101                 * it's value with the value of the expression node.  If the
102                 * element's value is greater than this upper bound then we
103                 * position the userIdxCursor after the last node.
104                 *
105                 * If the element's value is equal to this upper bound then we
106                 * position the userIdxCursor right before the last node.
107                 *
108                 * If the element's value is smaller, then we delegate to the
109                 * before() method of the userIdxCursor.
110                 */
111                //noinspection unchecked
112                int compareValue = lessEqEvaluator.getComparator().compare( value,
113                     lessEqEvaluator.getExpression().getValue().get() );
114    
115                if ( compareValue > 0 )
116                {
117                    afterLast();
118                    return;
119                }
120                else if ( compareValue == 0 )
121                {
122                    last();
123                    previous();
124                    available = false;
125                    return;
126                }
127    
128                userIdxCursor.beforeValue( id, value );
129                available = false;
130            }
131            else
132            {
133                throw new UnsupportedOperationException( UNSUPPORTED_MSG );
134            }
135        }
136    
137    
138        @SuppressWarnings("unchecked")
139        public void before( IndexEntry<V, ServerEntry> element ) throws Exception
140        {
141            checkNotClosed( "before()" );
142            if ( userIdxCursor != null )
143            {
144                /*
145                 * First we need to check and make sure this element is within
146                 * bounds as mandated by the assertion node.  To do so we compare
147                 * it's value with the value of the expression node.  If the
148                 * element's value is greater than this upper bound then we
149                 * position the userIdxCursor after the last node.
150                 *
151                 * If the element's value is equal to this upper bound then we
152                 * position the userIdxCursor right before the last node.
153                 *
154                 * If the element's value is smaller, then we delegate to the
155                 * before() method of the userIdxCursor.
156                 */
157                int compareValue = lessEqEvaluator.getComparator().compare( element.getValue(),
158                     lessEqEvaluator.getExpression().getValue().get() );
159    
160                if ( compareValue > 0 )
161                {
162                    afterLast();
163                    return;
164                }
165                else if ( compareValue == 0 )
166                {
167                    last();
168                    previous();
169                    available = false;
170                    return;
171                }
172    
173                userIdxCursor.before( element );
174                available = false;
175            }
176            else
177            {
178                throw new UnsupportedOperationException( UNSUPPORTED_MSG );
179            }
180        }
181    
182    
183        @SuppressWarnings("unchecked")
184        public void afterValue( Long id, V value ) throws Exception
185        {
186            checkNotClosed( "afterValue()" );
187            if ( userIdxCursor != null )
188            {
189                int comparedValue = lessEqEvaluator.getComparator().compare( value,
190                     lessEqEvaluator.getExpression().getValue().get() );
191    
192                /*
193                 * First we need to check and make sure this element is within
194                 * bounds as mandated by the assertion node.  To do so we compare
195                 * it's value with the value of the expression node.
196                 *
197                 * If the element's value is equal to or greater than this upper
198                 * bound then we position the userIdxCursor after the last node.
199                 *
200                 * If the element's value is smaller, then we delegate to the
201                 * after() method of the userIdxCursor.
202                 */
203                if ( comparedValue >= 0 )
204                {
205                    afterLast();
206                    return;
207                }
208    
209                // Element is in the valid range as specified by assertion
210                userIdxCursor.afterValue( id, value );
211                available = false;
212            }
213            else
214            {
215                throw new UnsupportedOperationException( UNSUPPORTED_MSG );
216            }
217        }
218    
219    
220        @SuppressWarnings("unchecked")
221        public void after( IndexEntry<V, ServerEntry> element ) throws Exception
222        {
223            checkNotClosed( "after()" );
224            if ( userIdxCursor != null )
225            {
226                int comparedValue = lessEqEvaluator.getComparator().compare( element.getValue(),
227                     lessEqEvaluator.getExpression().getValue().get() );
228    
229                /*
230                 * First we need to check and make sure this element is within
231                 * bounds as mandated by the assertion node.  To do so we compare
232                 * it's value with the value of the expression node.
233                 *
234                 * If the element's value is equal to or greater than this upper
235                 * bound then we position the userIdxCursor after the last node.
236                 *
237                 * If the element's value is smaller, then we delegate to the
238                 * after() method of the userIdxCursor.
239                 */
240                if ( comparedValue >= 0 )
241                {
242                    afterLast();
243                    return;
244                }
245    
246                // Element is in the valid range as specified by assertion
247                userIdxCursor.after( element );
248                available = false;
249            }
250            else
251            {
252                throw new UnsupportedOperationException( UNSUPPORTED_MSG );
253            }
254        }
255    
256    
257        public void beforeFirst() throws Exception
258        {
259            checkNotClosed( "beforeFirst()" );
260            if ( userIdxCursor != null )
261            {
262                userIdxCursor.beforeFirst();
263            }
264            else
265            {
266                ndnIdxCursor.beforeFirst();
267                ndnCandidate = null;
268            }
269    
270            available = false;
271        }
272    
273    
274        public void afterLast() throws Exception
275        {
276            checkNotClosed( "afterLast()" );
277            if ( userIdxCursor != null )
278            {
279                IndexEntry<V,ServerEntry> advanceTo = new ForwardIndexEntry<V,ServerEntry>();
280                //noinspection unchecked
281                advanceTo.setValue( ( V ) lessEqEvaluator.getExpression().getValue().get() );
282                userIdxCursor.after( advanceTo );
283            }
284            else
285            {
286                ndnIdxCursor.afterLast();
287                ndnCandidate = null;
288            }
289    
290            available = false;
291        }
292    
293    
294        public boolean first() throws Exception
295        {
296            beforeFirst();
297            return next();
298        }
299    
300    
301        public boolean last() throws Exception
302        {
303            afterLast();
304            return previous();
305        }
306    
307    
308        public boolean previous() throws Exception
309        {
310            checkNotClosed( "previous()" );
311    
312            if ( userIdxCursor != null )
313            {
314                /*
315                 * No need to do the same check that is done in next() since
316                 * values are decreasing with calls to previous().  We will
317                 * always have lesser values.
318                 */
319                return available = userIdxCursor.previous();
320            }
321    
322            while( ndnIdxCursor.previous() )
323            {
324                checkNotClosed( "previous()" );
325                ndnCandidate = ndnIdxCursor.get();
326                if ( lessEqEvaluator.evaluate( ndnCandidate ) )
327                {
328                     return available = true;
329                }
330                else
331                {
332                    ndnCandidate = null;
333                }
334            }
335    
336            return available = false;
337        }
338    
339    
340        @SuppressWarnings("unchecked")
341        public boolean next() throws Exception
342        {
343            checkNotClosed( "next()" );
344            if ( userIdxCursor != null )
345            {
346                /*
347                 * We have to check and make sure the next value complies by
348                 * being less than or eq to the expression node's value.  We need
349                 * to do this since values are increasing and we must limit to our
350                 * upper bound.
351                 */
352                while ( userIdxCursor.next() )
353                {
354                    checkNotClosed( "next()" );
355                    IndexEntry<?,ServerEntry> candidate = userIdxCursor.get();
356                    if ( lessEqEvaluator.getComparator().compare( candidate.getValue(),
357                         lessEqEvaluator.getExpression().getValue().get() ) <= 0 )
358                    {
359                        return available = true;
360                    }
361                }
362    
363                return available = false;
364            }
365    
366            while( ndnIdxCursor.next() )
367            {
368                checkNotClosed( "next()" );
369                ndnCandidate = ndnIdxCursor.get();
370                if ( lessEqEvaluator.evaluate( ndnCandidate ) )
371                {
372                     return available = true;
373                }
374                else
375                {
376                    ndnCandidate = null;
377                }
378            }
379    
380            return available = false;
381        }
382    
383    
384        public IndexEntry<V, ServerEntry> get() throws Exception
385        {
386            checkNotClosed( "get()" );
387            if ( userIdxCursor != null )
388            {
389                if ( available )
390                {
391                    return userIdxCursor.get();
392                }
393    
394                throw new InvalidCursorPositionException( "Cursor has not been positioned yet." );
395            }
396    
397            if ( available )
398            {
399                return ndnCandidate;
400            }
401    
402            throw new InvalidCursorPositionException( "Cursor has not been positioned yet." );
403        }
404    
405    
406        public boolean isElementReused()
407        {
408            if ( userIdxCursor != null )
409            {
410                return userIdxCursor.isElementReused();
411            }
412    
413            return ndnIdxCursor.isElementReused();
414        }
415    
416    
417        public void close() throws Exception
418        {
419            super.close();
420    
421            if ( userIdxCursor != null )
422            {
423                userIdxCursor.close();
424            }
425            else
426            {
427                ndnIdxCursor.close();
428                ndnCandidate = null;
429             }
430        }
431    }