View Javadoc

1   package com.atlassian.jira.rest.client.api;
2   
3   import javax.annotation.Nullable;
4   import java.util.Collections;
5   import java.util.Iterator;
6   
7   /**
8    * Represent iterable which is optional (for example due to lack of field in old REST API version).<br/>
9    * This iterable is intended to be not null, so you can always get items by using iterator. If you need
10   * to check if value was actually provided then use {@link OptionalIterable#isSupported}.
11   *
12   * @since v1.0
13   */
14  public class OptionalIterable<T> implements Iterable<T> {
15  
16  	@SuppressWarnings("unchecked")
17  	private static final OptionalIterable absentInstance = new OptionalIterable(null);
18  
19  	@Nullable
20  	private final Iterable<T> iterable;
21  
22  	@SuppressWarnings("unchecked")
23  	public static <T> OptionalIterable<T> absent() {
24  		return absentInstance;
25  	}
26  
27  	public OptionalIterable(@Nullable Iterable<T> iterable) {
28  		this.iterable = iterable;
29  	}
30  
31  	/**
32  	 * @return iterator for original iterable if {@link OptionalIterable#isSupported} is true,
33  	 *         or empty iterator in other case.
34  	 */
35  	@Override
36  	public Iterator<T> iterator() {
37  		return isSupported()
38  				? iterable.iterator()
39  				: Collections.<T>emptyList().iterator();
40  	}
41  
42  	/**
43  	 * @return true if server supports this field
44  	 */
45  	public boolean isSupported() {
46  		return iterable != null;
47  	}
48  }