-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathJarFile.java
More file actions
402 lines (361 loc) · 15.2 KB
/
Copy pathJarFile.java
File metadata and controls
402 lines (361 loc) · 15.2 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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.cadixdev.atlas.jar;
import org.cadixdev.atlas.util.NIOHelper;
import org.cadixdev.bombe.jar.AbstractJarEntry;
import org.cadixdev.bombe.provider.ClassProvider;
import org.cadixdev.bombe.jar.JarClassEntry;
import org.cadixdev.bombe.jar.JarEntryTransformer;
import org.cadixdev.bombe.jar.JarManifestEntry;
import org.cadixdev.bombe.jar.JarResourceEntry;
import org.cadixdev.bombe.jar.JarServiceProviderConfigurationEntry;
import org.cadixdev.bombe.jar.ServiceProviderConfiguration;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.jar.Manifest;
import java.util.stream.Stream;
/**
* A representation of a JAR file, with the class entries cached.
*
* @author Jamie Mansfield
* @since 0.1.0
*/
public class JarFile implements ClassProvider, Closeable {
private final Path path;
private final FileSystem fs;
private final Map<JarPath, JarClassEntry> cache = new ConcurrentHashMap<>();
public JarFile(final Path path) throws IOException {
this.path = path;
this.fs = NIOHelper.openZip(this.path, false);
}
/**
* Gets the name (location on file system) of the JAR file.
*
* @return The name
*/
public String getName() {
return this.path.toString();
}
/**
* Gets the entry for the given {@link JarPath JAR path}.
* <p>
* {@link JarClassEntry Class entries} will be cached upon use.
*
* @param path The path of the entry
* @return The entry, or {@code null} if no entry for the path exists
* @throws IOException Should an issue occur reading the entry
*/
public AbstractJarEntry get(final JarPath path) throws IOException {
final Path entry = this.fs.getPath("/", path.getName());
if (Files.notExists(entry)) return null;
if ("META-INF/MANIFEST.MF".equals(path.getName())) {
return _readManifest(entry);
}
else if (path.getName().startsWith("META-INF/services/")) {
return _readServiceConfig(entry);
}
else if (path.getName().endsWith(".class")) {
return this.getClass(path);
}
else {
return _readResource(entry);
}
}
/**
* Gets the <strong>cached</strong> class entry, of the given
* {@link JarPath JAR path}.
*
* @param path The class's JAR entry path
* @return The class entry, or {@code null} if not present
*/
public JarClassEntry getClass(final JarPath path) {
return this.cache.computeIfAbsent(path, p -> {
final Path entry = this.fs.getPath("/", p.getName());
if (Files.notExists(entry)) return null;
try {
return _readClass(entry);
}
catch (final IOException ignored) {
return null;
}
});
}
/**
* Gets the <strong>cached</strong> class entry, of the given name.
*
* @param name The class name
* @return The class entry, or {@code null} if not present
*/
public JarClassEntry getClass(final String name) {
return this.getClass(new JarPath(name));
}
/**
* Walks through the jar entries within the JAR file, omitting those targeted
* by a {@link JarVisitOption}.
*
* @param options The visit options to use, while walking
* @return The jar entries
* @throws IOException Should an issue with reading occur
*/
public Stream<JarPath> walk(final JarVisitOption... options) throws IOException {
return Files.walk(this.fs.getPath("/")).filter(p -> !Files.isDirectory(p)).map(p -> {
final String name = p.toString().substring(1); // Trim leading /
if ("META-INF/MANIFEST.MF".equals(name)) {
if (_contains(JarVisitOption.IGNORE_MANIFESTS, options)) return null;
}
else if (name.startsWith("META-INF/services/")) {
if (_contains(JarVisitOption.IGNORE_SERVICE_PROVIDER_CONFIGURATIONS, options)) return null;
}
else if (name.endsWith(".class")) {
if (_contains(JarVisitOption.IGNORE_CLASSES, options)) return null;
}
else {
if (_contains(JarVisitOption.IGNORE_RESOURCES, options)) return null;
}
return new JarPath(name);
}).filter(Objects::nonNull);
}
/**
* Transforms the JAR file, with the given {@link JarEntryTransformer}s, writing
* to the given output JAR path.
* <p>
* This will use {@link Executors#newWorkStealingPool()} as the executor service,
* use {@link #transform(Path, ExecutorService, JarEntryTransformer...)} if you
* wish to control this.
*
* @param export The JAR path to write to
* @param transformers The transformers to use
* @throws IOException Should an issue with reading or writing occur
* @throws JarTransformFailedException if one or more transformers threw
* exceptions while processing a jar entry
*/
public void transform(final Path export, final JarEntryTransformer... transformers) throws IOException {
final ExecutorService executorService = Executors.newWorkStealingPool();
try {
this.transform(export, executorService, transformers);
}
finally {
executorService.shutdown();
}
}
/**
* Transforms the JAR file, with the given {@link JarEntryTransformer}s, writing
* to the given output JAR path.
*
* @param export The JAR path to write to
* @param executorService The executor service to use
* @param transformers The transformers to use
* @throws IOException Should an issue with reading or writing occur
* @throws JarTransformFailedException if one or more transformers threw
* exceptions while processing a jar entry
* @since 0.2.1
*/
public void transform(final Path export, final ExecutorService executorService, final JarEntryTransformer... transformers) throws IOException {
Files.deleteIfExists(export);
final Map<JarPath, Exception> failedLocations = new ConcurrentHashMap<>();
try (final FileSystem fs = NIOHelper.openZip(export, true)) {
final CompletableFuture<Void> future = CompletableFuture.allOf(this.walk().map(path -> CompletableFuture.runAsync(() -> {
try {
// Get the entry
AbstractJarEntry entry = this.get(path);
if (entry == null) return;
// Transform the entry
for (final JarEntryTransformer transformer : transformers) {
entry = entry.accept(transformer);
if (entry == null) return;
}
// Write to jar
final Path outEntry = fs.getPath("/", entry.getName());
// Ensure parent directory exists
Files.createDirectories(outEntry.getParent());
// Write the result to the new jar
Files.write(outEntry, entry.getContents());
Files.setLastModifiedTime(outEntry, FileTime.fromMillis(entry.getTime()));
}
catch (final Exception ex) {
failedLocations.put(path, ex);
}
}, executorService)).toArray(CompletableFuture[]::new));
future.handle((value, error) -> {
// Capture errors
if (error != null) {
throw new RuntimeException(error);
}
return value;
}).get();
if (!failedLocations.isEmpty()) {
// Some entries failed to transform
throw new JarTransformFailedException("Some entries in " + this.getName() + " failed to be transformed", failedLocations);
}
// Add additions from transformers
for (final JarEntryTransformer transformer : transformers) {
for (final AbstractJarEntry addition : transformer.additions()) {
// Write to jar
final Path outEntry = fs.getPath("/", addition.getName());
// Ensure parent directory exists
Files.createDirectories(outEntry.getParent());
// Write the result to the new jar
Files.write(outEntry, addition.getContents());
Files.setLastModifiedTime(outEntry, FileTime.fromMillis(addition.getTime()));
}
}
}
catch (final InterruptedException ex) {
throw new RuntimeException(ex);
}
catch (final ExecutionException ex) {
try {
throw ex.getCause();
}
catch (final IOException ioe) {
throw ioe;
}
catch (final Throwable cause) {
throw new RuntimeException(cause);
}
}
}
/**
* Processes the JAR file, running the given {@link JarEntryTransformer jar entry transformers}
* for each path within the jar.
* <p>
* The eventual result of transformation is ignored, and not written to file.
* {@link #transform(Path, ExecutorService, JarEntryTransformer...)} should be used if such
* behaviour is desired.
* <p>
* This will use {@link Executors#newWorkStealingPool()} as the executor service, use
* {@link #process(ExecutorService, JarEntryTransformer...)} if you wish to control this.
*
* @param transformers The transformers to use
* @throws IOException Should an issue with reading occur
* @throws JarTransformFailedException if one or more transformers threw
* exceptions while processing a jar entry
* @since 0.2.2
*/
public void process(final JarEntryTransformer... transformers) throws IOException {
final ExecutorService executorService = Executors.newWorkStealingPool();
try {
this.process(executorService, transformers);
}
finally {
executorService.shutdown();
}
}
/**
* Processes the JAR file, running the given {@link JarEntryTransformer jar entry transformers}
* for each path within the jar.
* <p>
* The eventual result of transformation is ignored, and not written to file.
* {@link #transform(Path, ExecutorService, JarEntryTransformer...)} should be used if such
* behaviour is desired.
*
* @param executorService The executor service to use
* @param transformers The transformers to use
* @throws IOException Should an issue with reading occur
* @throws JarTransformFailedException if one or more transformers threw
* exceptions while processing a jar entry
* @since 0.2.2
*/
public void process(final ExecutorService executorService, final JarEntryTransformer... transformers)
throws IOException {
final Map<JarPath, Exception> failedLocations = new ConcurrentHashMap<>();
final CompletableFuture<Void> future = CompletableFuture.allOf(this.walk().map(path -> CompletableFuture.runAsync(() -> {
try {
// Get the entry
AbstractJarEntry entry = this.get(path);
if (entry == null) return;
// Transform the entry
for (final JarEntryTransformer transformer : transformers) {
entry = entry.accept(transformer);
if (entry == null) return;
}
}
catch (final Exception ex) {
failedLocations.put(path, ex);
}
}, executorService)).toArray(CompletableFuture[]::new));
try {
future.handle((value, error) -> {
// Capture errors
if (error != null) {
throw new RuntimeException(error);
}
return value;
}).get();
if (!failedLocations.isEmpty()) {
// Some entries failed to transform
throw new JarTransformFailedException("Some entries in " + this.getName() + " failed to be transformed", failedLocations);
}
}
catch (final InterruptedException ex) {
throw new RuntimeException(ex);
}
catch (final ExecutionException ex) {
try {
throw ex.getCause();
}
catch (final IOException ioe) {
throw ioe;
}
catch (final Throwable cause) {
throw new RuntimeException(cause);
}
}
}
@Override
public byte[] get(final String klass) {
final JarClassEntry entry = this.getClass(klass + ".class");
return entry == null ? null : entry.getContents();
}
@Override
public void close() throws IOException {
this.fs.close();
}
private static JarManifestEntry _readManifest(final Path entry) throws IOException {
final long time = Files.getLastModifiedTime(entry).toMillis();
try (final InputStream is = Files.newInputStream(entry)) {
return new JarManifestEntry(time, new Manifest(is));
}
}
private static JarServiceProviderConfigurationEntry _readServiceConfig(final Path entry) throws IOException {
final String name = entry.toString().substring(1); // Remove '/' prefix
final long time = Files.getLastModifiedTime(entry).toMillis();
try (final InputStream is = Files.newInputStream(entry)) {
final String serviceName = name.substring("META-INF/services/".length());
final ServiceProviderConfiguration config = new ServiceProviderConfiguration(serviceName);
config.read(is);
return new JarServiceProviderConfigurationEntry(time, config);
}
}
private static JarClassEntry _readClass(final Path entry) throws IOException {
final String name = entry.toString().substring(1); // Remove '/' prefix
final long time = Files.getLastModifiedTime(entry).toMillis();
return new JarClassEntry(name, time, Files.readAllBytes(entry));
}
private static JarResourceEntry _readResource(final Path entry) throws IOException {
final String name = entry.toString().substring(1); // Remove '/' prefix
final long time = Files.getLastModifiedTime(entry).toMillis();
return new JarResourceEntry(name, time, Files.readAllBytes(entry));
}
private static <T> boolean _contains(final T entry, final T[] in) {
for (final T i : in) {
if (i == entry) return true;
}
return false;
}
}