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 v4: |
13 | input=<directory> argument |
14 | */ |
15 | |
16 | public class x5 { |
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 | java.io.File ioBaseDir = new java.io.File("."), inputDir = null; |
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 if (arg.startsWith("input=")) |
37 | inputDir = new java.io.File(arg.substring(6)); |
38 | else |
39 | src = arg; |
40 | } |
41 | |
42 | if (inputDir != null) { |
43 | ioBaseDir = TempDirMaker_make(); |
44 | System.out.println("Taking input from: " + inputDir.getAbsolutePath()); |
45 | System.out.println("Output is in: " + new java.io.File(ioBaseDir, "output").getAbsolutePath()); |
46 | copyInput(inputDir, new java.io.File(ioBaseDir, "input")); |
47 | } |
48 | |
49 | javax4(src, ioBaseDir); |
50 | } |
51 | |
52 | public static void javax4(String src, java.io.File ioDir) throws IOException { |
53 | java.io.File srcDir; |
54 | if (isSnippetID(src)) |
55 | srcDir = loadSnippetAsMainJava(src); |
56 | else |
57 | srcDir = new java.io.File(src); |
58 | java.io.File X = programToInput(srcDir); |
59 | |
60 | if (!v2mode) { |
61 | boolean compilable = isCompilable(X); |
62 | if (verbose) System.out.println("Compilable: " + compilable); |
63 | if (!compilable) { |
64 | X = expandProgram(X); |
65 | java.io.File file = new java.io.File(X, "main.java"); |
66 | String program = loadTextFile(file.getPath(), null); |
67 | if (verbose) System.out.println("New program:\n" + program); |
68 | if (program == null) |
69 | throw new RuntimeException("Expansion failed (tried: " + file.getPath() + ")"); |
70 | } |
71 | } |
72 | |
73 | java.io.File Y = luaPrintToJavaPrint(X); |
74 | javax2(Y, ioDir, false); |
75 | } |
76 | |
77 | private static java.io.File luaPrintToJavaPrint(java.io.File x) throws IOException { |
78 | java.io.File newDir = TempDirMaker_make(); |
79 | String code = loadTextFile(new java.io.File(x, "main.java").getPath(), null); |
80 | code = luaPrintToJavaPrint(code); |
81 | if (verbose) |
82 | System.out.println(code); |
83 | saveTextFile(new java.io.File(newDir, "main.java").getPath(), code); |
84 | return newDir; |
85 | } |
86 | |
87 | public static String luaPrintToJavaPrint(String code) { |
88 | return ("\n" + code).replaceAll( |
89 | "(\n\\s*)print (\".*\")", |
90 | "$1System.out.println($2);").substring(1); |
91 | } |
92 | |
93 | public static java.io.File loadSnippetAsMainJava(String snippetID) throws IOException { |
94 | java.io.File srcDir = TempDirMaker_make(); |
95 | saveTextFile(new java.io.File(srcDir, "main.java").getPath(), loadSnippet(snippetID, false)); |
96 | return srcDir; |
97 | } |
98 | |
99 | public static java.io.File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { |
100 | java.io.File srcDir = TempDirMaker_make(); |
101 | saveTextFile(new java.io.File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); |
102 | return srcDir; |
103 | } |
104 | |
105 | private static java.io.File expandProgram(java.io.File x) throws IOException { |
106 | return runJavaX2_on_snippet(mainAdder, mainAdderHash, x, true); |
107 | } |
108 | |
109 | private static boolean isCompilable(java.io.File x) throws IOException { |
110 | java.io.File output = runJavaX2_on_snippet(isCompilable, isCompilableHash, x, true); |
111 | return hasFile(output, "is-compilable"); |
112 | } |
113 | |
114 | private static File runJavaX2_on_snippet(String snippetID, String hash, File x, boolean silent) throws IOException { |
115 | java.io.File srcDir = loadSnippetAsMainJavaVerified(snippetID, hash); |
116 | return runJavaX(srcDir, x, silent); |
117 | } |
118 | |
119 | private static File runJavaX(File originalSrcDir, File originalInput, boolean silent) throws IOException { |
120 | java.io.File ioBaseDir = TempDirMaker_make(); |
121 | java.io.File srcDir = new java.io.File(ioBaseDir, "src"); |
122 | java.io.File inputDir = new java.io.File(ioBaseDir, "input"); |
123 | File input = inputDir; |
124 | java.io.File outputDir = new java.io.File(ioBaseDir, "output"); |
125 | File output = outputDir; |
126 | copyInput(originalSrcDir, srcDir); |
127 | copyInput(originalInput, input); |
128 | javax2(srcDir, ioBaseDir, silent); |
129 | return output; |
130 | } |
131 | |
132 | private static void copyInput(File src, File dst) throws IOException { |
133 | copyDirectory(src, dst); |
134 | } |
135 | |
136 | private static File programToInput(java.io.File srcDir) { |
137 | return srcDir; |
138 | } |
139 | |
140 | public static boolean hasFile(File inputDir, String name) { |
141 | return new File(inputDir, name).exists(); |
142 | } |
143 | |
144 | public static void copyDirectory(java.io.File src, java.io.File dst) throws IOException { |
145 | if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); |
146 | dst.mkdirs(); |
147 | java.io.File[] files = src.listFiles(); |
148 | if (files == null) return; |
149 | for (java.io.File file : files) { |
150 | java.io.File dst1 = new java.io.File(dst, file.getName()); |
151 | if (file.isDirectory()) |
152 | copyDirectory(file, dst1); |
153 | else { |
154 | if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); |
155 | copy(file, dst1); |
156 | } |
157 | } |
158 | } |
159 | |
160 | /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ |
161 | public static void copy(java.io.File src, java.io.File dest) throws IOException { |
162 | FileInputStream inputStream = new FileInputStream(src); |
163 | FileOutputStream outputStream = new FileOutputStream(dest); |
164 | try { |
165 | copy(inputStream, outputStream); |
166 | inputStream.close(); |
167 | } finally { |
168 | outputStream.close(); |
169 | } |
170 | } |
171 | |
172 | public static void copy(InputStream in, OutputStream out) throws IOException { |
173 | byte[] buf = new byte[65536]; |
174 | while (true) { |
175 | int n = in.read(buf); |
176 | if (n <= 0) return; |
177 | out.write(buf, 0, n); |
178 | } |
179 | } |
180 | |
181 | /** writes safely (to temp file, then rename) */ |
182 | public static void saveTextFile(String fileName, String contents) throws IOException { |
183 | java.io.File file = new java.io.File(fileName); |
184 | java.io.File parentFile = file.getParentFile(); |
185 | if (parentFile != null) |
186 | parentFile.mkdirs(); |
187 | String tempFileName = fileName + "_temp"; |
188 | FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); |
189 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); |
190 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
191 | printWriter.print(contents); |
192 | printWriter.close(); |
193 | if (file.exists() && !file.delete()) |
194 | throw new IOException("Can't delete " + fileName); |
195 | |
196 | if (!new java.io.File(tempFileName).renameTo(file)) |
197 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
198 | } |
199 | |
200 | public static String loadTextFile(String fileName, String defaultContents) throws IOException { |
201 | if (!new java.io.File(fileName).exists()) |
202 | return defaultContents; |
203 | |
204 | FileInputStream fileInputStream = new FileInputStream(fileName); |
205 | InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); |
206 | return loadTextFile(inputStreamReader); |
207 | } |
208 | |
209 | public static String loadTextFile(Reader reader) throws IOException { |
210 | StringBuilder builder = new StringBuilder(); |
211 | try { |
212 | BufferedReader bufferedReader = new BufferedReader(reader); |
213 | String line; |
214 | while ((line = bufferedReader.readLine()) != null) |
215 | builder.append(line).append('\n'); |
216 | } finally { |
217 | reader.close(); |
218 | } |
219 | return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1); |
220 | } |
221 | |
222 | static java.io.File DiskSnippetCache_dir; |
223 | |
224 | public static void initDiskSnippetCache(java.io.File dir) { |
225 | DiskSnippetCache_dir = dir; |
226 | dir.mkdirs(); |
227 | } |
228 | |
229 | public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { |
230 | return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); |
231 | } |
232 | |
233 | private static java.io.File DiskSnippetCache_getFile(long snippetID) { |
234 | return new java.io.File(DiskSnippetCache_dir, "" + snippetID); |
235 | } |
236 | |
237 | public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { |
238 | saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); |
239 | } |
240 | |
241 | public static java.io.File DiskSnippetCache_getDir() { |
242 | return DiskSnippetCache_dir; |
243 | } |
244 | |
245 | public static void initSnippetCache() { |
246 | if (DiskSnippetCache_dir == null) |
247 | initDiskSnippetCache(new java.io.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 | initSnippetCache(); |
318 | String text = DiskSnippetCache_get(snippetID); |
319 | if (text != null) |
320 | return text; |
321 | } |
322 | |
323 | String text; |
324 | try { |
325 | URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); |
326 | text = loadPage(url); |
327 | } catch (FileNotFoundException e) { |
328 | throw new IOException("Snippet #" + snippetID + " not found or not public"); |
329 | } |
330 | |
331 | try { |
332 | initSnippetCache(); |
333 | DiskSnippetCache_put(snippetID, text); |
334 | } catch (IOException e) { |
335 | System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); |
336 | } |
337 | |
338 | return text; |
339 | } |
340 | |
341 | private static String loadPage(URL url) throws IOException { |
342 | System.out.println("Loading: " + url.toExternalForm()); |
343 | URLConnection con = url.openConnection(); |
344 | return loadPage(con, url); |
345 | } |
346 | |
347 | public static String loadPage(URLConnection con, URL url) throws IOException { |
348 | String contentType = con.getContentType(); |
349 | if (contentType == null) |
350 | throw new IOException("Page could not be read: " + url); |
351 | //Log.info("Content-Type: " + contentType); |
352 | String charset = guessCharset(contentType); |
353 | Reader r = new InputStreamReader(con.getInputStream(), charset); |
354 | StringBuilder buf = new StringBuilder(); |
355 | while (true) { |
356 | int ch = r.read(); |
357 | if (ch < 0) |
358 | break; |
359 | //Log.info("Chars read: " + buf.length()); |
360 | buf.append((char) ch); |
361 | } |
362 | return buf.toString(); |
363 | } |
364 | |
365 | public static String guessCharset(String contentType) { |
366 | Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); |
367 | Matcher m = p.matcher(contentType); |
368 | /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ |
369 | return m.matches() ? m.group(1) : "ISO-8859-1"; |
370 | } |
371 | |
372 | public static void javax2(java.io.File srcDir, java.io.File ioBaseDir, boolean silent) throws IOException { |
373 | List<java.io.File> sources = new ArrayList<java.io.File>(); |
374 | if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); |
375 | scanForSources(srcDir, sources, true); |
376 | if (sources.isEmpty()) { |
377 | System.out.println("No sources found"); |
378 | return; |
379 | } |
380 | java.io.File optionsFile = java.io.File.createTempFile("javax", ""); |
381 | java.io.File classesDir = TempDirMaker_make(); |
382 | if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); |
383 | String options = "-d " + bashQuote(classesDir.getPath()); |
384 | writeOptions(sources, optionsFile, options); |
385 | classesDir.mkdirs(); |
386 | invokeJavac(optionsFile); |
387 | if (verbose) System.out.println("Running program (class main.java)\n"); |
388 | runProgram(classesDir, ioBaseDir, silent); |
389 | } |
390 | |
391 | private static void runProgram(java.io.File classesDir, java.io.File ioBaseDir, boolean silent) throws IOException { |
392 | boolean echoOK = false; |
393 | String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " |
394 | + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; |
395 | if (verbose) System.out.println(bashCmd); |
396 | String output = backtick(bashCmd); |
397 | if (!silent) |
398 | System.out.println(output); |
399 | } |
400 | |
401 | private static void invokeJavac(java.io.File optionsFile) throws IOException { |
402 | String javacOutput = backtick("javac " + bashQuote("@" + optionsFile.getPath())); |
403 | if (verbose) System.out.println(javacOutput); |
404 | } |
405 | |
406 | private static void writeOptions(List<java.io.File> sources, java.io.File sourcesFile, String moreOptions) throws IOException { |
407 | FileWriter writer = new FileWriter(sourcesFile); |
408 | for (java.io.File source : sources) |
409 | writer.write(bashQuote(source.getPath()) + " "); |
410 | writer.write(moreOptions); |
411 | writer.close(); |
412 | } |
413 | |
414 | private static void scanForSources(java.io.File source, List<java.io.File> sources, boolean topLevel) { |
415 | if (source.isFile() && source.getName().endsWith(".java")) |
416 | sources.add(source); |
417 | else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { |
418 | java.io.File[] files = source.listFiles(); |
419 | for (java.io.File file : files) |
420 | scanForSources(file, sources, false); |
421 | } |
422 | } |
423 | |
424 | private static boolean isSkippedDirectoryName(String name, boolean topLevel) { |
425 | 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.) |
426 | return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); |
427 | } |
428 | |
429 | public static String backtick(String cmd) throws IOException { |
430 | java.io.File outFile = java.io.File.createTempFile("_backtick", ""); |
431 | java.io.File scriptFile = java.io.File.createTempFile("_backtick", ""); |
432 | |
433 | String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; |
434 | //Log.info("[Backtick] " + command); |
435 | try { |
436 | saveTextFile(scriptFile.getPath(), command); |
437 | String[] command2 = {"/bin/bash", scriptFile.getPath() }; |
438 | Process process = Runtime.getRuntime().exec(command2); |
439 | try { |
440 | process.waitFor(); |
441 | } catch (InterruptedException e) { |
442 | throw new RuntimeException(e); |
443 | } |
444 | int value = process.exitValue(); |
445 | //Log.info("exit value: " + value); |
446 | return loadTextFile(outFile.getPath(), ""); |
447 | } finally { |
448 | scriptFile.delete(); |
449 | } |
450 | } |
451 | |
452 | /** possibly improvable */ |
453 | public static String bashQuote(String text) { |
454 | if (text == null) return null; |
455 | return "\"" + text |
456 | .replace("\\", "\\\\") |
457 | .replace("\"", "\\\"") |
458 | .replace("\n", "\\n") |
459 | .replace("\r", "\\r") + "\""; |
460 | } |
461 | |
462 | public final static String charsetForTextFiles = "UTF8"; |
463 | |
464 | static long TempDirMaker_lastValue; |
465 | |
466 | public static java.io.File TempDirMaker_make() { |
467 | java.io.File dir = new java.io.File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue()); |
468 | dir.mkdirs(); |
469 | return dir; |
470 | } |
471 | |
472 | private static long TempDirMaker_newValue() { |
473 | long value; |
474 | do |
475 | value = System.currentTimeMillis(); |
476 | while (value == TempDirMaker_lastValue); |
477 | TempDirMaker_lastValue = value; |
478 | return value; |
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: | #572 |
Snippet name: | x5.java, out of date (replaced by #577) |
Eternal ID of this version: | #572/1 |
Text MD5: | a77a82680fda41c2ecdeef58868ed80e |
Author: | stefan |
Category: | |
Type: | Java source code |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-04-14 18:27:29 |
Source code size: | 18008 bytes / 480 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 761 / 212 |
Referenced in: | [show references] |