001/* 002 * Copyright (C) 2014 Jörg Prante 003 * 004 * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 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.xbib.elasticsearch.plugin.jdbc.classloader; 017 018import java.net.URL; 019import java.util.Collection; 020import java.util.Enumeration; 021import java.util.Iterator; 022import java.util.NoSuchElementException; 023 024public class ResourceEnumeration implements Enumeration<URL> { 025 026 private Iterator iterator; 027 028 private final String resourceName; 029 030 private URL 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 URL nextElement() { 043 fetchNext(); 044 // save next into a local variable and clear the next field 045 URL next = this.next; 046 this.next = null; 047 // if we didn't have a next throw an exception 048 if (next == null) { 049 throw new NoSuchElementException(); 050 } 051 return next; 052 } 053 054 private void fetchNext() { 055 if (iterator == null) { 056 return; 057 } 058 if (next != null) { 059 return; 060 } 061 try { 062 while (iterator.hasNext()) { 063 ResourceLocation resourceLocation = (ResourceLocation) iterator.next(); 064 ResourceHandle resourceHandle = resourceLocation.getResourceHandle(resourceName); 065 if (resourceHandle != null) { 066 next = resourceHandle.getUrl(); 067 return; 068 } 069 } 070 // no more elements 071 // clear the iterator so it can be GCed 072 iterator = null; 073 } catch (IllegalStateException e) { 074 // Jar file was closed... this means the resource finder was destroyed 075 // clear the iterator so it can be GCed 076 iterator = null; 077 throw e; 078 } 079 } 080}