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 package org.apache.geronimo.kernel.classloader;
018
019 import java.util.Enumeration;
020 import java.util.Iterator;
021 import java.util.Collection;
022 import java.util.NoSuchElementException;
023
024 /**
025 * @version $Rev: 476049 $ $Date: 2006-11-16 23:35:17 -0500 (Thu, 16 Nov 2006) $
026 */
027 public class ResourceEnumeration implements Enumeration {
028 private Iterator iterator;
029 private final String resourceName;
030 private Object next;
031
032 public ResourceEnumeration(Collection resourceLocations, String resourceName) {
033 this.iterator = resourceLocations.iterator();
034 this.resourceName = resourceName;
035 }
036
037 public boolean hasMoreElements() {
038 fetchNext();
039 return (next != null);
040 }
041
042 public Object nextElement() {
043 fetchNext();
044
045 // save next into a local variable and clear the next field
046 Object next = this.next;
047 this.next = null;
048
049 // if we didn't have a next throw an exception
050 if (next == null) {
051 throw new NoSuchElementException();
052 }
053 return next;
054 }
055
056 private void fetchNext() {
057 if (iterator == null) {
058 return;
059 }
060 if (next != null) {
061 return;
062 }
063
064 try {
065 while (iterator.hasNext()) {
066 ResourceLocation resourceLocation = (ResourceLocation) iterator.next();
067 ResourceHandle resourceHandle = resourceLocation.getResourceHandle(resourceName);
068 if (resourceHandle != null) {
069 next = resourceHandle.getUrl();
070 return;
071 }
072 }
073 // no more elements
074 // clear the iterator so it can be GCed
075 iterator = null;
076 } catch (IllegalStateException e) {
077 // Jar file was closed... this means the resource finder was destroyed
078 // clear the iterator so it can be GCed
079 iterator = null;
080 throw e;
081 }
082 }
083 }