-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathCompilerUtilsIoTest.java
More file actions
246 lines (215 loc) · 11 KB
/
Copy pathCompilerUtilsIoTest.java
File metadata and controls
246 lines (215 loc) · 11 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
/*
* Copyright 2013-2026 chronicle.software; SPDX-License-Identifier: Apache-2.0
*/
package net.openhft.compiler;
import org.junit.Test;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import static org.junit.Assert.*;
public class CompilerUtilsIoTest {
@Test
public void writeTextDetectsNoChangeAndReadBytesMatches() throws Exception {
Path tempDir = Files.createTempDirectory("compiler-utils-io");
Path filePath = tempDir.resolve("sample.txt");
File file = filePath.toFile();
boolean written = CompilerUtils.writeText(file, "hello");
assertTrue("First write should report changes", written);
boolean unchanged = CompilerUtils.writeText(file, "hello");
assertTrue("Repeat write with identical content should be treated as unchanged", !unchanged);
boolean changed = CompilerUtils.writeText(file, "different");
assertTrue("Modified content should trigger a rewrite", changed);
Method readBytes = CompilerUtils.class.getDeclaredMethod("readBytes", File.class);
readBytes.setAccessible(true);
byte[] bytes = (byte[]) readBytes.invoke(null, file);
Method decodeUTF8 = CompilerUtils.class.getDeclaredMethod("decodeUTF8", byte[].class);
decodeUTF8.setAccessible(true);
String decoded = (String) decodeUTF8.invoke(null, bytes);
assertEquals("different", decoded);
}
@Test
public void writeBytesFailsWhenParentIsNotDirectory() throws Exception {
Path tempDir = Files.createTempDirectory("compiler-utils-io-error");
Path parentFile = tempDir.resolve("not-a-directory");
Files.createFile(parentFile);
File target = parentFile.resolve("child.bin").toFile();
IllegalStateException ex = assertThrows(IllegalStateException.class,
() -> CompilerUtils.writeBytes(target, new byte[]{1, 2, 3}));
assertTrue(ex.getMessage().contains("Unable to create directory"));
}
@Test
public void encodeDecodeUtf8Matches() throws Exception {
Method encode = CompilerUtils.class.getDeclaredMethod("encodeUTF8", String.class);
Method decode = CompilerUtils.class.getDeclaredMethod("decodeUTF8", byte[].class);
encode.setAccessible(true);
decode.setAccessible(true);
byte[] bytes = (byte[]) encode.invoke(null, "sample-text");
String value = (String) decode.invoke(null, bytes);
assertEquals("sample-text", value);
}
@Test
public void defineClassLoadsCompiledBytes() throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
assertNotNull("JDK compiler required for tests", compiler);
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
CachedCompiler cachedCompiler = new CachedCompiler(null, null);
MyJavaFileManager myJavaFileManager = new MyJavaFileManager(fileManager);
Map<String, byte[]> compiled = cachedCompiler.compileFromJava(
"test.DefineClassTarget",
"package test; public class DefineClassTarget { public String id() { return \"ok\"; } }",
myJavaFileManager);
byte[] bytes = compiled.get("test.DefineClassTarget");
assertNotNull(bytes);
Class<?> clazz = CompilerUtils.defineClass(Thread.currentThread().getContextClassLoader(),
"test.DefineClassTarget", bytes);
assertEquals("test.DefineClassTarget", clazz.getName());
Object instance = clazz.getDeclaredConstructor().newInstance();
String id = (String) clazz.getMethod("id").invoke(instance);
assertEquals("ok", id);
Map<String, byte[]> compiledContext = cachedCompiler.compileFromJava(
"test.DefineClassTargetContext",
"package test; public class DefineClassTargetContext { public String ctx() { return \"ctx\"; } }",
myJavaFileManager);
byte[] contextBytes = compiledContext.get("test.DefineClassTargetContext");
assertNotNull(contextBytes);
CompilerUtils.defineClass("test.DefineClassTargetContext", contextBytes);
Class<?> contextDefined = Class.forName("test.DefineClassTargetContext");
Object contextInstance = contextDefined.getDeclaredConstructor().newInstance();
String ctx = (String) contextDefined.getMethod("ctx").invoke(contextInstance);
assertEquals("ctx", ctx);
}
}
@Test
public void addClassPathHandlesMissingDirectory() {
Path nonExisting = Paths.get("not-existing-" + System.nanoTime());
boolean result = CompilerUtils.addClassPath(nonExisting.toString());
assertTrue("Missing directories should return false", !result);
}
@Test
public void addClassPathAddsExistingDirectory() throws Exception {
Path tempDir = Files.createTempDirectory("compiler-utils-classpath");
String originalClasspath = System.getProperty("java.class.path");
try {
boolean added = CompilerUtils.addClassPath(tempDir.toAbsolutePath().toString());
assertTrue("Existing directory should be added", added);
boolean second = CompilerUtils.addClassPath(tempDir.toAbsolutePath().toString());
assertTrue("Re-adding the same directory should report true because reset always occurs", second);
} finally {
System.setProperty("java.class.path", originalClasspath);
}
}
@Test
public void readTextInlineShortcutAndReadBytesMissing() throws Exception {
Method readText = CompilerUtils.class.getDeclaredMethod("readText", String.class);
readText.setAccessible(true);
String inline = (String) readText.invoke(null, "=inline");
assertEquals("inline", inline);
Method readBytes = CompilerUtils.class.getDeclaredMethod("readBytes", File.class);
readBytes.setAccessible(true);
Object missing = readBytes.invoke(null, new File("definitely-missing-" + System.nanoTime()));
assertEquals(null, missing);
Path tempFile = Files.createTempFile("compiler-utils-bytes", ".bin");
Files.write(tempFile, "bytes".getBytes(StandardCharsets.UTF_8));
byte[] present = (byte[]) readBytes.invoke(null, tempFile.toFile());
assertEquals("bytes", new String(present, StandardCharsets.UTF_8));
}
@Test
public void closeSwallowsExceptions() throws Exception {
Method closeMethod = CompilerUtils.class.getDeclaredMethod("close", Closeable.class);
closeMethod.setAccessible(true);
closeMethod.invoke(null, (Closeable) () -> {
throw new IOException("boom");
});
}
@Test
public void closeIgnoresNullReference() throws Exception {
Method closeMethod = CompilerUtils.class.getDeclaredMethod("close", Closeable.class);
closeMethod.setAccessible(true);
closeMethod.invoke(null, new Object[]{null});
}
@Test
public void getInputStreamSupportsInlineContent() throws Exception {
Method method = CompilerUtils.class.getDeclaredMethod("getInputStream", String.class);
method.setAccessible(true);
try (InputStream is = (InputStream) method.invoke(null, "=inline-data")) {
String value = new String(readFully(is));
assertEquals("inline-data", value);
}
Path tempFile = Files.createTempFile("compiler-utils-stream", ".txt");
Files.write(tempFile, "file-data".getBytes(StandardCharsets.UTF_8));
try (InputStream is = (InputStream) method.invoke(null, tempFile.toString())) {
String value = new String(readFully(is));
assertEquals("file-data", value);
}
}
@Test
public void getInputStreamRejectsEmptyFilename() throws Exception {
Method method = CompilerUtils.class.getDeclaredMethod("getInputStream", String.class);
method.setAccessible(true);
InvocationTargetException ex = assertThrows(InvocationTargetException.class,
() -> method.invoke(null, ""));
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
@Test
public void getInputStreamUsesSlashFallback() throws Exception {
Method method = CompilerUtils.class.getDeclaredMethod("getInputStream", String.class);
method.setAccessible(true);
ClassLoader original = Thread.currentThread().getContextClassLoader();
ClassLoader loader = new ClassLoader(original) {
@Override
public InputStream getResourceAsStream(String name) {
if ("/fallback-resource".equals(name)) {
return new ByteArrayInputStream("fallback".getBytes(StandardCharsets.UTF_8));
}
return null;
}
};
Thread.currentThread().setContextClassLoader(loader);
try (InputStream is = (InputStream) method.invoke(null, "fallback-resource")) {
assertEquals("fallback", new String(readFully(is), StandardCharsets.UTF_8));
} finally {
Thread.currentThread().setContextClassLoader(original);
}
}
@Test
public void sanitizePathPreventsTraversal() {
assertThrows(IllegalArgumentException.class,
() -> CompilerUtils.sanitizePath(Paths.get("..", "escape")));
}
@Test
public void writeBytesCreatesMissingParentDirectories() throws Exception {
Path tempDir = Files.createTempDirectory("compiler-utils-parent");
Path nested = tempDir.resolve("nested").resolve("file.bin");
boolean changed = CompilerUtils.writeBytes(nested.toFile(), new byte[]{10, 20, 30});
assertTrue("Path with missing parents should be created", changed);
assertTrue(Files.exists(nested));
}
@Test
public void readBytesRejectsDirectories() throws Exception {
Method readBytes = CompilerUtils.class.getDeclaredMethod("readBytes", File.class);
readBytes.setAccessible(true);
Path tempDir = Files.createTempDirectory("compiler-utils-dir");
InvocationTargetException ex = assertThrows(InvocationTargetException.class,
() -> readBytes.invoke(null, tempDir.toFile()));
assertTrue(ex.getCause() instanceof IllegalStateException);
String message = ex.getCause().getMessage();
assertTrue(message.contains("Unable to determine size") || message.contains("Unable to read file"));
}
private static byte[] readFully(InputStream inputStream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] chunk = new byte[1024];
int read;
while ((read = inputStream.read(chunk)) != -1) {
buffer.write(chunk, 0, read);
}
return buffer.toByteArray();
}
}