1 | import java.io.*; |
2 | import java.net.URL; |
3 | import java.net.URLConnection; |
4 | import java.security.MessageDigest; |
5 | import java.security.NoSuchAlgorithmException; |
6 | import java.util.ArrayList; |
7 | import java.util.List; |
8 | import java.util.regex.Matcher; |
9 | import java.util.regex.Pattern; |
10 | |
11 | /** |
12 | Changes to v3: |
13 | Includes "Lua print to Java print" |
14 | */ |
15 | |
16 | public class javax4 { |
17 | static boolean verbose = false; |
18 | static boolean v2mode = false; |
19 | |
20 | private static String isCompilable = "http://tinybrain.de/" |
21 | + /*"564"*/"1000251"; // silenced version (but I think we're silencing now anyway) |
22 | private static String isCompilableHash = "8fe3851d7a686b60546a2429a2bde0d9"; |
23 | |
24 | private static String mainAdder = "http://tinybrain.de/1000252"; |
25 | private static String mainAdderHash = "ce1e89785facd87ea64a6d9ad16a7aec"; |
26 | |
27 | public static void main(String[] args) throws IOException { |
28 | File ioBaseDir = new File("."); |
29 | String src = "."; |
30 | for (int i = 0; i < args.length; i++) { |
31 | String arg = args[i]; |
32 | if (arg.equals("-v")) |
33 | verbose = true; |
34 | else if (arg.equals("-v2")) |
35 | v2mode = true; |
36 | else |
37 | src = arg; |
38 | } |
39 | |
40 | javax4(src, ioBaseDir); |
41 | } |
42 | |
43 | public static void javax4(String src, File ioDir) throws IOException { |
44 | File srcDir; |
45 | if (isSnippetID(src)) |
46 | srcDir = loadSnippetAsMainJava(src); |
47 | else |
48 | srcDir = new File(src); |
49 | Input X = programToInput(srcDir); |
50 | |
51 | if (!v2mode) { |
52 | boolean compilable = isCompilable(X); |
53 | if (verbose) System.out.println("Compilable: " + compilable); |
54 | if (!compilable) { |
55 | X = expandProgram(X); |
56 | File file = new File(X.dir, "main.java"); |
57 | String program = loadTextFile(file.getPath(), null); |
58 | if (verbose) System.out.println("New program:\n" + program); |
59 | if (program == null) |
60 | throw new RuntimeException("Expansion failed (tried: " + file.getPath() + ")"); |
61 | } |
62 | } |
63 | |
64 | Input Y = luaPrintToJavaPrint(X); |
65 | javax2(Y.dir, ioDir, false); |
66 | } |
67 | |
68 | private static Input luaPrintToJavaPrint(Input x) throws IOException { |
69 | File newDir = TempDirMaker.make(); |
70 | String code = loadTextFile(new File(x.dir, "main.java").getPath(), null); |
71 | code = luaPrintToJavaPrint(code); |
72 | if (verbose) |
73 | System.out.println(code); |
74 | saveTextFile(new File(newDir, "main.java").getPath(), code); |
75 | return new Input(newDir); |
76 | } |
77 | |
78 | public static String luaPrintToJavaPrint(String code) { |
79 | return ("\n" + code).replaceAll( |
80 | "(\n\\s*)print (\".*\")", |
81 | "$1System.out.println($2);").substring(1); |
82 | } |
83 | |
84 | public static File loadSnippetAsMainJava(String snippetID) throws IOException { |
85 | File srcDir = TempDirMaker.make(); |
86 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID, false)); |
87 | return srcDir; |
88 | } |
89 | |
90 | public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { |
91 | File srcDir = TempDirMaker.make(); |
92 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); |
93 | return srcDir; |
94 | } |
95 | |
96 | private static Input expandProgram(Input x) throws IOException { |
97 | return runJavaX2_on_snippet(mainAdder, mainAdderHash, x, true); |
98 | } |
99 | |
100 | private static boolean isCompilable(Input x) throws IOException { |
101 | Input output = runJavaX2_on_snippet(isCompilable, isCompilableHash, x, true); |
102 | return output.hasFile("is-compilable"); |
103 | } |
104 | |
105 | private static Input runJavaX2_on_snippet(String snippetID, String hash, Input x, boolean silent) throws IOException { |
106 | File srcDir = loadSnippetAsMainJavaVerified(snippetID, hash); |
107 | return runJavaX(new Input(srcDir), x, silent); |
108 | } |
109 | |
110 | private static Input runJavaX(Input originalSrcDir, Input originalInput, boolean silent) throws IOException { |
111 | File ioBaseDir = TempDirMaker.make(); |
112 | File srcDir = new File(ioBaseDir, "src"); |
113 | File inputDir = new File(ioBaseDir, "input"); |
114 | Input input = new Input(inputDir); |
115 | File outputDir = new File(ioBaseDir, "output"); |
116 | Input output = new Input(outputDir); |
117 | copyInput(originalSrcDir, new Input(srcDir)); |
118 | copyInput(originalInput, input); |
119 | javax2(srcDir, ioBaseDir, silent); |
120 | return output; |
121 | } |
122 | |
123 | private static void copyInput(Input src, Input dst) throws IOException { |
124 | copyDirectory(src.dir, dst.dir); |
125 | } |
126 | |
127 | private static Input programToInput(File srcDir) { |
128 | return new Input(srcDir); |
129 | } |
130 | |
131 | static class Input { |
132 | File dir; |
133 | |
134 | public Input(File dir) { |
135 | this.dir = dir; |
136 | } |
137 | |
138 | public boolean hasFile(String name) { |
139 | return new File(dir, name).exists(); |
140 | } |
141 | } |
142 | |
143 | public static void copyDirectory(File src, File dst) throws IOException { |
144 | if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); |
145 | dst.mkdirs(); |
146 | File[] files = src.listFiles(); |
147 | if (files == null) return; |
148 | for (File file : files) { |
149 | File dst1 = new File(dst, file.getName()); |
150 | if (file.isDirectory()) |
151 | copyDirectory(file, dst1); |
152 | else { |
153 | if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); |
154 | copy(file, dst1); |
155 | } |
156 | } |
157 | } |
158 | |
159 | /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ |
160 | public static void copy(File src, File dest) throws IOException { |
161 | FileInputStream inputStream = new FileInputStream(src); |
162 | FileOutputStream outputStream = new FileOutputStream(dest); |
163 | try { |
164 | copy(inputStream, outputStream); |
165 | inputStream.close(); |
166 | } finally { |
167 | outputStream.close(); |
168 | } |
169 | } |
170 | |
171 | public static void copy(InputStream in, OutputStream out) throws IOException { |
172 | byte[] buf = new byte[65536]; |
173 | while (true) { |
174 | int n = in.read(buf); |
175 | if (n <= 0) return; |
176 | out.write(buf, 0, n); |
177 | } |
178 | } |
179 | |
180 | /** writes safely (to temp file, then rename) */ |
181 | public static void saveTextFile(String fileName, String contents) throws IOException { |
182 | File file = new File(fileName); |
183 | File parentFile = file.getParentFile(); |
184 | if (parentFile != null) |
185 | parentFile.mkdirs(); |
186 | String tempFileName = fileName + "_temp"; |
187 | FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); |
188 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); |
189 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
190 | printWriter.print(contents); |
191 | printWriter.close(); |
192 | if (file.exists() && !file.delete()) |
193 | throw new IOException("Can't delete " + fileName); |
194 | |
195 | if (!new File(tempFileName).renameTo(file)) |
196 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
197 | } |
198 | |
199 | public static String loadTextFile(String fileName, String defaultContents) throws IOException { |
200 | if (!new File(fileName).exists()) |
201 | return defaultContents; |
202 | |
203 | FileInputStream fileInputStream = new FileInputStream(fileName); |
204 | InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); |
205 | return loadTextFile(inputStreamReader); |
206 | } |
207 | |
208 | public static String loadTextFile(Reader reader) throws IOException { |
209 | StringBuilder builder = new StringBuilder(); |
210 | try { |
211 | BufferedReader bufferedReader = new BufferedReader(reader); |
212 | String line; |
213 | while ((line = bufferedReader.readLine()) != null) |
214 | builder.append(line).append('\n'); |
215 | } finally { |
216 | reader.close(); |
217 | } |
218 | return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1); |
219 | } |
220 | |
221 | static class DiskSnippetCache { |
222 | final File dir; |
223 | |
224 | public DiskSnippetCache(File dir) { |
225 | this.dir = dir; |
226 | dir.mkdirs(); |
227 | } |
228 | |
229 | public synchronized String get(long snippetID) throws IOException { |
230 | return loadTextFile(getFile(snippetID).getPath(), null); |
231 | } |
232 | |
233 | private File getFile(long snippetID) { |
234 | return new File(dir, "" + snippetID); |
235 | } |
236 | |
237 | public synchronized void put(long snippetID, String snippet) throws IOException { |
238 | saveTextFile(getFile(snippetID).getPath(), snippet); |
239 | } |
240 | |
241 | public File getDir() { |
242 | return dir; |
243 | } |
244 | } |
245 | |
246 | public static DiskSnippetCache getSnippetCache() { |
247 | return new DiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache")); |
248 | } |
249 | |
250 | public static String loadSnippetVerified(String snippetID, String hash) throws IOException { |
251 | String text = loadSnippet(snippetID, !hash.isEmpty()); |
252 | String realHash = getHash(text.getBytes("UTF-8")); |
253 | if (!realHash.equals(hash)) { |
254 | String msg; |
255 | if (hash.isEmpty()) |
256 | msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash; |
257 | else |
258 | msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??"; |
259 | throw new RuntimeException(msg); |
260 | } |
261 | return text; |
262 | } |
263 | |
264 | public static String getHash(byte[] data) { |
265 | return bytesToHex(getFullFingerprint(data)); |
266 | } |
267 | |
268 | public static byte[] getFullFingerprint(byte[] data) { |
269 | try { |
270 | return MessageDigest.getInstance("MD5").digest(data); |
271 | } catch (NoSuchAlgorithmException e) { |
272 | throw new RuntimeException(e); |
273 | } |
274 | } |
275 | |
276 | public static String bytesToHex(byte[] bytes) { |
277 | return bytesToHex(bytes, 0, bytes.length); |
278 | } |
279 | |
280 | public static String bytesToHex(byte[] bytes, int ofs, int len) { |
281 | StringBuilder stringBuilder = new StringBuilder(len*2); |
282 | for (int i = 0; i < len; i++) { |
283 | String s = "0" + Integer.toHexString(bytes[ofs+i]); |
284 | stringBuilder.append(s.substring(s.length()-2, s.length())); |
285 | } |
286 | return stringBuilder.toString(); |
287 | } |
288 | |
289 | public static String loadSnippet(String snippetID, boolean preferCached) throws IOException { |
290 | return loadSnippet(parseSnippetID(snippetID), preferCached); |
291 | } |
292 | |
293 | public static long parseSnippetID(String snippetID) { |
294 | return Long.parseLong(shortenSnippetID(snippetID)); |
295 | } |
296 | |
297 | private static String shortenSnippetID(String snippetID) { |
298 | if (snippetID.startsWith("#")) |
299 | snippetID = snippetID.substring(1); |
300 | String httpBlaBla = "http://tinybrain.de/"; |
301 | if (snippetID.startsWith(httpBlaBla)) |
302 | snippetID = snippetID.substring(httpBlaBla.length()); |
303 | return snippetID; |
304 | } |
305 | |
306 | public static boolean isSnippetID(String snippetID) { |
307 | snippetID = shortenSnippetID(snippetID); |
308 | return isInteger(snippetID) && Long.parseLong(snippetID) != 0; |
309 | } |
310 | |
311 | public static boolean isInteger(String s) { |
312 | return Pattern.matches("\\-?\\d+", s); |
313 | } |
314 | |
315 | public static String loadSnippet(long snippetID, boolean preferCached) throws IOException { |
316 | if (preferCached) { |
317 | String text = getSnippetCache().get(snippetID); |
318 | if (text != null) |
319 | return text; |
320 | } |
321 | |
322 | String text; |
323 | try { |
324 | URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); |
325 | text = loadPage(url); |
326 | } catch (FileNotFoundException e) { |
327 | throw new IOException("Snippet #" + snippetID + " not found or not public"); |
328 | } |
329 | |
330 | try { |
331 | getSnippetCache().put(snippetID, text); |
332 | } catch (IOException e) { |
333 | System.err.println("Minor warning: Couldn't save snippet to cache (" + getSnippetCache().getDir() + ")"); |
334 | } |
335 | |
336 | return text; |
337 | } |
338 | |
339 | private static String loadPage(URL url) throws IOException { |
340 | System.out.println("Loading: " + url.toExternalForm()); |
341 | URLConnection con = url.openConnection(); |
342 | return loadPage(con, url); |
343 | } |
344 | |
345 | public static String loadPage(URLConnection con, URL url) throws IOException { |
346 | String contentType = con.getContentType(); |
347 | if (contentType == null) |
348 | throw new IOException("Page could not be read: " + url); |
349 | //Log.info("Content-Type: " + contentType); |
350 | String charset = guessCharset(contentType); |
351 | Reader r = new InputStreamReader(con.getInputStream(), charset); |
352 | StringBuilder buf = new StringBuilder(); |
353 | while (true) { |
354 | int ch = r.read(); |
355 | if (ch < 0) |
356 | break; |
357 | //Log.info("Chars read: " + buf.length()); |
358 | buf.append((char) ch); |
359 | } |
360 | return buf.toString(); |
361 | } |
362 | |
363 | public static String guessCharset(String contentType) { |
364 | Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); |
365 | Matcher m = p.matcher(contentType); |
366 | /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ |
367 | return m.matches() ? m.group(1) : "ISO-8859-1"; |
368 | } |
369 | |
370 | public static void javax2(File srcDir, File ioBaseDir, boolean silent) throws IOException { |
371 | List<File> sources = new ArrayList<File>(); |
372 | if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); |
373 | scanForSources(srcDir, sources, true); |
374 | if (sources.isEmpty()) { |
375 | System.out.println("No sources found"); |
376 | return; |
377 | } |
378 | File optionsFile = File.createTempFile("javax", ""); |
379 | File classesDir = TempDirMaker.make(); |
380 | if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); |
381 | String options = "-d " + bashQuote(classesDir.getPath()); |
382 | writeOptions(sources, optionsFile, options); |
383 | classesDir.mkdirs(); |
384 | invokeJavac(optionsFile); |
385 | if (verbose) System.out.println("Running program (class main.java)\n"); |
386 | runProgram(classesDir, ioBaseDir, silent); |
387 | } |
388 | |
389 | private static void runProgram(File classesDir, File ioBaseDir, boolean silent) throws IOException { |
390 | boolean echoOK = false; |
391 | String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " |
392 | + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; |
393 | if (verbose) System.out.println(bashCmd); |
394 | String output = backtick(bashCmd); |
395 | if (!silent) |
396 | System.out.println(output); |
397 | } |
398 | |
399 | private static void invokeJavac(File optionsFile) throws IOException { |
400 | String javacOutput = backtick("javac " + bashQuote("@" + optionsFile.getPath())); |
401 | if (verbose) System.out.println(javacOutput); |
402 | } |
403 | |
404 | private static void writeOptions(List<File> sources, File sourcesFile, String moreOptions) throws IOException { |
405 | FileWriter writer = new FileWriter(sourcesFile); |
406 | for (File source : sources) |
407 | writer.write(bashQuote(source.getPath()) + " "); |
408 | writer.write(moreOptions); |
409 | writer.close(); |
410 | } |
411 | |
412 | private static void scanForSources(File source, List<File> sources, boolean topLevel) { |
413 | if (source.isFile() && source.getName().endsWith(".java")) |
414 | sources.add(source); |
415 | else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { |
416 | File[] files = source.listFiles(); |
417 | for (File file : files) |
418 | scanForSources(file, sources, false); |
419 | } |
420 | } |
421 | |
422 | private static boolean isSkippedDirectoryName(String name, boolean topLevel) { |
423 | if (topLevel) return false; // input or output ok as highest directory (intentionally specified by user, not just found by a directory scan in which case we probably don't want it. it's more like heuristics actually.) |
424 | return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); |
425 | } |
426 | |
427 | public static String backtick(String cmd) throws IOException { |
428 | File outFile = File.createTempFile("_backtick", ""); |
429 | File scriptFile = File.createTempFile("_backtick", ""); |
430 | |
431 | String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; |
432 | //Log.info("[Backtick] " + command); |
433 | try { |
434 | saveTextFile(scriptFile.getPath(), command); |
435 | String[] command2 = {"/bin/bash", scriptFile.getPath() }; |
436 | Process process = Runtime.getRuntime().exec(command2); |
437 | try { |
438 | process.waitFor(); |
439 | } catch (InterruptedException e) { |
440 | throw new RuntimeException(e); |
441 | } |
442 | int value = process.exitValue(); |
443 | //Log.info("exit value: " + value); |
444 | return loadTextFile(outFile.getPath(), ""); |
445 | } finally { |
446 | scriptFile.delete(); |
447 | } |
448 | } |
449 | |
450 | /** possibly improvable */ |
451 | public static String bashQuote(String text) { |
452 | if (text == null) return null; |
453 | return "\"" + text |
454 | .replace("\\", "\\\\") |
455 | .replace("\"", "\\\"") |
456 | .replace("\n", "\\n") |
457 | .replace("\r", "\\r") + "\""; |
458 | } |
459 | |
460 | public final static String charsetForTextFiles = "UTF8"; |
461 | |
462 | public static class TempDirMaker { |
463 | static long lastValue; |
464 | |
465 | public static File make() { |
466 | File dir = new File(System.getProperty("user.home"), ".javax/" + newValue()); |
467 | dir.mkdirs(); |
468 | return dir; |
469 | } |
470 | |
471 | private static long newValue() { |
472 | long value; |
473 | do |
474 | value = System.currentTimeMillis(); |
475 | while (value == lastValue); |
476 | lastValue = value; |
477 | return value; |
478 | } |
479 | } |
480 | } |
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #568 |
Snippet name: | javax4.java |
Eternal ID of this version: | #568/1 |
Text MD5: | 31ec81baa7ad22797c2e74a38f9b8ebf |
Author: | stefan |
Category: | |
Type: | Java source code |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-04-11 05:41:31 |
Source code size: | 16942 bytes / 480 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 765 / 210 |
Referenced in: | [show references] |