001/**
002 * Copyright 2010-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.common.util.xml.jaxb.adapter;
017
018import java.util.Collection;
019import java.util.Collections;
020
021import javax.xml.bind.annotation.adapters.XmlAdapter;
022
023import org.kuali.common.util.xml.jaxb.wrapper.CollectionWrapper;
024
025public class ImmutableCollectionAdapter<T> extends XmlAdapter<CollectionWrapper<T>, Collection<T>> {
026
027        private final Collection<T> EMPTY_COLLECTION = Collections.emptyList();
028        private final CollectionWrapper<T> EMPTY_WRAPPER = new CollectionWrapper<T>(EMPTY_COLLECTION);
029
030        @Override
031        public CollectionWrapper<T> marshal(Collection<T> c) {
032                if (isEmpty(c)) {
033                        return EMPTY_WRAPPER;
034                } else {
035                        return new CollectionWrapper<T>(c);
036                }
037        }
038
039        @Override
040        public Collection<T> unmarshal(CollectionWrapper<T> wrapper) {
041                if (isEmpty(wrapper.getCollection())) {
042                        return EMPTY_COLLECTION;
043                } else {
044                        return Collections.unmodifiableCollection(wrapper.getCollection());
045                }
046        }
047
048        protected static boolean isEmpty(Collection<?> c) {
049                return c == null || c.size() == 0;
050        }
051
052}