1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.bcel.util;
20
21 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
22 import static org.junit.jupiter.api.Assertions.assertNotNull;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.util.zip.ZipEntry;
31 import java.util.zip.ZipOutputStream;
32
33 import org.apache.bcel.AbstractTest;
34 import org.junit.jupiter.api.Test;
35 import org.junit.jupiter.api.io.TempDir;
36
37 class ClassPathTest extends AbstractTest {
38
39 private static int lastIndexOf(final byte[] haystack, final byte[] needle) {
40 outer: for (int i = haystack.length - needle.length; i >= 0; i--) {
41 for (int j = 0; j < needle.length; j++) {
42 if (haystack[i + j] != needle[j]) {
43 continue outer;
44 }
45 }
46 return i;
47 }
48 return -1;
49 }
50
51 private static void writeLittleEndianInt(final byte[] bytes, final int offset, final int value) {
52 bytes[offset] = (byte) value;
53 bytes[offset + 1] = (byte) (value >>> 8);
54 bytes[offset + 2] = (byte) (value >>> 16);
55 bytes[offset + 3] = (byte) (value >>> 24);
56 }
57
58 @Test
59 void testClose() throws IOException {
60 try (ClassPath cp = new ClassPath(ClassPath.getClassPath())) {
61 assertNotNull(cp);
62 }
63 }
64
65
66
67
68
69
70 @Test
71 void testGetBytesIgnoresForgedUncompressedSize(@TempDir final Path tempDir) throws IOException {
72 final byte[] content = new byte[256];
73 for (int i = 0; i < content.length; i++) {
74 content[i] = (byte) i;
75 }
76 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
77 try (ZipOutputStream zos = new ZipOutputStream(baos)) {
78 zos.putNextEntry(new ZipEntry("Foo.class"));
79 zos.write(content);
80 zos.closeEntry();
81 }
82 final byte[] jar = baos.toByteArray();
83
84
85 final int cen = lastIndexOf(jar, new byte[] { 0x50, 0x4B, 0x01, 0x02 });
86 assertTrue(cen >= 0);
87 writeLittleEndianInt(jar, cen + 24, 64 * 1024 * 1024);
88 final Path jarFile = tempDir.resolve("forged.jar");
89 Files.write(jarFile, jar);
90 try (ClassPath classPath = new ClassPath(jarFile.toString())) {
91 assertArrayEquals(content, classPath.getBytes("Foo"));
92 }
93 }
94
95 @Test
96 void testGetClassFile() throws IOException {
97 assertNotNull(ClassPath.SYSTEM_CLASS_PATH.getClassFile("java.lang.String"));
98 }
99
100 @Test
101 void testGetResource() {
102 assertNotNull(ClassPath.SYSTEM_CLASS_PATH.getResource("java/lang/String.class"));
103 }
104
105 @Test
106 void testGetResourceAsStream() throws IOException {
107 try (InputStream inputStream = ClassPath.SYSTEM_CLASS_PATH.getResourceAsStream("java/lang/String.class")) {
108 assertNotNull(inputStream);
109 }
110 }
111
112 @Test
113 void testGetResources() {
114 assertTrue(ClassPath.SYSTEM_CLASS_PATH.getResources("java/lang/String.class").hasMoreElements());
115 }
116 }