aboutsummaryrefslogtreecommitdiff
path: root/src/utils/lombok/core/SpiLoadUtil.java
blob: 0feb7f123b0c35947202695b94292c443010e4ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*
 * Copyright (C) 2009-2011 The Project Lombok Authors.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package lombok.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * The java core libraries have a SPI discovery system, but it works only in Java 1.6 and up. For at least Eclipse,
 * lombok actually works in java 1.5, so we've rolled our own SPI discovery system.
 * 
 * It is not API compatible with {@code ServiceLoader}.
 * 
 * @see java.util.ServiceLoader
 */
public class SpiLoadUtil {
	private SpiLoadUtil() {
		//Prevent instantiation
	}
	
	/**
	 * Method that conveniently turn the {@code Iterable}s returned by the other methods in this class to a
	 * {@code List}.
	 * 
	 * @see #findServices(Class)
	 * @see #findServices(Class, ClassLoader)
	 */
	public static <T> List<T> readAllFromIterator(Iterable<T> findServices) {
		List<T> list = new ArrayList<T>();
		for (T t : findServices) list.add(t);
		return list;
	}
	
	/**
	 * Returns an iterator of instances that, at least according to the spi discovery file, are implementations
	 * of the stated class.
	 * 
	 * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor.
	 * 
	 * Convenience method that calls the more elaborate {@link #findServices(Class, ClassLoader)} method with
	 * this {@link java.lang.Thread}'s context class loader as {@code ClassLoader}.
	 * 
	 * @param target class to find implementations for.
	 */
	public static <C> Iterable<C> findServices(Class<C> target) throws IOException {
		return findServices(target, Thread.currentThread().getContextClassLoader());
	}
	
	/**
	 * Returns an iterator of class objects that, at least according to the spi discovery file, are implementations
	 * of the stated class.
	 * 
	 * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor.
	 * 
	 * @param target class to find implementations for.
	 * @param loader The classloader object to use to both the spi discovery files, as well as the loader to use
	 * to make the returned instances.
	 */
	public static <C> Iterable<C> findServices(final Class<C> target, ClassLoader loader) throws IOException {
		if (loader == null) loader = ClassLoader.getSystemClassLoader();
		Enumeration<URL> resources = loader.getResources("META-INF/services/" + target.getName());
		final Set<String> entries = new LinkedHashSet<String>();
		while (resources.hasMoreElements()) {
			URL url = resources.nextElement();
			readServicesFromUrl(entries, url);
		}
		
		final Iterator<String> names = entries.iterator();
		final ClassLoader fLoader = loader;
		return new Iterable<C> () {
			@Override public Iterator<C> iterator() {
				return new Iterator<C>() {
					@Override public boolean hasNext() {
						return names.hasNext();
					}
					
					@Override public C next() {
						try {
							return target.cast(Class.forName(names.next(), true, fLoader).getConstructor().newInstance());
						} catch (Exception e) {
							Throwable t = e;
							if (t instanceof InvocationTargetException) t = t.getCause();
							if (t instanceof RuntimeException) throw (RuntimeException) t;
							if (t instanceof Error) throw (Error) t;
							throw new RuntimeException(t);
						}
					}
					
					@Override public void remove() {
						throw new UnsupportedOperationException();
					}
				};
			}
		};
	}
	
	private static void readServicesFromUrl(Collection<String> list, URL url) throws IOException {
		InputStream in = url.openStream();
		BufferedReader r = null;
		try {
			if (in == null) return;
			r = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			while (true) {
				String line = r.readLine();
				if (line == null) break;
				int idx = line.indexOf('#');
				if (idx != -1) line = line.substring(0, idx);
				line = line.trim();
				if (line.length() == 0) continue;
				list.add(line);
			}
		} finally {
			try {
				if (r != null) r.close();
				if (in != null) in.close();
			} catch (Throwable ignore) {}
		}
	}
	
	/**
	 * This method will find the @{code T} in {@code public class Foo extends BaseType<T>}.
	 * 
	 * It returns an annotation type because it is used exclusively to figure out which annotations are
	 * being handled by {@link lombok.eclipse.EclipseAnnotationHandler} and {@link lombok.javac.JavacAnnotationHandler}.
	 */
	public static Class<? extends Annotation> findAnnotationClass(Class<?> c, Class<?> base) {
		if (c == Object.class || c == null) return null;
		Class<? extends Annotation> answer = null;
		
		answer = findAnnotationHelper(base, c.getGenericSuperclass());
		if (answer != null) return answer;
		
		for (Type iface : c.getGenericInterfaces()) {
			answer = findAnnotationHelper(base, iface);
			if (answer != null) return answer;
		}
		
		Class<? extends Annotation> potential = findAnnotationClass(c.getSuperclass(), base);
		if (potential != null) return potential;
		for (Class<?> iface : c.getInterfaces()) {
			potential = findAnnotationClass(iface, base);
			if (potential != null) return potential;
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private static Class<? extends Annotation> findAnnotationHelper(Class<?> base, Type iface) {
		if (iface instanceof ParameterizedType) {
			ParameterizedType p = (ParameterizedType)iface;
			if (!base.equals(p.getRawType())) return null;
			Type target = p.getActualTypeArguments()[0];
			if (target instanceof Class<?>) {
				if (Annotation.class.isAssignableFrom((Class<?>) target)) {
					return (Class<? extends Annotation>) target;
				}
			}
			
			throw new ClassCastException("Not an annotation type: " + target);
		}
		return null;
	}
}