Repository navigation
Expand file tree
/
Copy pathClasspathResolver.java
More file actions
84 lines (72 loc) · 3.01 KB
/
Copy pathClasspathResolver.java
File metadata and controls
84 lines (72 loc) · 3.01 KB
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
package com.github.mustachejava.resolver;
import com.github.mustachejava.MustacheResolver;
import java.io.*;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.jar.JarEntry;
/**
* MustacheResolver implementation that resolves mustache files from the classpath.
*/
public class ClasspathResolver implements MustacheResolver {
private final String resourceRoot;
public ClasspathResolver() {
this.resourceRoot = null;
}
/**
* Use the classpath to resolve mustache templates.
*
* @param resourceRoot where to find the templates
*/
public ClasspathResolver(String resourceRoot) {
this.resourceRoot = resourceRoot;
}
@Override
public Reader getReader(String resourceName) {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
String fullResourceName = concatResourceRootAndResourceName(resourceName);
String normalizeResourceName = URI.create(fullResourceName).normalize().getPath();
URL resource = ccl.getResource(normalizeResourceName);
if (resource == null) {
resource = ClasspathResolver.class.getClassLoader().getResource(normalizeResourceName);
}
if (resource != null) {
try {
if (resource.getProtocol().equals("jar") && normalizeResourceName.endsWith("/")) {
return null;
}
if (resource.getProtocol().equals("file") && new File(resource.getPath()).isDirectory()) {
return null;
}
URLConnection connection = resource.openConnection();
if (connection instanceof JarURLConnection) {
JarEntry entry = ((JarURLConnection) connection).getJarEntry();
if (entry == null || entry.isDirectory()) {
return null;
}
}
return new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
} catch (IOException e) {
return null;
}
} else {
return null;
}
}
private String concatResourceRootAndResourceName(String resourceName) {
if ((resourceRoot == null) || (resourceName == null)) {
return resourceName;
} else {
//Ensure there is only one (and only one) forward slash between the resourceRoot and resourceName paths
if (resourceName.startsWith("/") && resourceRoot.endsWith("/")) {
return resourceRoot.substring(0, resourceRoot.length() - 1) + resourceName;
} else if ((resourceName.startsWith("/") && !resourceRoot.endsWith("/")) || (!resourceName.startsWith("/") && resourceRoot.endsWith("/"))) {
return resourceRoot + resourceName;
} else {
return resourceRoot + "/" + resourceName;
}
}
}
}