001    /*
002     * Copyright 2007 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     */
016    package org.kuali.rice.kns.util;
017    
018    import java.util.Iterator;
019    
020    import org.apache.commons.collections.IteratorUtils;
021    
022    /**
023     * This class provides utility methods to support the operation of transactional services
024     */
025    public class TransactionalServiceUtils {
026        /**
027         * Copys iterators so that they may be used outside of this class.  Often, the DAO may
028         * return iterators that may not be used outside of this class because the transaction/
029         * connection may be automatically closed by Spring.
030         * 
031         * This method copies all of the elements in the OJB backed iterators into list-based iterators
032         * by placing the returned BOs into a list
033         * 
034         * @param iter an OJB backed iterator to copy
035         * @return an Iterator that may be used outside of this class
036         */
037        public static <E> Iterator<E> copyToExternallyUsuableIterator(Iterator<E> iter) {
038            return IteratorUtils.toList(iter).iterator();
039        }
040        
041        /**
042         * Returns the first element and exhausts an iterator
043         * 
044         * @param <E> the type of elements in the iterator
045         * @param iterator the iterator to exhaust
046         * @return the first element of the iterator; null if the iterator's empty
047         */
048        public static <E> E retrieveFirstAndExhaustIterator(Iterator<E> iterator) {
049            E returnVal = null;
050            if (iterator.hasNext()) {
051                returnVal = iterator.next();
052            }
053            exhaustIterator(iterator);
054            return returnVal;
055        }
056        
057        /**
058         * Exhausts (i.e. complete iterates through) an iterator
059         * 
060         * @param iterator
061         */
062        public static void exhaustIterator(Iterator<?> iterator) {
063            while (iterator.hasNext()) {
064                iterator.next();
065            }
066        }
067    }