001    /**
002     *
003     * Copyright 2003-2004 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  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 {
028    
029        private final Collection collection;
030    
031        public SingleElementCollection(Object element) {
032            if (element == null) {
033                collection = Collections.EMPTY_SET;
034            } else {
035                collection = Collections.singleton(element);
036            }
037        }
038    
039        public SingleElementCollection(Collection collection) {
040            if (collection == null) {
041                collection = Collections.EMPTY_SET;            
042            }
043    
044            this.collection = collection;
045        }
046    
047        public Object 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 it = collection.iterator();
055            return it.next();
056        }
057    
058    }