1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package io.earcam.instrumental.reflect;
19
20 import static io.earcam.instrumental.reflect.Names.typeToResourceName;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.UncheckedIOException;
26 import java.net.URI;
27
28 import javax.annotation.WillClose;
29
30 import io.earcam.unexceptional.Exceptional;
31
32
33
34
35
36
37
38 public final class Resources {
39
40 private Resources()
41 {}
42
43
44
45
46
47
48
49
50
51
52 public static byte[] classAsBytes(Class<?> type)
53 {
54 return readAllBytes(classAsStream(type));
55 }
56
57
58 static byte[] readAllBytes(@WillClose InputStream input)
59 {
60 ByteArrayOutputStream baos = new ByteArrayOutputStream();
61
62 int read;
63 try(InputStream in = input) {
64 while((read = in.read()) != -1) {
65 baos.write(read);
66 }
67 } catch(IOException e) {
68 throw new UncheckedIOException(e);
69 }
70 return baos.toByteArray();
71 }
72
73
74
75
76
77
78
79
80
81
82 public static InputStream classAsStream(Class<?> type)
83 {
84 return type.getClassLoader().getResourceAsStream(typeToResourceName(type));
85 }
86
87
88
89
90
91
92
93
94
95
96 public static String sourceOfResource(Class<?> type)
97 {
98 ClassLoader classLoader = type.getClassLoader();
99 return sourceOfResource(type, classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader);
100 }
101
102
103
104
105
106
107
108
109
110
111
112 public static String sourceOfResource(Class<?> type, ClassLoader classLoader)
113 {
114 String className = Names.typeToResourceName(type);
115 String resource = removeJarUrlDecoration(Exceptional.uri(classLoader.getResource(className)));
116 int shebang = resource.indexOf('!');
117 return shebang > -1 ? resource.substring(0, shebang)
118 : resource.substring(0, resource.length() - className.length());
119 }
120
121
122
123
124
125
126
127
128
129
130 public static String removeJarUrlDecoration(URI jar)
131 {
132 return jar.toString()
133 .replaceFirst("^jar:file:", "")
134 .replaceFirst("^file:(//)?", "")
135 .replaceAll("!/$", "");
136 }
137 }