PageRenderTime 28ms CodeModel.GetById 21ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/hudson-core/src/main/java/hudson/util/Service.java

http://github.com/hudson/hudson
Java | 115 lines | 71 code | 9 blank | 35 comment | 8 complexity | d7e16f48192055c185c78952b172d739 MD5 | raw file
  1/*
  2 * The MIT License
  3 * 
  4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
  5 * 
  6 * Permission is hereby granted, free of charge, to any person obtaining a copy
  7 * of this software and associated documentation files (the "Software"), to deal
  8 * in the Software without restriction, including without limitation the rights
  9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 10 * copies of the Software, and to permit persons to whom the Software is
 11 * furnished to do so, subject to the following conditions:
 12 * 
 13 * The above copyright notice and this permission notice shall be included in
 14 * all copies or substantial portions of the Software.
 15 * 
 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 22 * THE SOFTWARE.
 23 */
 24package hudson.util;
 25
 26import java.io.BufferedReader;
 27import java.io.IOException;
 28import java.io.InputStreamReader;
 29import java.net.URL;
 30import java.util.Collection;
 31import java.util.Enumeration;
 32import java.util.List;
 33import java.util.ArrayList;
 34import java.util.logging.Level;
 35import java.util.logging.Logger;
 36import static java.util.logging.Level.WARNING;
 37
 38/**
 39 * Load classes by looking up <tt>META-INF/services</tt>.
 40 *
 41 * @author Kohsuke Kawaguchi
 42 */
 43public class Service {
 44    /**
 45     * Poorman's clone of JDK6 ServiceLoader.
 46     */
 47    public static <T> List<T> loadInstances(ClassLoader classLoader, Class<T> type) throws IOException {
 48        List<T> result = new ArrayList<T>();
 49
 50        final Enumeration<URL> e = classLoader.getResources("META-INF/services/"+type.getName());
 51        while (e.hasMoreElements()) {
 52            URL url = e.nextElement();
 53            BufferedReader configFile = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
 54            String line;
 55            while ((line = configFile.readLine()) != null) {
 56                line = line.trim();
 57                if (line.startsWith("#") || line.length()==0)   continue;
 58
 59                try {
 60                    Class<?> t = classLoader.loadClass(line);
 61                    if (!type.isAssignableFrom(t))   continue;      // invalid type
 62
 63                    result.add(type.cast(t.newInstance()));
 64                } catch (ClassNotFoundException x) {
 65                    LOGGER.log(WARNING,"Failed to load "+line,x);
 66                } catch (InstantiationException x) {
 67                    LOGGER.log(WARNING,"Failed to load "+line,x);
 68                } catch (IllegalAccessException x) {
 69                    LOGGER.log(WARNING,"Failed to load "+line,x);
 70                }
 71            }
 72        }
 73
 74        return result;
 75    }
 76
 77    /**
 78     * Look up <tt>META-INF/service/<i>SPICLASSNAME</i></tt> from the classloader
 79     * and all the discovered classes into the given collection.
 80     */
 81    public static <T> void load(Class<T> spi, ClassLoader cl, Collection<Class<? extends T>> result) {
 82        try {
 83            Enumeration<URL> e = cl.getResources("META-INF/services/" + spi.getName());
 84            while(e.hasMoreElements()) {
 85                BufferedReader r = null;
 86                URL url = e.nextElement();
 87                try {
 88                    r = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
 89                    String line;
 90                    while((line=r.readLine())!=null) {
 91                        if(line.startsWith("#"))
 92                            continue;   // comment line
 93                        line = line.trim();
 94                        if(line.length()==0)
 95                            continue;   // empty line. ignore.
 96
 97                        try {
 98                            result.add(cl.loadClass(line).asSubclass(spi));
 99                        } catch (ClassNotFoundException x) {
100                            LOGGER.log(Level.WARNING, "Failed to load "+line, x);
101                        }
102                    }
103                } catch (IOException x) {
104                    LOGGER.log(Level.WARNING, "Failed to load "+url, x);
105                } finally {
106                    r.close();
107                }
108            }
109        } catch (IOException x) {
110            LOGGER.log(Level.WARNING, "Failed to look up service providers for "+spi, x);
111        }
112    }
113
114    private static final Logger LOGGER = Logger.getLogger(Service.class.getName());
115}