001    /**
002     *  Licensed to the Apache Software Foundation (ASF) under one or more
003     *  contributor license agreements.  See the NOTICE file distributed with
004     *  this work for additional information regarding copyright ownership.
005     *  The ASF licenses this file to You under the Apache License, Version 2.0
006     *  (the "License"); you may not use this file except in compliance with
007     *  the License.  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    
018    package org.apache.geronimo.gbean;
019    
020    import java.util.Collection;
021    import java.util.Collections;
022    import java.util.Iterator;
023    
024    /**
025     * A wrapper around a reference collection to simulate a 0..1 reference
026     */
027    public class SingleElementCollection<T> {
028    
029        private final Collection<T> collection;
030    
031        public SingleElementCollection(T element) {
032            if (element == null) {
033                collection = Collections.emptySet();
034            } else {
035                collection = Collections.singleton(element);
036            }
037        }
038    
039        public SingleElementCollection(Collection<T> collection) {
040            if (collection == null) {
041                collection = Collections.emptySet();
042            }
043    
044            this.collection = collection;
045        }
046    
047        public T getElement() {
048            if (collection.isEmpty()) {
049                return null;
050            }
051            if (collection.size() > 1) {
052                throw new IllegalStateException("More than one element: " + collection);
053            }
054            Iterator<T> it = collection.iterator();
055            return it.next();
056        }
057    
058    }