|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +package org.apache.tika.metadata.schema; |
| 18 | + |
| 19 | +import java.io.File; |
| 20 | +import java.io.IOException; |
| 21 | +import java.lang.reflect.Field; |
| 22 | +import java.nio.charset.StandardCharsets; |
| 23 | +import java.nio.file.Files; |
| 24 | +import java.nio.file.Path; |
| 25 | +import java.util.Enumeration; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.TreeMap; |
| 28 | +import java.util.jar.JarEntry; |
| 29 | +import java.util.jar.JarFile; |
| 30 | + |
| 31 | +import org.apache.tika.digest.DigestDef; |
| 32 | +import org.apache.tika.metadata.Property; |
| 33 | + |
| 34 | +/** |
| 35 | + * Generates the machine-readable metadata key registry ({@code metadata-keys.json}) from the live |
| 36 | + * {@link Property} declarations. Dependency-free: it scans the runtime classpath for classes that |
| 37 | + * declare a {@code Property} field, force-loads them (their static init registers into the global |
| 38 | + * {@code Property} table), then serializes that table as stable, sorted JSON. |
| 39 | + * |
| 40 | + * <p>The generated file is committed; {@code MetadataSchemaTest} regenerates and asserts no diff, |
| 41 | + * so the registry can never drift from the declarations. |
| 42 | + */ |
| 43 | +public final class SchemaGenerator { |
| 44 | + |
| 45 | + // Field/parameter descriptor for org.apache.tika.metadata.Property in a .class constant pool. |
| 46 | + private static final byte[] PROP_DESC = |
| 47 | + "Lorg/apache/tika/metadata/Property;".getBytes(StandardCharsets.ISO_8859_1); |
| 48 | + |
| 49 | + private SchemaGenerator() { |
| 50 | + } |
| 51 | + |
| 52 | + /** @return the registry as stable JSON (sorted by key). */ |
| 53 | + public static String generate() throws Exception { |
| 54 | + ClassLoader cl = SchemaGenerator.class.getClassLoader(); |
| 55 | + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { |
| 56 | + File f = new File(entry); |
| 57 | + if (f.isDirectory()) { |
| 58 | + scanDir(f, f.toPath(), cl); |
| 59 | + } else if (f.getName().endsWith(".jar")) { |
| 60 | + scanJar(f, cl); |
| 61 | + } |
| 62 | + } |
| 63 | + Field fld = Property.class.getDeclaredField("PROPERTIES"); |
| 64 | + fld.setAccessible(true); |
| 65 | + @SuppressWarnings("unchecked") |
| 66 | + Map<String, Property> reg = (Map<String, Property>) fld.get(null); |
| 67 | + |
| 68 | + TreeMap<String, String[]> entries = new TreeMap<>(); // key -> [valueType, cardinality] |
| 69 | + for (Map.Entry<String, Property> e : reg.entrySet()) { |
| 70 | + entries.put(e.getKey(), new String[]{ |
| 71 | + e.getValue().getValueType().toString(), e.getValue().getPropertyType().toString()}); |
| 72 | + } |
| 73 | + // Digest keys are a CLOSED cross-product of the supported algorithms and encodings, not an |
| 74 | + // open template. Synthesize them via the real DigestDef.metadataKey() so they can't drift. |
| 75 | + for (DigestDef.Algorithm a : DigestDef.Algorithm.values()) { |
| 76 | + for (DigestDef.Encoding enc : DigestDef.Encoding.values()) { |
| 77 | + entries.put(new DigestDef(a, enc).metadataKey(), new String[]{"TEXT", "SIMPLE"}); |
| 78 | + } |
| 79 | + } |
| 80 | + return toJson(entries); |
| 81 | + } |
| 82 | + |
| 83 | + private static void scanDir(File root, Path dir, ClassLoader cl) throws IOException { |
| 84 | + try (var stream = Files.walk(dir)) { |
| 85 | + for (Path p : (Iterable<Path>) stream::iterator) { |
| 86 | + if (!p.toString().endsWith(".class")) { |
| 87 | + continue; |
| 88 | + } |
| 89 | + String rel = root.toPath().relativize(p).toString().replace(File.separatorChar, '/'); |
| 90 | + maybeLoad(rel, Files.readAllBytes(p), cl); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private static void scanJar(File jar, ClassLoader cl) throws IOException { |
| 96 | + try (JarFile jf = new JarFile(jar)) { |
| 97 | + for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements(); ) { |
| 98 | + JarEntry je = e.nextElement(); |
| 99 | + if (!je.getName().endsWith(".class")) { |
| 100 | + continue; |
| 101 | + } |
| 102 | + maybeLoad(je.getName(), jf.getInputStream(je).readAllBytes(), cl); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + private static void maybeLoad(String classPath, byte[] bytes, ClassLoader cl) { |
| 108 | + if (!classPath.startsWith("org/apache/tika/") || !contains(bytes, PROP_DESC)) { |
| 109 | + return; |
| 110 | + } |
| 111 | + String cn = classPath.substring(0, classPath.length() - 6).replace('/', '.'); |
| 112 | + try { |
| 113 | + Class.forName(cn, true, cl); // static init registers any Property constants |
| 114 | + } catch (Throwable ignore) { |
| 115 | + // classes whose static init needs an absent dependency are skipped; the corpus test backs this |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + private static boolean contains(byte[] hay, byte[] needle) { |
| 120 | + outer: |
| 121 | + for (int i = 0; i <= hay.length - needle.length; i++) { |
| 122 | + for (int j = 0; j < needle.length; j++) { |
| 123 | + if (hay[i + j] != needle[j]) { |
| 124 | + continue outer; |
| 125 | + } |
| 126 | + } |
| 127 | + return true; |
| 128 | + } |
| 129 | + return false; |
| 130 | + } |
| 131 | + |
| 132 | + private static String toJson(TreeMap<String, String[]> entries) { |
| 133 | + StringBuilder sb = new StringBuilder("[\n"); |
| 134 | + int i = 0; |
| 135 | + int n = entries.size(); |
| 136 | + for (Map.Entry<String, String[]> e : entries.entrySet()) { |
| 137 | + String k = e.getKey(); |
| 138 | + String ns = k.contains(":") ? k.substring(0, k.indexOf(':')) : ""; |
| 139 | + sb.append(" {\"key\":").append(quote(k)) |
| 140 | + .append(",\"namespace\":").append(quote(ns)) |
| 141 | + .append(",\"valueType\":\"").append(e.getValue()[0]) |
| 142 | + .append("\",\"cardinality\":\"").append(e.getValue()[1]) |
| 143 | + .append("\"}").append(++i < n ? "," : "").append('\n'); |
| 144 | + } |
| 145 | + return sb.append("]\n").toString(); |
| 146 | + } |
| 147 | + |
| 148 | + private static String quote(String s) { |
| 149 | + return '"' + s.replace("\\", "\\\\").replace("\"", "\\\"") + '"'; |
| 150 | + } |
| 151 | + |
| 152 | + public static void main(String[] args) throws Exception { |
| 153 | + Path out = Path.of(args[0]); |
| 154 | + Files.writeString(out, generate()); |
| 155 | + System.out.println("wrote " + out); |
| 156 | + } |
| 157 | +} |
0 commit comments