-
Notifications
You must be signed in to change notification settings - Fork 14
/
ClasspathScanner.java
152 lines (137 loc) · 6.01 KB
/
ClasspathScanner.java
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
/**
* Copyright (C) 2019 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.loaders;
import cz.cvut.kbss.jopa.exceptions.OWLPersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Processes classes available to the current classloader.
*/
class ClasspathScanner {
private static final Logger LOG = LoggerFactory.getLogger(ClasspathScanner.class);
private static final String JAR_FILE_SUFFIX = ".jar";
private static final String CLASS_FILE_SUFFIX = ".class";
private final List<Consumer<Class<?>>> listeners = new ArrayList<>();
private final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
void addListener(Consumer<Class<?>> listener) {
listeners.add(listener);
}
/**
* Inspired by https://github.com/ddopson/java-class-enumerator
*/
void processClasses(String scanPath) {
try {
Enumeration<URL> urls = classLoader.getResources(scanPath.replace('.', '/'));
while (urls.hasMoreElements()) {
final URL url = urls.nextElement();
if (isJar(url.toString())) {
processJarFile(url, scanPath);
} else {
processDirectory(new File(getUrlAsUri(url).getPath()), scanPath);
}
}
// Scan jar files on classpath
Enumeration<URL> resources = classLoader.getResources(".");
while (resources.hasMoreElements()) {
URL resourceURL = resources.nextElement();
if (isJar(resourceURL.toString()))
processJarFile(resourceURL, scanPath);
}
} catch (IOException e) {
throw new OWLPersistenceException("Unable to scan packages for entity classes.", e);
}
}
private static boolean isJar(String filePath) {
return filePath.startsWith("jar:") || filePath.endsWith(JAR_FILE_SUFFIX);
}
private static URI getUrlAsUri(URL url) {
try {
// Transformation to URI handles encoding, e.g. of whitespaces in the path
return url.toURI();
} catch (URISyntaxException ex) {
throw new OWLPersistenceException(
"Unable to scan resource " + url + ". It is not a valid URI.", ex);
}
}
private void processJarFile(URL jarResource, String packageName) {
final String relPath = packageName.replace('.', '/');
final String jarPath = jarResource.getPath().replaceFirst("[.]jar[!].*", JAR_FILE_SUFFIX)
.replaceFirst("file:", "");
LOG.trace("Scanning jar file {} for entity classes.", jarPath);
try (final JarFile jarFile = new JarFile(jarPath)) {
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
String className = null;
if (entryName.endsWith(CLASS_FILE_SUFFIX) && entryName.startsWith(relPath)) {
className = entryName.replace('/', '.').replace('\\', '.');
className = className.substring(0, className.length() - CLASS_FILE_SUFFIX.length());
}
if (className != null) {
processClass(className);
}
}
} catch (IOException e) {
throw new OWLPersistenceException("Unexpected IOException reading JAR File " + jarPath, e);
}
}
private void processClass(String className) {
try {
final Class<?> cls = Class.forName(className, true, classLoader);
listeners.forEach(listener -> listener.accept(cls));
} catch (ClassNotFoundException e) {
throw new OWLPersistenceException("Unexpected ClassNotFoundException when scanning for entities.", e);
}
}
private void processDirectory(File dir, String packageName)
throws MalformedURLException {
LOG.trace("Scanning directory {} for entity classes.", dir);
// Get the list of the files contained in the package
final String[] files = dir.list();
if (files == null) {
return;
}
for (String fileName : files) {
String className = null;
// we are only interested in .class files
if (fileName.endsWith(CLASS_FILE_SUFFIX)) {
// removes the .class extension
className = packageName + '.' + fileName.substring(0, fileName.length() - 6);
}
if (className != null) {
processClass(className);
}
final File subDir = new File(dir, fileName);
if (subDir.isDirectory()) {
processDirectory(subDir, packageName + (!packageName.isEmpty() ? '.' : "") + fileName);
} else if (isJar(subDir.getAbsolutePath())) {
processJarFile(subDir.toURI().toURL(), packageName);
}
}
}
}