01: /*
02: * $Id: FactoryServiceFinder.java,v 1.4 2004/07/08 08:01:45 yuvalo Exp $
03: *
04: * (C) Copyright 2002-2004 by Yuval Oren. All rights reserved.
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18:
19: package com.bluecast.util;
20:
21: import java.io.*;
22: import java.util.*;
23: import java.net.*;
24:
25: /**
26: * This class can enumerate all the Providers of a particular Service. It
27: * searches the classpath for META-INF/services/<service name> and returns
28: * the first line of each service. That string is usually the name of the
29: * factory class implementing the requested service.
30: */
31: public class FactoryServiceFinder {
32: static final String SERVICE = "META-INF/services/";
33:
34: /**
35: * Find the first listed provider for the given service name
36: */
37: static public String findService(String name) throws IOException {
38: InputStream is = ClassLoader.getSystemClassLoader()
39: .getResourceAsStream(SERVICE + name);
40: BufferedReader r = new BufferedReader(new InputStreamReader(is,
41: "UTF-8"));
42: return r.readLine();
43: }
44:
45: /**
46: * Return an Enumeration of class name Strings of
47: * available provider classes for the given service.
48: */
49: static public Enumeration findServices(String name)
50: throws IOException {
51: return new FactoryEnumeration(ClassLoader
52: .getSystemClassLoader().getResources(name));
53: }
54:
55: static private class FactoryEnumeration implements Enumeration {
56: Enumeration enumValue;
57: Object next = null;
58:
59: FactoryEnumeration(Enumeration enumValue) {
60: this .enumValue = enumValue;
61: nextElement();
62: }
63:
64: public boolean hasMoreElements() {
65: return (next != null);
66: }
67:
68: public Object nextElement() {
69: Object current = next;
70:
71: while (true) {
72: try {
73: if (enumValue.hasMoreElements()) {
74: BufferedReader r = new BufferedReader(
75: new InputStreamReader(((URL) enumValue
76: .nextElement()).openStream()));
77: next = r.readLine();
78: } else
79: next = null;
80:
81: break;
82: } catch (IOException e) {
83: /* this one got an error. try the next. */
84: }
85: }
86:
87: return current;
88: }
89: }
90:
91: }
|