1 | import java.io.*; |
2 | import java.lang.reflect.Method; |
3 | import java.net.URL; |
4 | import java.net.URLClassLoader; |
5 | import java.net.URLConnection; |
6 | import java.security.MessageDigest; |
7 | import java.security.NoSuchAlgorithmException; |
8 | import java.util.*; |
9 | import java.util.regex.Matcher; |
10 | import java.util.regex.Pattern; |
11 | |
12 | /** |
13 | JavaX runner version 11. |
14 | |
15 | Changes to v10: |
16 | -can load libraries :) |
17 | [Just upload them via http://tinybrain.de:8080/tb/upload-data.php and include in source as "!12345", |
18 | like a translator.] |
19 | |
20 | Still Linux only. (Where are the Windows porters?) |
21 | */ |
22 | |
23 | public class x11 { |
24 | static final String version = "JavaX 11"; |
25 | |
26 | static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true; |
27 | static boolean preferCached = false; |
28 | static List<String> mainTranslators = new ArrayList<String>(); |
29 | private static Map<Long, String> memSnippetCache = new HashMap<Long, String>(); |
30 | private static int processesStarted; |
31 | |
32 | public static void main(String[] args) throws Exception { |
33 | File ioBaseDir = new File("."), inputDir = null, outputDir = null; |
34 | String src = "."; |
35 | for (int i = 0; i < args.length; i++) { |
36 | String arg = args[i]; |
37 | if (arg.equals("-v") || arg.equals("-verbose")) |
38 | verbose = true; |
39 | else if (arg.equals("-finderror")) |
40 | verbose = true; |
41 | else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached")) |
42 | preferCached = true; |
43 | else if (arg.equals("-novirt")) |
44 | virtualizeTranslators = false; |
45 | else if (arg.equals("translate")) |
46 | translate = true; |
47 | else if (arg.equals("list")) |
48 | list = true; |
49 | else if (arg.equals("run")) { |
50 | // it's the default command anyway |
51 | } else if (arg.startsWith("input=")) |
52 | inputDir = new File(arg.substring(6)); |
53 | else if (arg.startsWith("output=")) |
54 | outputDir = new File(arg.substring(7)); |
55 | else if (arg.equals("with")) |
56 | mainTranslators.add(args[++i]); |
57 | else |
58 | src = arg; |
59 | } |
60 | |
61 | if (virtualizeTranslators && !preferCached) |
62 | initDiskSnippetCache(TempDirMaker_make()); |
63 | |
64 | if (inputDir != null) { |
65 | ioBaseDir = TempDirMaker_make(); |
66 | System.out.println("Taking input from: " + inputDir.getAbsolutePath()); |
67 | System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath()); |
68 | copyInput(inputDir, new File(ioBaseDir, "input")); |
69 | } |
70 | |
71 | javax4(src, ioBaseDir, translate, list); |
72 | |
73 | if (outputDir != null) { |
74 | copyInput(new File(ioBaseDir, "output"), outputDir); |
75 | System.out.println("Output copied to: " + outputDir.getAbsolutePath()); |
76 | } |
77 | |
78 | if (verbose) |
79 | System.out.println("Processes started: " + processesStarted); |
80 | } |
81 | |
82 | public static void javax4(String src, File ioDir, boolean translate, boolean list) throws Exception { |
83 | File srcDir; |
84 | if (isSnippetID(src)) |
85 | srcDir = loadSnippetAsMainJava(src); |
86 | else { |
87 | srcDir = new File(src); |
88 | if (!new File(srcDir, "main.java").exists()) { |
89 | System.out.println("This is " + version + ".\n" + |
90 | "No main.java found, exiting"); |
91 | return; |
92 | } |
93 | } |
94 | |
95 | // translate |
96 | |
97 | List<File> libraries = new ArrayList<File>(); |
98 | File X = srcDir; |
99 | X = applyTranslators(X, mainTranslators, libraries); |
100 | X = defaultTranslate(X, libraries); |
101 | |
102 | // list or run |
103 | |
104 | if (translate) |
105 | System.out.println("Program translated to: " + X.getAbsolutePath()); |
106 | else if (list) |
107 | System.out.println(loadTextFile(new File(X, "main.java").getPath(), null)); |
108 | else |
109 | javax2(X, ioDir, false, false, libraries); |
110 | } |
111 | |
112 | private static File defaultTranslate(File x, List<File> libraries_out) throws Exception { |
113 | x = luaPrintToJavaPrint(x); |
114 | x = autoTranslate(x, libraries_out); |
115 | return x; |
116 | } |
117 | |
118 | private static File autoTranslate(File x, List<File> libraries_out) throws Exception { |
119 | String main = loadTextFile(new File(x, "main.java").getPath(), null); |
120 | List<String> lines = toLines(main); |
121 | List<String> translators = findTranslators(lines); |
122 | if (translators.isEmpty()) |
123 | return x; |
124 | |
125 | main = fromLines(lines); |
126 | File newDir = TempDirMaker_make(); |
127 | saveTextFile(new File(newDir, "main.java").getPath(), main); |
128 | return applyTranslators(newDir, translators, libraries_out); |
129 | } |
130 | |
131 | private static List<String> findTranslators(List<String> lines) { |
132 | List<String> translators = new ArrayList<String>(); |
133 | Pattern pattern = Pattern.compile("^!([0-9# \t]+)"); |
134 | for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) { |
135 | String line = iterator.next(); |
136 | line = line.trim(); |
137 | Matcher matcher = pattern.matcher(line); |
138 | if (matcher.find()) { |
139 | translators.addAll(Arrays.asList(matcher.group(1).split("[ \t]+"))); |
140 | iterator.remove(); |
141 | } |
142 | } |
143 | return translators; |
144 | } |
145 | |
146 | public static List<String> toLines(String s) { |
147 | List<String> lines = new ArrayList<String>(); |
148 | int start = 0; |
149 | while (true) { |
150 | int i = toLines_nextLineBreak(s, start); |
151 | if (i < 0) { |
152 | if (s.length() > start) lines.add(s.substring(start)); |
153 | break; |
154 | } |
155 | |
156 | lines.add(s.substring(start, i)); |
157 | if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n') |
158 | i += 2; |
159 | else |
160 | ++i; |
161 | |
162 | start = i; |
163 | } |
164 | return lines; |
165 | } |
166 | |
167 | private static int toLines_nextLineBreak(String s, int start) { |
168 | for (int i = start; i < s.length(); i++) { |
169 | char c = s.charAt(i); |
170 | if (c == '\r' || c == '\n') |
171 | return i; |
172 | } |
173 | return -1; |
174 | } |
175 | |
176 | public static String fromLines(List<String> lines) { |
177 | StringBuilder buf = new StringBuilder(); |
178 | for (String line : lines) { |
179 | buf.append(line).append('\n'); |
180 | } |
181 | return buf.toString(); |
182 | } |
183 | |
184 | private static File applyTranslators(File x, List<String> translators, List<File> libraries_out) throws Exception { |
185 | for (String translator : translators) |
186 | x = applyTranslator(x, translator, libraries_out); |
187 | return x; |
188 | } |
189 | |
190 | // also takes a library |
191 | private static File applyTranslator(File x, String translator, List<File> libraries_out) throws Exception { |
192 | if (verbose) |
193 | System.out.println("Using translator " + translator + " on sources in " + x.getPath()); |
194 | |
195 | File newDir = runTranslatorOnInput(translator, null, x, !verbose, libraries_out); |
196 | |
197 | if (!new File(newDir, "main.java").exists()) { |
198 | throw new Exception("Translator " + translator + " did not generate main.java"); |
199 | // TODO: show translator output |
200 | } |
201 | if (verbose) |
202 | System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath()); |
203 | x = newDir; |
204 | return x; |
205 | } |
206 | |
207 | private static File luaPrintToJavaPrint(File x) throws IOException { |
208 | File newDir = TempDirMaker_make(); |
209 | String code = loadTextFile(new File(x, "main.java").getPath(), null); |
210 | code = luaPrintToJavaPrint(code); |
211 | if (verbose) |
212 | System.out.println(code); |
213 | saveTextFile(new File(newDir, "main.java").getPath(), code); |
214 | return newDir; |
215 | } |
216 | |
217 | public static String luaPrintToJavaPrint(String code) { |
218 | return ("\n" + code).replaceAll( |
219 | "(\n\\s*)print (\".*\")", |
220 | "$1System.out.println($2);").substring(1); |
221 | } |
222 | |
223 | public static File loadSnippetAsMainJava(String snippetID) throws IOException { |
224 | File srcDir = TempDirMaker_make(); |
225 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID)); |
226 | return srcDir; |
227 | } |
228 | |
229 | public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { |
230 | File srcDir = TempDirMaker_make(); |
231 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); |
232 | return srcDir; |
233 | } |
234 | |
235 | /** returns output dir */ |
236 | private static File runTranslatorOnInput(String snippetID, String hash, File input, boolean silent, |
237 | List<File> libraries_out) throws Exception { |
238 | File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); |
239 | if (libraryFile != null) { |
240 | loadLibrary(snippetID, libraries_out, libraryFile); |
241 | return input; |
242 | } |
243 | |
244 | File srcDir = hash == null ? loadSnippetAsMainJava(snippetID) |
245 | : loadSnippetAsMainJavaVerified(snippetID, hash); |
246 | |
247 | long mainJavaSize = new File(srcDir, "main.java").length(); |
248 | |
249 | if (mainJavaSize == 0) { // no text in snippet? assume it's a library |
250 | loadLibrary(snippetID, libraries_out, libraryFile); |
251 | return input; |
252 | } |
253 | |
254 | List<File> libraries = new ArrayList<File>(); |
255 | srcDir = defaultTranslate(srcDir, libraries); |
256 | boolean runInProcess = false; |
257 | File ioBaseDir = TempDirMaker_make(); |
258 | |
259 | if (virtualizeTranslators) { |
260 | if (verbose) System.out.println("Virtualizing translator"); |
261 | |
262 | //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator |
263 | // that doesn't work because it recurses infinitely... |
264 | |
265 | // So we do it right here: |
266 | String s = loadTextFile(new File(srcDir, "main.java").getPath(), null); |
267 | s = s.replaceAll("new\\s+File\\(", "virtual.newFile("); |
268 | s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream("); |
269 | s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream("); |
270 | s += "\n\n" + loadSnippet("#2000355"); // load class virtual |
271 | |
272 | // change baseDir |
273 | s = s.replace("virtual_baseDir = \"\";", |
274 | "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";"); |
275 | |
276 | // forward snippet cache |
277 | s = s.replace("static File DiskSnippetCache_dir;", |
278 | "static File DiskSnippetCache_dir = new File(" + javaQuote(DiskSnippetCache_dir.getAbsolutePath()) + ");"); |
279 | s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;"); |
280 | |
281 | if (verbose) { |
282 | System.out.println("==BEGIN VIRTUALIZED TRANSLATOR=="); |
283 | System.out.println(s); |
284 | System.out.println("==END VIRTUALIZED TRANSLATOR=="); |
285 | } |
286 | saveTextFile(new File(srcDir, "main.java").getPath(), s); |
287 | |
288 | // TODO: silence translator also |
289 | runInProcess = true; |
290 | } |
291 | |
292 | return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries); |
293 | } |
294 | |
295 | private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException { |
296 | if (verbose) |
297 | System.out.println("Assuming " + snippetID + " is a library."); |
298 | |
299 | if (libraryFile == null) { |
300 | byte[] data; |
301 | try { |
302 | URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID) |
303 | + "&contentType=application/binary"); |
304 | System.err.println("Loading library: " + url); |
305 | data = loadBinaryPage(url.openConnection(), url); |
306 | if (verbose) |
307 | System.err.println("Bytes loaded: " + data.length); |
308 | } catch (FileNotFoundException e) { |
309 | throw new IOException("Binary snippet #" + snippetID + " not found or not public"); |
310 | } |
311 | DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data); |
312 | libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); |
313 | } |
314 | |
315 | if (!libraries_out.contains(libraryFile)) |
316 | libraries_out.add(libraryFile); |
317 | } |
318 | |
319 | /** returns output dir */ |
320 | private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput, |
321 | boolean silent, boolean runInProcess, |
322 | List<File> libraries) throws Exception { |
323 | File srcDir = new File(ioBaseDir, "src"); |
324 | File inputDir = new File(ioBaseDir, "input"); |
325 | File outputDir = new File(ioBaseDir, "output"); |
326 | copyInput(originalSrcDir, srcDir); |
327 | copyInput(originalInput, inputDir); |
328 | javax2(srcDir, ioBaseDir, silent, runInProcess, libraries); |
329 | return outputDir; |
330 | } |
331 | |
332 | private static void copyInput(File src, File dst) throws IOException { |
333 | copyDirectory(src, dst); |
334 | } |
335 | |
336 | public static boolean hasFile(File inputDir, String name) { |
337 | return new File(inputDir, name).exists(); |
338 | } |
339 | |
340 | public static void copyDirectory(File src, File dst) throws IOException { |
341 | if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); |
342 | dst.mkdirs(); |
343 | File[] files = src.listFiles(); |
344 | if (files == null) return; |
345 | for (File file : files) { |
346 | File dst1 = new File(dst, file.getName()); |
347 | if (file.isDirectory()) |
348 | copyDirectory(file, dst1); |
349 | else { |
350 | if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); |
351 | copy(file, dst1); |
352 | } |
353 | } |
354 | } |
355 | |
356 | /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ |
357 | public static void copy(File src, File dest) throws IOException { |
358 | FileInputStream inputStream = new FileInputStream(src); |
359 | FileOutputStream outputStream = new FileOutputStream(dest); |
360 | try { |
361 | copy(inputStream, outputStream); |
362 | inputStream.close(); |
363 | } finally { |
364 | outputStream.close(); |
365 | } |
366 | } |
367 | |
368 | public static void copy(InputStream in, OutputStream out) throws IOException { |
369 | byte[] buf = new byte[65536]; |
370 | while (true) { |
371 | int n = in.read(buf); |
372 | if (n <= 0) return; |
373 | out.write(buf, 0, n); |
374 | } |
375 | } |
376 | |
377 | /** writes safely (to temp file, then rename) */ |
378 | public static void saveTextFile(String fileName, String contents) throws IOException { |
379 | File file = new File(fileName); |
380 | File parentFile = file.getParentFile(); |
381 | if (parentFile != null) |
382 | parentFile.mkdirs(); |
383 | String tempFileName = fileName + "_temp"; |
384 | FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); |
385 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); |
386 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
387 | printWriter.print(contents); |
388 | printWriter.close(); |
389 | if (file.exists() && !file.delete()) |
390 | throw new IOException("Can't delete " + fileName); |
391 | |
392 | if (!new File(tempFileName).renameTo(file)) |
393 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
394 | } |
395 | |
396 | /** writes safely (to temp file, then rename) */ |
397 | public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { |
398 | File file = new File(fileName); |
399 | File parentFile = file.getParentFile(); |
400 | if (parentFile != null) |
401 | parentFile.mkdirs(); |
402 | String tempFileName = fileName + "_temp"; |
403 | FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); |
404 | fileOutputStream.write(contents); |
405 | fileOutputStream.close(); |
406 | if (file.exists() && !file.delete()) |
407 | throw new IOException("Can't delete " + fileName); |
408 | |
409 | if (!new File(tempFileName).renameTo(file)) |
410 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
411 | } |
412 | |
413 | public static String loadTextFile(String fileName, String defaultContents) throws IOException { |
414 | if (!new File(fileName).exists()) |
415 | return defaultContents; |
416 | |
417 | FileInputStream fileInputStream = new FileInputStream(fileName); |
418 | InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); |
419 | return loadTextFile(inputStreamReader); |
420 | } |
421 | |
422 | public static String loadTextFile(Reader reader) throws IOException { |
423 | StringBuilder builder = new StringBuilder(); |
424 | try { |
425 | BufferedReader bufferedReader = new BufferedReader(reader); |
426 | String line; |
427 | while ((line = bufferedReader.readLine()) != null) |
428 | builder.append(line).append('\n'); |
429 | } finally { |
430 | reader.close(); |
431 | } |
432 | return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1); |
433 | } |
434 | |
435 | static File DiskSnippetCache_dir; |
436 | |
437 | public static void initDiskSnippetCache(File dir) { |
438 | DiskSnippetCache_dir = dir; |
439 | dir.mkdirs(); |
440 | } |
441 | |
442 | // Data files are immutable, use centralized cache |
443 | public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException { |
444 | File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); |
445 | if (verbose) |
446 | System.out.println("Checking data cache: " + file.getPath()); |
447 | return file.exists() ? file : null; |
448 | } |
449 | |
450 | public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { |
451 | return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); |
452 | } |
453 | |
454 | private static File DiskSnippetCache_getFile(long snippetID) { |
455 | return new File(DiskSnippetCache_dir, "" + snippetID); |
456 | } |
457 | |
458 | public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { |
459 | saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); |
460 | } |
461 | |
462 | public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { |
463 | saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); |
464 | } |
465 | |
466 | public static File DiskSnippetCache_getDir() { |
467 | return DiskSnippetCache_dir; |
468 | } |
469 | |
470 | public static void initSnippetCache() { |
471 | if (DiskSnippetCache_dir == null) |
472 | initDiskSnippetCache(getGlobalCache()); |
473 | } |
474 | |
475 | private static File getGlobalCache() { |
476 | File file = new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"); |
477 | file.mkdirs(); |
478 | return file; |
479 | } |
480 | |
481 | public static String loadSnippetVerified(String snippetID, String hash) throws IOException { |
482 | String text = loadSnippet(snippetID); |
483 | String realHash = getHash(text.getBytes("UTF-8")); |
484 | if (!realHash.equals(hash)) { |
485 | String msg; |
486 | if (hash.isEmpty()) |
487 | msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash; |
488 | else |
489 | msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??"; |
490 | throw new RuntimeException(msg); |
491 | } |
492 | return text; |
493 | } |
494 | |
495 | public static String getHash(byte[] data) { |
496 | return bytesToHex(getFullFingerprint(data)); |
497 | } |
498 | |
499 | public static byte[] getFullFingerprint(byte[] data) { |
500 | try { |
501 | return MessageDigest.getInstance("MD5").digest(data); |
502 | } catch (NoSuchAlgorithmException e) { |
503 | throw new RuntimeException(e); |
504 | } |
505 | } |
506 | |
507 | public static String bytesToHex(byte[] bytes) { |
508 | return bytesToHex(bytes, 0, bytes.length); |
509 | } |
510 | |
511 | public static String bytesToHex(byte[] bytes, int ofs, int len) { |
512 | StringBuilder stringBuilder = new StringBuilder(len*2); |
513 | for (int i = 0; i < len; i++) { |
514 | String s = "0" + Integer.toHexString(bytes[ofs+i]); |
515 | stringBuilder.append(s.substring(s.length()-2, s.length())); |
516 | } |
517 | return stringBuilder.toString(); |
518 | } |
519 | |
520 | public static String loadSnippet(String snippetID) throws IOException { |
521 | return loadSnippet(parseSnippetID(snippetID)); |
522 | } |
523 | |
524 | public static long parseSnippetID(String snippetID) { |
525 | return Long.parseLong(shortenSnippetID(snippetID)); |
526 | } |
527 | |
528 | private static String shortenSnippetID(String snippetID) { |
529 | if (snippetID.startsWith("#")) |
530 | snippetID = snippetID.substring(1); |
531 | String httpBlaBla = "http://tinybrain.de/"; |
532 | if (snippetID.startsWith(httpBlaBla)) |
533 | snippetID = snippetID.substring(httpBlaBla.length()); |
534 | return snippetID; |
535 | } |
536 | |
537 | public static boolean isSnippetID(String snippetID) { |
538 | snippetID = shortenSnippetID(snippetID); |
539 | return isInteger(snippetID) && Long.parseLong(snippetID) != 0; |
540 | } |
541 | |
542 | public static boolean isInteger(String s) { |
543 | return Pattern.matches("\\-?\\d+", s); |
544 | } |
545 | |
546 | public static String loadSnippet(long snippetID) throws IOException { |
547 | String text = memSnippetCache.get(snippetID); |
548 | if (text != null) |
549 | return text; |
550 | |
551 | if (preferCached) { |
552 | initSnippetCache(); |
553 | text = DiskSnippetCache_get(snippetID); |
554 | if (text != null) |
555 | return text; |
556 | } |
557 | |
558 | try { |
559 | URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); |
560 | text = loadPage(url); |
561 | } catch (FileNotFoundException e) { |
562 | throw new IOException("Snippet #" + snippetID + " not found or not public"); |
563 | } |
564 | |
565 | memSnippetCache.put(snippetID, text); |
566 | |
567 | try { |
568 | initSnippetCache(); |
569 | DiskSnippetCache_put(snippetID, text); |
570 | } catch (IOException e) { |
571 | System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); |
572 | } |
573 | |
574 | return text; |
575 | } |
576 | |
577 | private static String loadPage(URL url) throws IOException { |
578 | System.err.println("Loading: " + url.toExternalForm()); |
579 | URLConnection con = url.openConnection(); |
580 | return loadPage(con, url); |
581 | } |
582 | |
583 | public static String loadPage(URLConnection con, URL url) throws IOException { |
584 | String contentType = con.getContentType(); |
585 | if (contentType == null) |
586 | throw new IOException("Page could not be read: " + url); |
587 | //Log.info("Content-Type: " + contentType); |
588 | String charset = guessCharset(contentType); |
589 | Reader r = new InputStreamReader(con.getInputStream(), charset); |
590 | StringBuilder buf = new StringBuilder(); |
591 | while (true) { |
592 | int ch = r.read(); |
593 | if (ch < 0) |
594 | break; |
595 | //Log.info("Chars read: " + buf.length()); |
596 | buf.append((char) ch); |
597 | } |
598 | return buf.toString(); |
599 | } |
600 | |
601 | public static byte[] loadBinaryPage(URLConnection con, URL url) throws IOException { |
602 | ByteArrayOutputStream buf = new ByteArrayOutputStream(); |
603 | InputStream inputStream = con.getInputStream(); |
604 | while (true) { |
605 | int ch = inputStream.read(); |
606 | if (ch < 0) |
607 | break; |
608 | buf.write(ch); |
609 | } |
610 | inputStream.close(); |
611 | return buf.toByteArray(); |
612 | } |
613 | |
614 | public static String guessCharset(String contentType) { |
615 | Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); |
616 | Matcher m = p.matcher(contentType); |
617 | /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ |
618 | return m.matches() ? m.group(1) : "ISO-8859-1"; |
619 | } |
620 | |
621 | /** runs a transpiled set of sources */ |
622 | public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess, |
623 | List<File> libraries) throws Exception { |
624 | // collect sources |
625 | |
626 | List<File> sources = new ArrayList<File>(); |
627 | if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); |
628 | scanForSources(srcDir, sources, true); |
629 | if (sources.isEmpty()) { |
630 | System.out.println("No sources found"); |
631 | return; |
632 | } |
633 | |
634 | // compile |
635 | |
636 | File optionsFile = File.createTempFile("javax", ""); |
637 | File classesDir = TempDirMaker_make(); |
638 | if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); |
639 | String options = "-d " + bashQuote(classesDir.getPath()); |
640 | writeOptions(sources, libraries, optionsFile, options); |
641 | classesDir.mkdirs(); |
642 | String javacOutput = invokeJavac(optionsFile); |
643 | |
644 | // run |
645 | |
646 | if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath() |
647 | + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n"); |
648 | runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries); |
649 | } |
650 | |
651 | private static void runProgram(String javacOutput, File classesDir, File ioBaseDir, |
652 | boolean silent, boolean runInProcess, |
653 | List<File> libraries) throws Exception { |
654 | // print javac output if compile failed and it hasn't been printed yet |
655 | boolean didNotCompile = !hasFile(classesDir, "main.class"); |
656 | if (verbose || didNotCompile) |
657 | System.out.println(javacOutput); |
658 | if (didNotCompile) |
659 | return; |
660 | |
661 | if (runInProcess |
662 | || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) { |
663 | runProgramQuick(classesDir, libraries); |
664 | return; |
665 | } |
666 | |
667 | boolean echoOK = false; |
668 | // TODO: add libraries to class path |
669 | String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " |
670 | + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; |
671 | if (verbose) System.out.println(bashCmd); |
672 | String output = backtick(bashCmd); |
673 | if (verbose || !silent) |
674 | System.out.println(output); |
675 | } |
676 | |
677 | private static void runProgramQuick(File classesDir, List<File> libraries) throws Exception { |
678 | // collect urls |
679 | URL[] urls = new URL[libraries.size()+1]; |
680 | urls[0] = classesDir.toURI().toURL(); |
681 | for (int i = 0; i < libraries.size(); i++) |
682 | urls[i+1] = libraries.get(i).toURI().toURL(); |
683 | |
684 | // make class loader |
685 | URLClassLoader classLoader = new URLClassLoader(urls); |
686 | |
687 | // load JavaX main class |
688 | Class<?> mainClass = classLoader.loadClass("main"); |
689 | |
690 | // run main method |
691 | Method main = mainClass.getMethod("main", String[].class); |
692 | main.invoke(null, (Object) new String[0]); |
693 | } |
694 | |
695 | private static String invokeJavac(File optionsFile) throws IOException { |
696 | String output; |
697 | try { |
698 | output = invokeEcj(optionsFile); |
699 | } catch (NoClassDefFoundError e) { |
700 | if (verbose) { |
701 | System.err.println("ecj not found - using javac"); |
702 | e.printStackTrace(); |
703 | } |
704 | output = backtick("javac " + bashQuote("@" + optionsFile.getPath())); |
705 | } |
706 | if (verbose) System.out.println(output); |
707 | return output; |
708 | } |
709 | |
710 | // throws ClassNotFoundError if ecj is not in classpath |
711 | static String invokeEcj(File optionsFile) { |
712 | StringWriter writer = new StringWriter(); |
713 | PrintWriter printWriter = new PrintWriter(writer); |
714 | org.eclipse.jdt.core.compiler.CompilationProgress progress = null; |
715 | org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile( |
716 | new String[] { "@" + optionsFile.getPath(), "-source", "1.7" }, |
717 | printWriter, |
718 | printWriter, |
719 | progress); |
720 | return writer.toString(); |
721 | } |
722 | |
723 | private static void writeOptions(List<File> sources, List<File> libraries, |
724 | File optionsFile, String moreOptions) throws IOException { |
725 | FileWriter writer = new FileWriter(optionsFile); |
726 | for (File source : sources) |
727 | writer.write(bashQuote(source.getPath()) + " "); |
728 | if (!libraries.isEmpty()) { |
729 | List<String> cp = new ArrayList<String>(); |
730 | for (File lib : libraries) |
731 | cp.add(lib.getAbsolutePath()); |
732 | writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " "); |
733 | } |
734 | writer.write(moreOptions); |
735 | writer.close(); |
736 | } |
737 | |
738 | private static void scanForSources(File source, List<File> sources, boolean topLevel) { |
739 | if (source.isFile() && source.getName().endsWith(".java")) |
740 | sources.add(source); |
741 | else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { |
742 | File[] files = source.listFiles(); |
743 | for (File file : files) |
744 | scanForSources(file, sources, false); |
745 | } |
746 | } |
747 | |
748 | private static boolean isSkippedDirectoryName(String name, boolean topLevel) { |
749 | 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.) |
750 | return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); |
751 | } |
752 | |
753 | public static String backtick(String cmd) throws IOException { |
754 | ++processesStarted; |
755 | File outFile = File.createTempFile("_backtick", ""); |
756 | File scriptFile = File.createTempFile("_backtick", ""); |
757 | |
758 | String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; |
759 | //Log.info("[Backtick] " + command); |
760 | try { |
761 | saveTextFile(scriptFile.getPath(), command); |
762 | String[] command2 = {"/bin/bash", scriptFile.getPath() }; |
763 | Process process = Runtime.getRuntime().exec(command2); |
764 | try { |
765 | process.waitFor(); |
766 | } catch (InterruptedException e) { |
767 | throw new RuntimeException(e); |
768 | } |
769 | process.exitValue(); |
770 | return loadTextFile(outFile.getPath(), ""); |
771 | } finally { |
772 | scriptFile.delete(); |
773 | } |
774 | } |
775 | |
776 | /** possibly improvable */ |
777 | public static String javaQuote(String text) { |
778 | return bashQuote(text); |
779 | } |
780 | |
781 | /** possibly improvable */ |
782 | public static String bashQuote(String text) { |
783 | if (text == null) return null; |
784 | return "\"" + text |
785 | .replace("\\", "\\\\") |
786 | .replace("\"", "\\\"") |
787 | .replace("\n", "\\n") |
788 | .replace("\r", "\\r") + "\""; |
789 | } |
790 | |
791 | public final static String charsetForTextFiles = "UTF8"; |
792 | |
793 | static long TempDirMaker_lastValue; |
794 | |
795 | public static File TempDirMaker_make() { |
796 | File dir = new File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue()); |
797 | dir.mkdirs(); |
798 | return dir; |
799 | } |
800 | |
801 | private static long TempDirMaker_newValue() { |
802 | long value; |
803 | do |
804 | value = System.currentTimeMillis(); |
805 | while (value == TempDirMaker_lastValue); |
806 | TempDirMaker_lastValue = value; |
807 | return value; |
808 | } |
809 | |
810 | public static String join(String glue, Iterable<String> strings) { |
811 | StringBuilder buf = new StringBuilder(); |
812 | Iterator<String> i = strings.iterator(); |
813 | if (i.hasNext()) { |
814 | buf.append(i.next()); |
815 | while (i.hasNext()) |
816 | buf.append(glue).append(i.next()); |
817 | } |
818 | return buf.toString(); |
819 | } |
820 | } |
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
ID | Author/Program | Comment | Date | |
---|---|---|---|---|
906 | #1000604 (pitcher) | 2015-08-20 15:28:24 | ||
895 | #1000610 | Edit suggestion: !636 !629 main { static Object androidContext; static String programID; public static void main(String[] args) throws Exception { import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** JavaX runner version 11. Changes to v10: -can load libraries :) [Just upload them via http://tinybrain.de:8080/tb/upload-data.php and include in source as "!12345", like a translator.] Still Linux only. (Where are the Windows porters?) */ public class x11 { static final String version = "JavaX 11"; static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true; static boolean preferCached = false; static List<String> mainTranslators = new ArrayList<String>(); private static Map<Long, String> memSnippetCache = new HashMap<Long, String>(); private static int processesStarted; public static void main(String[] args) throws Exception { File ioBaseDir = new File("."), inputDir = null, outputDir = null; String src = "."; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("-v") || arg.equals("-verbose")) verbose = true; else if (arg.equals("-finderror")) verbose = true; else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached")) preferCached = true; else if (arg.equals("-novirt")) virtualizeTranslators = false; else if (arg.equals("translate")) translate = true; else if (arg.equals("list")) list = true; else if (arg.equals("run")) { // it's the default command anyway } else if (arg.startsWith("input=")) inputDir = new File(arg.substring(6)); else if (arg.startsWith("output=")) outputDir = new File(arg.substring(7)); else if (arg.equals("with")) mainTranslators.add(args[++i]); else src = arg; } if (virtualizeTranslators && !preferCached) initDiskSnippetCache(TempDirMaker_make()); if (inputDir != null) { ioBaseDir = TempDirMaker_make(); System.out.println("Taking input from: " + inputDir.getAbsolutePath()); System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath()); copyInput(inputDir, new File(ioBaseDir, "input")); } javax4(src, ioBaseDir, translate, list); if (outputDir != null) { copyInput(new File(ioBaseDir, "output"), outputDir); System.out.println("Output copied to: " + outputDir.getAbsolutePath()); } if (verbose) System.out.println("Processes started: " + processesStarted); } public static void javax4(String src, File ioDir, boolean translate, boolean list) throws Exception { File srcDir; if (isSnippetID(src)) srcDir = loadSnippetAsMainJava(src); else { srcDir = new File(src); if (!new File(srcDir, "main.java").exists()) { System.out.println("This is " + version + ".\n" + "No main.java found, exiting"); return; } } // translate List<File> libraries = new ArrayList<File>(); File X = srcDir; X = applyTranslators(X, mainTranslators, libraries); X = defaultTranslate(X, libraries); // list or run if (translate) System.out.println("Program translated to: " + X.getAbsolutePath()); else if (list) System.out.println(loadTextFile(new File(X, "main.java").getPath(), null)); else javax2(X, ioDir, false, false, libraries); } private static File defaultTranslate(File x, List<File> libraries_out) throws Exception { x = luaPrintToJavaPrint(x); x = autoTranslate(x, libraries_out); return x; } private static File autoTranslate(File x, List<File> libraries_out) throws Exception { String main = loadTextFile(new File(x, "main.java").getPath(), null); List<String> lines = toLines(main); List<String> translators = findTranslators(lines); if (translators.isEmpty()) return x; main = fromLines(lines); File newDir = TempDirMaker_make(); saveTextFile(new File(newDir, "main.java").getPath(), main); return applyTranslators(newDir, translators, libraries_out); } private static List<String> findTranslators(List<String> lines) { List<String> translators = new ArrayList<String>(); Pattern pattern = Pattern.compile("^!([0-9# \t]+)"); for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) { String line = iterator.next(); line = line.trim(); Matcher matcher = pattern.matcher(line); if (matcher.find()) { translators.addAll(Arrays.asList(matcher.group(1).split("[ \t]+"))); iterator.remove(); } } return translators; } public static List<String> toLines(String s) { List<String> lines = new ArrayList<String>(); int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n') i += 2; else ++i; start = i; } return lines; } private static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } public static String fromLines(List<String> lines) { StringBuilder buf = new StringBuilder(); for (String line : lines) { buf.append(line).append('\n'); } return buf.toString(); } private static File applyTranslators(File x, List<String> translators, List<File> libraries_out) throws Exception { for (String translator : translators) x = applyTranslator(x, translator, libraries_out); return x; } // also takes a library private static File applyTranslator(File x, String translator, List<File> libraries_out) throws Exception { if (verbose) System.out.println("Using translator " + translator + " on sources in " + x.getPath()); File newDir = runTranslatorOnInput(translator, null, x, !verbose, libraries_out); if (!new File(newDir, "main.java").exists()) { throw new Exception("Translator " + translator + " did not generate main.java"); // TODO: show translator output } if (verbose) System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath()); x = newDir; return x; } private static File luaPrintToJavaPrint(File x) throws IOException { File newDir = TempDirMaker_make(); String code = loadTextFile(new File(x, "main.java").getPath(), null); code = luaPrintToJavaPrint(code); if (verbose) System.out.println(code); saveTextFile(new File(newDir, "main.java").getPath(), code); return newDir; } public static String luaPrintToJavaPrint(String code) { return ("\n" + code).replaceAll( "(\n\\s*)print (\".*\")", "$1System.out.println($2);").substring(1); } public static File loadSnippetAsMainJava(String snippetID) throws IOException { File srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID)); return srcDir; } public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { File srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); return srcDir; } /** returns output dir */ private static File runTranslatorOnInput(String snippetID, String hash, File input, boolean silent, List<File> libraries_out) throws Exception { File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); if (libraryFile != null) { loadLibrary(snippetID, libraries_out, libraryFile); return input; } File srcDir = hash == null ? loadSnippetAsMainJava(snippetID) : loadSnippetAsMainJavaVerified(snippetID, hash); long mainJavaSize = new File(srcDir, "main.java").length(); if (mainJavaSize == 0) { // no text in snippet? assume it's a library loadLibrary(snippetID, libraries_out, libraryFile); return input; } List<File> libraries = new ArrayList<File>(); srcDir = defaultTranslate(srcDir, libraries); boolean runInProcess = false; File ioBaseDir = TempDirMaker_make(); if (virtualizeTranslators) { if (verbose) System.out.println("Virtualizing translator"); //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator // that doesn't work because it recurses infinitely... // So we do it right here: String s = loadTextFile(new File(srcDir, "main.java").getPath(), null); s = s.replaceAll("new\\s+File\\(", "virtual.newFile("); s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream("); s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream("); s += "\n\n" + loadSnippet("#2000355"); // load class virtual // change baseDir s = s.replace("virtual_baseDir = \"\";", "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";"); // forward snippet cache s = s.replace("static File DiskSnippetCache_dir;", "static File DiskSnippetCache_dir = new File(" + javaQuote(DiskSnippetCache_dir.getAbsolutePath()) + ");"); s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;"); if (verbose) { System.out.println("==BEGIN VIRTUALIZED TRANSLATOR=="); System.out.println(s); System.out.println("==END VIRTUALIZED TRANSLATOR=="); } saveTextFile(new File(srcDir, "main.java").getPath(), s); // TODO: silence translator also runInProcess = true; } return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries); } private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException { if (verbose) System.out.println("Assuming " + snippetID + " is a library."); if (libraryFile == null) { byte[] data; try { URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID) + "&contentType=application/binary"); System.err.println("Loading library: " + url); data = loadBinaryPage(url.openConnection(), url); if (verbose) System.err.println("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data); libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); } if (!libraries_out.contains(libraryFile)) libraries_out.add(libraryFile); } /** returns output dir */ private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput, boolean silent, boolean runInProcess, List<File> libraries) throws Exception { File srcDir = new File(ioBaseDir, "src"); File inputDir = new File(ioBaseDir, "input"); File outputDir = new File(ioBaseDir, "output"); copyInput(originalSrcDir, srcDir); copyInput(originalInput, inputDir); javax2(srcDir, ioBaseDir, silent, runInProcess, libraries); return outputDir; } private static void copyInput(File src, File dst) throws IOException { copyDirectory(src, dst); } public static boolean hasFile(File inputDir, String name) { return new File(inputDir, name).exists(); } public static void copyDirectory(File src, File dst) throws IOException { if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); dst.mkdirs(); File[] files = src.listFiles(); if (files == null) return; for (File file : files) { File dst1 = new File(dst, file.getName()); if (file.isDirectory()) copyDirectory(file, dst1); else { if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); copy(file, dst1); } } } /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ public static void copy(File src, File dest) throws IOException { FileInputStream inputStream = new FileInputStream(src); FileOutputStream outputStream = new FileOutputStream(dest); try { copy(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } /** writes safely (to temp file, then rename) */ public static void saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } /** writes safely (to temp file, then rename) */ public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } public static String loadTextFile(String fileName, String defaultContents) throws IOException { if (!new File(fileName).exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); return loadTextFile(inputStreamReader); } public static String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) builder.append(line).append('\n'); } finally { reader.close(); } return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1); } static File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } // Data files are immutable, use centralized cache public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); if (verbose) System.out.println("Checking data cache: " + file.getPath()); return file.exists() ? file : null; } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } private static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } private static File getGlobalCache() { File file = new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"); file.mkdirs(); return file; } public static String loadSnippetVerified(String snippetID, String hash) throws IOException { String text = loadSnippet(snippetID); String realHash = getHash(text.getBytes("UTF-8")); if (!realHash.equals(hash)) { String msg; if (hash.isEmpty()) msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash; else msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??"; throw new RuntimeException(msg); } return text; } public static String getHash(byte[] data) { return bytesToHex(getFullFingerprint(data)); } public static byte[] getFullFingerprint(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len*2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs+i]); stringBuilder.append(s.substring(s.length()-2, s.length())); } return stringBuilder.toString(); } public static String loadSnippet(String snippetID) throws IOException { return loadSnippet(parseSnippetID(snippetID)); } public static long parseSnippetID(String snippetID) { return Long.parseLong(shortenSnippetID(snippetID)); } private static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return snippetID; } public static boolean isSnippetID(String snippetID) { snippetID = shortenSnippetID(snippetID); return isInteger(snippetID) && Long.parseLong(snippetID) != 0; } public static boolean isInteger(String s) { return Pattern.matches("\\-?\\d+", s); } public static String loadSnippet(long snippetID) throws IOException { String text = memSnippetCache.get(snippetID); if (text != null) return text; if (preferCached) { initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (text != null) return text; } try { URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); text = loadPage(url); } catch (FileNotFoundException e) { throw new IOException("Snippet #" + snippetID + " not found or not public"); } memSnippetCache.put(snippetID, text); try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } private static String loadPage(URL url) throws IOException { System.err.println("Loading: " + url.toExternalForm()); URLConnection con = url.openConnection(); return loadPage(con, url); } public static String loadPage(URLConnection con, URL url) throws IOException { String contentType = con.getContentType(); if (contentType == null) throw new IOException("Page could not be read: " + url); //Log.info("Content-Type: " + contentType); String charset = guessCharset(contentType); Reader r = new InputStreamReader(con.getInputStream(), charset); StringBuilder buf = new StringBuilder(); while (true) { int ch = r.read(); if (ch < 0) break; //Log.info("Chars read: " + buf.length()); buf.append((char) ch); } return buf.toString(); } public static byte[] loadBinaryPage(URLConnection con, URL url) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); } inputStream.close(); return buf.toByteArray(); } public static String guessCharset(String contentType) { Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); Matcher m = p.matcher(contentType); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ return m.matches() ? m.group(1) : "ISO-8859-1"; } /** runs a transpiled set of sources */ public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess, List<File> libraries) throws Exception { // collect sources List<File> sources = new ArrayList<File>(); if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); scanForSources(srcDir, sources, true); if (sources.isEmpty()) { System.out.println("No sources found"); return; } // compile File optionsFile = File.createTempFile("javax", ""); File classesDir = TempDirMaker_make(); if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); String options = "-d " + bashQuote(classesDir.getPath()); writeOptions(sources, libraries, optionsFile, options); classesDir.mkdirs(); String javacOutput = invokeJavac(optionsFile); // run if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath() + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n"); runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries); } private static void runProgram(String javacOutput, File classesDir, File ioBaseDir, boolean silent, boolean runInProcess, List<File> libraries) throws Exception { // print javac output if compile failed and it hasn't been printed yet boolean didNotCompile = !hasFile(classesDir, "main.class"); if (verbose || didNotCompile) System.out.println(javacOutput); if (didNotCompile) return; if (runInProcess || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) { runProgramQuick(classesDir, libraries); return; } boolean echoOK = false; // TODO: add libraries to class path String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; if (verbose) System.out.println(bashCmd); String output = backtick(bashCmd); if (verbose || !silent) System.out.println(output); } private static void runProgramQuick(File classesDir, List<File> libraries) throws Exception { // collect urls URL[] urls = new URL[libraries.size()+1]; urls[0] = classesDir.toURI().toURL(); for (int i = 0; i < libraries.size(); i++) urls[i+1] = libraries.get(i).toURI().toURL(); // make class loader URLClassLoader classLoader = new URLClassLoader(urls); // load JavaX main class Class<?> mainClass = classLoader.loadClass("main"); // run main method Method main = mainClass.getMethod("main", String[].class); main.invoke(null, (Object) new String[0]); } private static String invokeJavac(File optionsFile) throws IOException { String output; try { output = invokeEcj(optionsFile); } catch (NoClassDefFoundError e) { if (verbose) { System.err.println("ecj not found - using javac"); e.printStackTrace(); } output = backtick("javac " + bashQuote("@" + optionsFile.getPath())); } if (verbose) System.out.println(output); return output; } // throws ClassNotFoundError if ecj is not in classpath static String invokeEcj(File optionsFile) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); org.eclipse.jdt.core.compiler.CompilationProgress progress = null; org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile( new String[] { "@" + optionsFile.getPath(), "-source", "1.7" }, printWriter, printWriter, progress); return writer.toString(); } private static void writeOptions(List<File> sources, List<File> libraries, File optionsFile, String moreOptions) throws IOException { FileWriter writer = new FileWriter(optionsFile); for (File source : sources) writer.write(bashQuote(source.getPath()) + " "); if (!libraries.isEmpty()) { List<String> cp = new ArrayList<String>(); for (File lib : libraries) cp.add(lib.getAbsolutePath()); writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " "); } writer.write(moreOptions); writer.close(); } private static void scanForSources(File source, List<File> sources, boolean topLevel) { if (source.isFile() && source.getName().endsWith(".java")) sources.add(source); else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { File[] files = source.listFiles(); for (File file : files) scanForSources(file, sources, false); } } private static boolean isSkippedDirectoryName(String name, boolean topLevel) { 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.) return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); } public static String backtick(String cmd) throws IOException { ++processesStarted; File outFile = File.createTempFile("_backtick", ""); File scriptFile = File.createTempFile("_backtick", ""); String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; //Log.info("[Backtick] " + command); try { saveTextFile(scriptFile.getPath(), command); String[] command2 = {"/bin/bash", scriptFile.getPath() }; Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } process.exitValue(); return loadTextFile(outFile.getPath(), ""); } finally { scriptFile.delete(); } } /** possibly improvable */ public static String javaQuote(String text) { return bashQuote(text); } /** possibly improvable */ public static String bashQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } public final static String charsetForTextFiles = "UTF8"; static long TempDirMaker_lastValue; public static File TempDirMaker_make() { File dir = new File(System.getProperty("user.home"), ".javax/" + TempDirMaker_newValue()); dir.mkdirs(); return dir; } private static long TempDirMaker_newValue() { long value; do value = System.currentTimeMillis(); while (value == TempDirMaker_lastValue); TempDirMaker_lastValue = value; return value; } public static String join(String glue, Iterable<String> strings) { StringBuilder buf = new StringBuilder(); Iterator<String> i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } } }} | 2015-08-20 00:52:03 | delete |
Snippet ID: | #621 |
Snippet name: | x11.java |
Eternal ID of this version: | #621/1 |
Text MD5: | 736e13d062af99431e8ba3afc68c1593 |
Author: | stefan |
Category: | javax |
Type: | Java source code |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-05-19 21:42:31 |
Source code size: | 29717 bytes / 820 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 1460 / 209 |
Referenced in: | [show references] |