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 *    https://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 */
020package org.apache.directory.api.util;
021
022
023import javax.naming.NamingEnumeration;
024
025import java.util.NoSuchElementException;
026
027
028/**
029 * A NamingEnumeration over a single element.
030 * 
031 * @param <T> The element in the enumeration
032 * 
033 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
034 */
035public class SingletonEnumeration<T> implements NamingEnumeration<T>
036{
037    /** The singleton element to return */
038    private final T element;
039
040    /** Can we return a element */
041    private boolean hasMore = true;
042
043
044    /**
045     * Creates a NamingEnumeration over a single element.
046     * 
047     * @param element The element to store in this enumeration
048     */
049    public SingletonEnumeration( final T element )
050    {
051        this.element = element;
052    }
053
054
055    /**
056     * Makes calls to hasMore to false even if we had more.
057     * 
058     * @see javax.naming.NamingEnumeration#close()
059     */
060    @Override
061    public void close()
062    {
063        hasMore = false;
064    }
065
066
067    /**
068     * @see javax.naming.NamingEnumeration#hasMore()
069     */
070    @Override
071    public boolean hasMore()
072    {
073        return hasMore;
074    }
075
076
077    /**
078     * @see javax.naming.NamingEnumeration#next()
079     */
080    @Override
081    public T next()
082    {
083        if ( hasMore )
084        {
085            hasMore = false;
086            return element;
087        }
088
089        throw new NoSuchElementException();
090    }
091
092
093    /**
094     * @see java.util.Enumeration#hasMoreElements()
095     */
096    @Override
097    public boolean hasMoreElements()
098    {
099        return hasMore;
100    }
101
102
103    /**
104     * @see java.util.Enumeration#nextElement()
105     */
106    @Override
107    public T nextElement()
108    {
109        return next();
110    }
111}