    001/*
    002 * Copyright (c) 2007-2016 Concurrent, Inc. All Rights Reserved.
    003 *
    004 * Project and contact information: http://www.cascading.org/
    005 *
    006 * This file is part of the Cascading project.
    007 *
    008 * Licensed under the Apache License, Version 2.0 (the "License");
    009 * you may not use this file except in compliance with the License.
    010 * You may obtain a copy of the License at
    011 *
    012 *     http://www.apache.org/licenses/LICENSE-2.0
    013 *
    014 * Unless required by applicable law or agreed to in writing, software
    015 * distributed under the License is distributed on an "AS IS" BASIS,
    016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    017 * See the License for the specific language governing permissions and
    018 * limitations under the License.
    019 */
    020
    021package cascading.util;
    022
    023import java.util.Iterator;
    024
    025/**
    026 * Class SingleValueIterator is a convenience to creating an {@link Iterator} that returns one value for use
    027 * with interfaces that only accept Iterator instances.
    028 * <p/>
    029 * If given a {@code null} value, it will be assumed this Iterator instance has no value, and {@link #hasNext()}
    030 * will return false.
    031 */
    032public class SingleValueIterator<Value> implements Iterator<Value>
    033  {
    034  public static final SingleValueIterator EMPTY = new SingleValueIterator();
    035
    036  private boolean hasValue = true;
    037  protected Value value;
    038
    039  public SingleValueIterator()
    040    {
    041    this.hasValue = false;
    042    }
    043
    044  public SingleValueIterator( Value value )
    045    {
    046    this.hasValue = value != null;
    047    this.value = value;
    048    }
    049
    050  @Override
    051  public boolean hasNext()
    052    {
    053    return hasValue;
    054    }
    055
    056  @Override
    057  public Value next()
    058    {
    059    if( !hasValue )
    060      throw new IllegalStateException( "no value available" );
    061
    062    try
    063      {
    064      return value;
    065      }
    066    finally
    067      {
    068      hasValue = false;
    069      }
    070    }
    071
    072  @Override
    073  public void remove()
    074    {
    075    throw new UnsupportedOperationException( "unimplimented" );
    076    }
    077
    078  public void reset( Value value )
    079    {
    080    this.hasValue = value != null;
    081    this.value = value;
    082    }
    083  }