001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021
022package org.biojava.utils;
023
024import java.io.BufferedReader;
025import java.io.IOException;
026import java.io.InputStreamReader;
027import java.net.URL;
028import java.util.Collections;
029import java.util.Enumeration;
030import java.util.HashSet;
031import java.util.Set;
032
033/**
034 * Utility methods for handling META-INF/services files
035 *
036 * @author Thomas Down
037 * @author Matthew Pocock
038 * @since 1.3
039 */
040
041public class Services {
042    /**
043     * Return a Set of names of implementations of the
044     * given service interface in the classloader from 
045     * which BioJava was loaded.
046     */
047    public static Set getImplementationNames(Class serviceIF)
048        throws IOException
049    {
050        return getImplementationNames(serviceIF,
051                                      ClassTools.getClassLoader(Services.class));
052    }
053
054    /**
055     * Return a List of names of implementations of the
056     * given service interface available in a given
057     * classloader.
058     */
059    public static Set getImplementationNames(Class serviceIF, ClassLoader loader)
060        throws IOException
061    {
062        String serviceName = serviceIF.getName();
063        Enumeration serviceFiles = loader.getResources("META-INF/services/"
064                                                       + serviceName);
065        Set names = new HashSet();
066
067        while (serviceFiles.hasMoreElements()) {
068            URL serviceFile = (URL) serviceFiles.nextElement();
069            BufferedReader serviceReader =
070                new BufferedReader(new InputStreamReader(serviceFile.openStream()));
071            String implName;
072
073            while ((implName = serviceReader.readLine()) != null) {
074              if(implName.length() > 0) {
075                names.add(implName);
076              }
077            }
078        }
079
080        return Collections.unmodifiableSet(names);
081    }
082}