-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathJarUtils.java
More file actions
74 lines (69 loc) · 2.82 KB
/
JarUtils.java
File metadata and controls
74 lines (69 loc) · 2.82 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
package io.arex.agent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class JarUtils {
private static final String JAR_SUFFIX = ".jar";
private static final String DELIMITER = ";";
private static final String NESTED_BOOTSTRAP_JARS_PATH = "Nested-BootStrap-Jars-Path";
/**
* ex:
* arex-agent.jar
* │
* └───bootstrap
* │ │ arex-agent-bootstrap.jar
* │
* └───jackson
* │ jackson.jar
*/
public static List<File> extractNestedBootStrapJar(File file) {
try (JarFile jarFile = new JarFile(file)) {
String nestedBootStrapJarsPath = jarFile.getManifest().getMainAttributes().getValue(NESTED_BOOTSTRAP_JARS_PATH);
if (nestedBootStrapJarsPath == null || nestedBootStrapJarsPath.isEmpty()) {
return Collections.emptyList();
}
String[] jarPaths = nestedBootStrapJarsPath.split(DELIMITER);
List<File> jarFiles = new ArrayList<>(jarPaths.length);
for (String jarPath : jarPaths) {
JarEntry jarEntry = jarFile.getJarEntry(jarPath);
if (jarEntry.getName().endsWith(JAR_SUFFIX)) {
jarFiles.add(extractNestedBootStrapJar(jarFile, jarEntry, jarEntry.getName(), file.getParentFile()));
}
}
return jarFiles;
} catch (IOException e) {
System.err.printf("extract nested bootstrap jar failed, file: %s%n", file.getAbsolutePath());
return Collections.emptyList();
}
}
private static File extractNestedBootStrapJar(JarFile file, JarEntry entry, String entryName, File parentDir) throws IOException {
String fileName = new File(entryName).getName();
File outputFile = createFile(parentDir.getAbsolutePath() + File.separator + "bootstrap" + File.separator + fileName);
try(InputStream inputStream = file.getInputStream(entry);
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
}
return outputFile;
}
private static File createFile(String path) throws IOException {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
boolean newFile = file.createNewFile();
if (newFile) {
System.out.printf("create file: %s%n", file.getAbsolutePath());
}
return file;
}
}