1 | import java.security.NoSuchAlgorithmException; |
2 | import java.security.MessageDigest; |
3 | import java.lang.reflect.*; |
4 | import java.net.*; |
5 | import javax.swing.*; |
6 | import java.util.regex.*; |
7 | import java.util.*; |
8 | import java.util.Timer; |
9 | import java.util.TimerTask; |
10 | import java.io.*; |
11 | |
12 | import android.widget.*; |
13 | import android.view.*; |
14 | import android.content.Context; |
15 | import android.app.Activity; |
16 | import android.view.inputmethod.*; |
17 | import android.content.*; |
18 | |
19 | public class main { |
20 | static List<Prog> programsStarted = new ArrayList<Prog>(); |
21 | |
22 | static class Prog { |
23 | String snippetID; |
24 | Thread thread; |
25 | } |
26 | |
27 | static class Lg { |
28 | static int maxBufferLength = 2048; |
29 | |
30 | Activity context; |
31 | ScrollView sv; |
32 | TextView tv; |
33 | StringBuilder buf = new StringBuilder(); |
34 | |
35 | Lg(Activity context) { |
36 | this.context = context; |
37 | sv = new ScrollView(context); |
38 | tv = new TextView(context); |
39 | tv.setText(buf.toString()); |
40 | sv.addView(tv); |
41 | } |
42 | |
43 | View getView() { |
44 | return sv; |
45 | } |
46 | |
47 | void shortenBuffer() { |
48 | while (buf.length() > maxBufferLength) { |
49 | String s = buf.toString(); |
50 | int i = s.indexOf('\n'); |
51 | if (i < 0) return; |
52 | buf = new StringBuilder(s.substring(i+1)); |
53 | } |
54 | } |
55 | |
56 | void print(final String s) { |
57 | context.runOnUiThread(new Runnable() { |
58 | public void run() { |
59 | buf.append(s); |
60 | shortenBuffer(); |
61 | tv.setText(buf.toString()); |
62 | |
63 | sv.post(new Runnable() { |
64 | public void run() { |
65 | // This method works but animates the scrolling |
66 | // which looks weird on first load |
67 | sv.fullScroll(View.FOCUS_DOWN); |
68 | |
69 | // This method works even better because there are no animations. |
70 | //sv.scrollTo(0, sv.getBottom()); |
71 | } |
72 | }); |
73 | } |
74 | }); |
75 | } |
76 | |
77 | void println(String s) { |
78 | print(s + "\n"); |
79 | } |
80 | } |
81 | |
82 | public static View main(final Activity context) throws Exception { |
83 | x19.androidContext = context; |
84 | final File defSnip = new File(x19.userHome(), ".javax/defsnip"); |
85 | String id = x19.loadTextFile(defSnip.getPath(), "675"); |
86 | final File defargs = new File(x19.userHome(), ".javax/defargs"); |
87 | String arg = x19.loadTextFile(defargs.getPath(), ""); |
88 | |
89 | ScrollView sv = new ScrollView(context); |
90 | LinearLayout ll = new LinearLayout(context); |
91 | ll.setOrientation(LinearLayout.VERTICAL); |
92 | |
93 | LinearLayout line1 = new LinearLayout(context); |
94 | |
95 | TextView label = new TextView(context); |
96 | label.setText("Run which snippet ID?"); |
97 | line1.addView(label); |
98 | |
99 | final EditText tv = new EditText(context); |
100 | tv.setText(id); |
101 | line1.addView(tv); |
102 | |
103 | Button btnGo = new Button(context); |
104 | btnGo.setText("Go"); |
105 | line1.addView(btnGo); |
106 | |
107 | ll.addView(line1); |
108 | |
109 | LinearLayout line2 = new LinearLayout(context); |
110 | |
111 | label = new TextView(context); |
112 | label.setText("Program arguments:"); |
113 | line2.addView(label); |
114 | |
115 | final EditText tvArgs = new EditText(context); |
116 | tvArgs.setText(arg); |
117 | line2.addView(tvArgs); |
118 | |
119 | ll.addView(line2); |
120 | |
121 | btnGo.setOnClickListener(new View.OnClickListener() { |
122 | public void onClick(View v) { |
123 | hideKeyboard(context); |
124 | String snippetID = tv.getText().toString(); |
125 | String text = "Running: " + snippetID; |
126 | Toast.makeText(context, text, 2000).show(); |
127 | |
128 | try { |
129 | x19.saveTextFile(defSnip.getPath(), snippetID); |
130 | x19.saveTextFile(defargs.getPath(), tvArgs.getText().toString()); |
131 | } catch (IOException e) { |
132 | } |
133 | run(context, snippetID, tvArgs.getText().toString().split(" +")); |
134 | } |
135 | }); |
136 | |
137 | sv.addView(ll); |
138 | return sv; |
139 | } |
140 | |
141 | static Lg lg; |
142 | |
143 | public static void run(final Activity context, final String mainSnippet, final String[] args) { |
144 | lg = new Lg(context); |
145 | |
146 | OutputStream outputStream = new OutputStream() { |
147 | public void write(int b) { |
148 | try { |
149 | lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap |
150 | } catch (UnsupportedEncodingException e) {} |
151 | } |
152 | |
153 | @Override |
154 | public void write(byte[] b, int off, int len) { |
155 | try { |
156 | lg.print(new String(b, off, len, "UTF-8")); // This is crap |
157 | } catch (UnsupportedEncodingException e) {} |
158 | } |
159 | }; |
160 | |
161 | PrintStream ps = new PrintStream(outputStream, true); |
162 | System.setOut(ps); |
163 | System.setErr(ps); |
164 | |
165 | Prog prog = new Prog(); |
166 | prog.snippetID = mainSnippet; |
167 | |
168 | prog.thread = new Thread() { |
169 | public void run() { |
170 | try { |
171 | String[] a = new String[args.length+1]; |
172 | System.arraycopy(args, 0, a, 1, args.length); |
173 | a[0] = mainSnippet; |
174 | x19.main(a); |
175 | } catch (Throwable e) { |
176 | System.out.println("Whoa!"); |
177 | e.printStackTrace(); |
178 | } |
179 | } |
180 | }; |
181 | |
182 | programsStarted.add(prog); |
183 | prog.thread.start(); |
184 | |
185 | context.setContentView(lg.getView()); |
186 | } |
187 | |
188 | static void setContentViewInUIThread(final View view) { |
189 | ((Activity) x19.androidContext).runOnUiThread(new Runnable() { |
190 | public void run() { |
191 | ((Activity) x19.androidContext).setContentView(view); |
192 | } |
193 | }); |
194 | } |
195 | |
196 | public static void hideKeyboard(Activity context) { |
197 | View view = context.getCurrentFocus(); |
198 | if (view != null) { |
199 | InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); |
200 | inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); |
201 | } |
202 | } |
203 | |
204 | static void onActivityResult(int requestCode, int resultCode, Intent data) { |
205 | if (x19.mainClass != null) |
206 | x19.call(x19.mainClass, "onActivityResult", requestCode, resultCode, data); |
207 | } |
208 | } |
209 | |
210 | class x19 { |
211 | static final String version = "JavaX 19"; |
212 | |
213 | static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true; |
214 | static String translateTo = null; |
215 | static boolean preferCached = false, noID = false, noPrefetch = false; |
216 | static boolean safeOnly = false, safeTranslate = false, javacOnly = false; |
217 | static List<String[]> mainTranslators = new ArrayList<String[]>(); |
218 | private static Map<Long, String> memSnippetCache = new HashMap<Long, String>(); |
219 | private static int processesStarted, compilations; |
220 | |
221 | // snippet ID -> md5 |
222 | private static HashMap<Long, String> prefetched = new HashMap<Long, String>(); |
223 | private static File virtCache; |
224 | |
225 | // doesn't work yet |
226 | private static Map<String, Class<?>> programCache = new HashMap<String, Class<?>>(); |
227 | static boolean cacheTranslators = false; |
228 | |
229 | // this should work (caches transpiled translators) |
230 | private static HashMap<Long, Object[]> translationCache = new HashMap<Long, Object[]>(); |
231 | static boolean cacheTranspiledTranslators = true; |
232 | |
233 | // which snippets are available pre-transpiled server-side? |
234 | private static Set<Long> hasTranspiledSet = new HashSet<Long>(); |
235 | static boolean useServerTranspiled = true; |
236 | |
237 | static Object androidContext; |
238 | static boolean android = isAndroid(); |
239 | |
240 | // Translators currently being translated (to detect recursions) |
241 | private static Set<Long> translating = new HashSet<Long>(); |
242 | |
243 | static String lastOutput; |
244 | |
245 | public static void main(String[] args) throws Exception { |
246 | File ioBaseDir = new File("."), inputDir = null, outputDir = null; |
247 | String src = null; |
248 | List<String> programArgs = new ArrayList<String>(); |
249 | String programID; |
250 | |
251 | for (int i = 0; i < args.length; i++) { |
252 | String arg = args[i]; |
253 | |
254 | if (arg.equals("-version")) { |
255 | showVersion(); |
256 | return; |
257 | } |
258 | |
259 | if (arg.equals("-sysprop")) { |
260 | showSystemProperties(); |
261 | return; |
262 | } |
263 | |
264 | if (arg.equals("-v") || arg.equals("-verbose")) |
265 | verbose = true; |
266 | else if (arg.equals("-finderror")) |
267 | verbose = true; |
268 | else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached")) |
269 | preferCached = true; |
270 | else if (arg.equals("-novirt")) |
271 | virtualizeTranslators = false; |
272 | else if (arg.equals("-safeonly")) |
273 | safeOnly = true; |
274 | else if (arg.equals("-safetranslate")) |
275 | safeTranslate = true; |
276 | else if (arg.equals("-noid")) |
277 | noID = true; |
278 | else if (arg.equals("-nocachetranspiled")) |
279 | cacheTranspiledTranslators = false; |
280 | else if (arg.equals("-javac")) |
281 | javacOnly = true; |
282 | else if (arg.equals("-localtranspile")) |
283 | useServerTranspiled = false; |
284 | else if (arg.equals("translate") && src == null) |
285 | translate = true; |
286 | else if (arg.equals("list") && src == null) { |
287 | list = true; |
288 | virtualizeTranslators = false; // so they are silenced |
289 | } else if (arg.equals("run") && src == null) { |
290 | // it's the default command anyway |
291 | } else if (arg.startsWith("input=")) |
292 | inputDir = new File(arg.substring(6)); |
293 | else if (arg.startsWith("output=")) |
294 | outputDir = new File(arg.substring(7)); |
295 | else if (arg.equals("with")) |
296 | mainTranslators.add(new String[] {args[++i], null}); |
297 | else if (translate && arg.equals("to")) |
298 | translateTo = args[++i]; |
299 | else if (src == null) { |
300 | //System.out.println("src=" + arg); |
301 | src = arg; |
302 | } else |
303 | programArgs.add(arg); |
304 | } |
305 | |
306 | cleanCache(); |
307 | |
308 | if (useServerTranspiled) |
309 | noPrefetch = true; |
310 | |
311 | if (src == null) src = "."; |
312 | |
313 | // Might actually want to write to 2 disk caches (global/per program). |
314 | if (virtualizeTranslators && !preferCached) |
315 | virtCache = TempDirMaker_make(); |
316 | |
317 | if (inputDir != null) { |
318 | ioBaseDir = TempDirMaker_make(); |
319 | System.out.println("Taking input from: " + inputDir.getAbsolutePath()); |
320 | System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath()); |
321 | copyInput(inputDir, new File(ioBaseDir, "input")); |
322 | } |
323 | |
324 | javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()])); |
325 | |
326 | if (outputDir != null) { |
327 | copyInput(new File(ioBaseDir, "output"), outputDir); |
328 | System.out.println("Output copied to: " + outputDir.getAbsolutePath()); |
329 | } |
330 | |
331 | if (verbose) { |
332 | // print stats |
333 | System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations); |
334 | } |
335 | } |
336 | |
337 | public static void javaxmain(String src, File ioDir, boolean translate, boolean list, |
338 | String[] args) throws Exception { |
339 | String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null; |
340 | |
341 | if (android && !translate && !list && ioDir.getPath().equals(".")) { |
342 | if (javaAndroidQuick(programID, args)) |
343 | return; |
344 | } |
345 | |
346 | List<File> libraries = new ArrayList<File>(); |
347 | |
348 | File X = transpileMain(src, libraries); |
349 | if (X == null) |
350 | return; |
351 | |
352 | // list or run |
353 | |
354 | if (translate) { |
355 | File to = X; |
356 | if (translateTo != null) |
357 | if (new File(translateTo).isDirectory()) |
358 | to = new File(translateTo, "main.java"); |
359 | else |
360 | to = new File(translateTo); |
361 | if (to != X) |
362 | copy(new File(X, "main.java"), to); |
363 | System.out.println("Program translated to: " + to.getAbsolutePath()); |
364 | } else if (list) |
365 | System.out.println(loadTextFile(new File(X, "main.java").getPath(), null)); |
366 | else |
367 | javax2(X, ioDir, false, false, libraries, args, null, programID); |
368 | } |
369 | |
370 | static boolean javaAndroidQuick(String programID, String[] args) throws Exception { |
371 | URL url = new URL("http://tinybrain.de:8080/dexcompile.php?id=" + programID + "&transOnly=1"); |
372 | byte[] dexData = loadBinaryPage(url.openConnection()); |
373 | if (!isDex(dexData)) return false; |
374 | javaAndroidGo(dexData, programID, args); |
375 | return true; |
376 | } |
377 | |
378 | static File transpileMain(String src, List<File> libraries) throws Exception { |
379 | File srcDir; |
380 | boolean isTranspiled = false; |
381 | if (isSnippetID(src)) { |
382 | prefetch(src); |
383 | long id = parseSnippetID(src); |
384 | prefetched.remove(id); // hackfix to ensure transpiled main program is found. |
385 | srcDir = loadSnippetAsMainJava(src); |
386 | if (verbose) |
387 | System.err.println("hasTranspiledSet: " + hasTranspiledSet); |
388 | if (hasTranspiledSet.contains(id) && useServerTranspiled) { |
389 | System.err.println("Trying pretranspiled main program: #" + id); |
390 | String transpiledSrc = getServerTranspiled("#" + id); |
391 | if (!transpiledSrc.isEmpty()) { |
392 | srcDir = TempDirMaker_make(); |
393 | saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc); |
394 | //saveTextFile(new File(srcDir, "is-transpiled").getPath(), "" + id); |
395 | isTranspiled = true; |
396 | //translationCache.put(id, new Object[] {srcDir, libraries}); |
397 | } |
398 | } |
399 | } else { |
400 | srcDir = new File(src); |
401 | |
402 | // if the argument is a file, it is assumed to be main.java |
403 | if (srcDir.isFile()) { |
404 | srcDir = TempDirMaker_make(); |
405 | copy(new File(src), new File(srcDir, "main.java")); |
406 | } |
407 | |
408 | if (!new File(srcDir, "main.java").exists()) { |
409 | showVersion(); |
410 | System.out.println("No main.java found, exiting"); |
411 | return null; |
412 | } |
413 | } |
414 | |
415 | // translate |
416 | |
417 | File X = srcDir; |
418 | |
419 | if (!isTranspiled) { |
420 | X = topLevelTranslate(X, libraries); |
421 | System.err.println("Translated " + src); |
422 | |
423 | // save prefetch data |
424 | if (isSnippetID(src)) |
425 | savePrefetchData(src); |
426 | } |
427 | return X; |
428 | } |
429 | |
430 | private static void prefetch(String mainSnippetID) throws IOException { |
431 | if (noPrefetch) return; |
432 | |
433 | long mainID = parseSnippetID(mainSnippetID); |
434 | String s = mainID + " " + loadTextFile(new File(userHome(), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), ""); |
435 | String[] ids = s.trim().split(" "); |
436 | if (ids.length > 1) { |
437 | String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8"); |
438 | String data = loadPage(new URL(url)); |
439 | String[] split = data.split(" "); |
440 | if (split.length == ids.length) |
441 | for (int i = 0; i < ids.length; i++) |
442 | prefetched.put(parseSnippetID(ids[i]), split[i]); |
443 | } |
444 | } |
445 | |
446 | static String userHomeInternal() { |
447 | if (android) |
448 | return ((File) call(androidContext, "getFilesDir")).getAbsolutePath(); |
449 | else |
450 | return System.getProperty("user.home"); |
451 | } |
452 | |
453 | static String userHome() { |
454 | if (android) |
455 | return "/storage/sdcard0/"; |
456 | else |
457 | return System.getProperty("user.home"); |
458 | } |
459 | |
460 | private static void savePrefetchData(String mainSnippetID) throws IOException { |
461 | List<String> ids = new ArrayList<String>(); |
462 | long mainID = parseSnippetID(mainSnippetID); |
463 | |
464 | for (long id : memSnippetCache.keySet()) |
465 | if (id != mainID) |
466 | ids.add(String.valueOf(id)); |
467 | |
468 | saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids)); |
469 | } |
470 | |
471 | static File topLevelTranslate(File srcDir, List<File> libraries_out) throws Exception { |
472 | File X = srcDir; |
473 | X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual) |
474 | |
475 | // actual inner translation of the JavaX source |
476 | X = defaultTranslate(X, libraries_out); |
477 | return X; |
478 | } |
479 | |
480 | private static File defaultTranslate(File x, List<File> libraries_out) throws Exception { |
481 | x = luaPrintToJavaPrint(x); |
482 | x = repeatAutoTranslate(x, libraries_out); |
483 | return x; |
484 | } |
485 | |
486 | private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception { |
487 | while (true) { |
488 | File y = autoTranslate(x, libraries_out); |
489 | if (y == x) |
490 | return x; |
491 | x = y; |
492 | } |
493 | } |
494 | |
495 | private static File autoTranslate(File x, List<File> libraries_out) throws Exception { |
496 | String main = loadTextFile(new File(x, "main.java").getPath(), null); |
497 | List<String> lines = toLines(main); |
498 | List<String[]> translators = findTranslators(lines); |
499 | if (translators.isEmpty()) |
500 | return x; |
501 | |
502 | main = fromLines(lines); |
503 | File newDir = TempDirMaker_make(); |
504 | saveTextFile(new File(newDir, "main.java").getPath(), main); |
505 | return applyTranslators(newDir, translators, libraries_out); |
506 | } |
507 | |
508 | private static List<String[]> findTranslators(List<String> lines) { |
509 | List<String[]> translators = new ArrayList<String[]>(); |
510 | Pattern pattern = Pattern.compile("^!([0-9# \t]+)"); |
511 | Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)"); |
512 | for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) { |
513 | String line = iterator.next(); |
514 | line = line.trim(); |
515 | Matcher matcher = pattern.matcher(line); |
516 | if (matcher.find()) { |
517 | String[] t = matcher.group(1).split("[ \t]+"); |
518 | String rest = line.substring(matcher.end()); |
519 | String arg = null; |
520 | if (t.length == 1) { |
521 | Matcher mArgs = pArgs.matcher(rest); |
522 | if (mArgs.find()) |
523 | arg = mArgs.group(1); |
524 | } |
525 | for (String transi : t) |
526 | translators.add(new String[]{transi, arg}); |
527 | iterator.remove(); |
528 | } |
529 | } |
530 | return translators; |
531 | } |
532 | |
533 | public static List<String> toLines(String s) { |
534 | List<String> lines = new ArrayList<String>(); |
535 | int start = 0; |
536 | while (true) { |
537 | int i = toLines_nextLineBreak(s, start); |
538 | if (i < 0) { |
539 | if (s.length() > start) lines.add(s.substring(start)); |
540 | break; |
541 | } |
542 | |
543 | lines.add(s.substring(start, i)); |
544 | if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n') |
545 | i += 2; |
546 | else |
547 | ++i; |
548 | |
549 | start = i; |
550 | } |
551 | return lines; |
552 | } |
553 | |
554 | private static int toLines_nextLineBreak(String s, int start) { |
555 | for (int i = start; i < s.length(); i++) { |
556 | char c = s.charAt(i); |
557 | if (c == '\r' || c == '\n') |
558 | return i; |
559 | } |
560 | return -1; |
561 | } |
562 | |
563 | public static String fromLines(List<String> lines) { |
564 | StringBuilder buf = new StringBuilder(); |
565 | for (String line : lines) { |
566 | buf.append(line).append('\n'); |
567 | } |
568 | return buf.toString(); |
569 | } |
570 | |
571 | private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception { |
572 | for (String[] translator : translators) |
573 | x = applyTranslator(x, translator[0], translator[1], libraries_out); |
574 | return x; |
575 | } |
576 | |
577 | // also takes a library |
578 | private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception { |
579 | if (verbose) |
580 | System.out.println("Using translator " + translator + " on sources in " + x.getPath()); |
581 | |
582 | File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out); |
583 | |
584 | if (!new File(newDir, "main.java").exists()) { |
585 | throw new Exception("Translator " + translator + " did not generate main.java"); |
586 | // TODO: show translator output |
587 | } |
588 | if (verbose) |
589 | System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath()); |
590 | x = newDir; |
591 | return x; |
592 | } |
593 | |
594 | private static File luaPrintToJavaPrint(File x) throws IOException { |
595 | File newDir = TempDirMaker_make(); |
596 | String code = loadTextFile(new File(x, "main.java").getPath(), null); |
597 | code = luaPrintToJavaPrint(code); |
598 | if (verbose) |
599 | System.out.println(code); |
600 | saveTextFile(new File(newDir, "main.java").getPath(), code); |
601 | return newDir; |
602 | } |
603 | |
604 | public static String luaPrintToJavaPrint(String code) { |
605 | return ("\n" + code).replaceAll( |
606 | "(\n\\s*)print (\".*\")", |
607 | "$1System.out.println($2);").substring(1); |
608 | } |
609 | |
610 | public static File loadSnippetAsMainJava(String snippetID) throws IOException { |
611 | checkProgramSafety(snippetID); |
612 | File srcDir = TempDirMaker_make(); |
613 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID)); |
614 | return srcDir; |
615 | } |
616 | |
617 | public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { |
618 | checkProgramSafety(snippetID); |
619 | File srcDir = TempDirMaker_make(); |
620 | saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); |
621 | return srcDir; |
622 | } |
623 | |
624 | /** returns output dir */ |
625 | private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input, |
626 | boolean silent, |
627 | List<File> libraries_out) throws Exception { |
628 | if (safeTranslate) |
629 | checkProgramSafetyImpl(snippetID); |
630 | long id = parseSnippetID(snippetID); |
631 | |
632 | File libraryFile = DiskSnippetCache_getLibrary(id); |
633 | if (libraryFile != null) { |
634 | loadLibrary(snippetID, libraries_out, libraryFile); |
635 | return input; |
636 | } |
637 | |
638 | String[] args = arg != null ? new String[]{arg} : new String[0]; |
639 | |
640 | File srcDir = hash == null ? loadSnippetAsMainJava(snippetID) |
641 | : loadSnippetAsMainJavaVerified(snippetID, hash); |
642 | long mainJavaSize = new File(srcDir, "main.java").length(); |
643 | |
644 | if (mainJavaSize == 0) { // no text in snippet? assume it's a library |
645 | loadLibrary(snippetID, libraries_out, libraryFile); |
646 | return input; |
647 | } |
648 | |
649 | List<File> libraries = new ArrayList<File>(); |
650 | Object[] cached = translationCache.get(id); |
651 | if (cached != null) { |
652 | //System.err.println("Taking translator " + snippetID + " from cache!"); |
653 | srcDir = (File) cached[0]; |
654 | libraries = (List<File>) cached[1]; |
655 | } else if (hasTranspiledSet.contains(id) && useServerTranspiled) { |
656 | System.err.println("Trying pretranspiled translator: #" + snippetID); |
657 | String transpiledSrc = getServerTranspiled(snippetID); |
658 | if (!transpiledSrc.isEmpty()) { |
659 | srcDir = TempDirMaker_make(); |
660 | saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc); |
661 | translationCache.put(id, cached = new Object[] {srcDir, libraries}); |
662 | } |
663 | } |
664 | |
665 | File ioBaseDir = TempDirMaker_make(); |
666 | |
667 | /*Class<?> mainClass = programCache.get("" + parseSnippetID(snippetID)); |
668 | if (mainClass != null) |
669 | return runCached(ioBaseDir, input, args);*/ |
670 | // Doesn't work yet because virtualized directories are hardcoded in translator... |
671 | |
672 | if (cached == null) { |
673 | System.err.println("Translating translator #" + id); |
674 | if (translating.contains(id)) |
675 | throw new RuntimeException("Recursive translator reference chain including #" + id); |
676 | translating.add(id); |
677 | try { |
678 | srcDir = defaultTranslate(srcDir, libraries); |
679 | } finally { |
680 | translating.remove(id); |
681 | } |
682 | System.err.println("Translated translator #" + id); |
683 | translationCache.put(id, new Object[]{srcDir, libraries}); |
684 | } |
685 | |
686 | boolean runInProcess = false; |
687 | |
688 | if (virtualizeTranslators) { |
689 | if (verbose) System.out.println("Virtualizing translator"); |
690 | |
691 | //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator |
692 | // that doesn't work because it recurses infinitely... |
693 | |
694 | // So we do it right here: |
695 | String s = loadTextFile(new File(srcDir, "main.java").getPath(), null); |
696 | s = s.replaceAll("new\\s+File\\(", "virtual.newFile("); |
697 | s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream("); |
698 | s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream("); |
699 | s += "\n\n" + loadSnippet("#2000355"); // load class virtual |
700 | |
701 | // change baseDir |
702 | s = s.replace("virtual_baseDir = \"\";", |
703 | "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";"); |
704 | |
705 | // forward snippet cache (virtualized one) |
706 | File dir = virtCache != null ? virtCache : DiskSnippetCache_dir; |
707 | s = s.replace("static File DiskSnippetCache_dir;", |
708 | "static File DiskSnippetCache_dir = new File(" + javaQuote(dir.getAbsolutePath()) + ");"); |
709 | s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;"); |
710 | |
711 | if (verbose) { |
712 | System.out.println("==BEGIN VIRTUALIZED TRANSLATOR=="); |
713 | System.out.println(s); |
714 | System.out.println("==END VIRTUALIZED TRANSLATOR=="); |
715 | } |
716 | srcDir = TempDirMaker_make(); |
717 | saveTextFile(new File(srcDir, "main.java").getPath(), s); |
718 | |
719 | // TODO: silence translator also |
720 | runInProcess = true; |
721 | } |
722 | |
723 | return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries, |
724 | args, cacheTranslators ? "" + id : null, "" + id); |
725 | } |
726 | |
727 | private static String getServerTranspiled(String snippetID) throws IOException { |
728 | long id = parseSnippetID(snippetID); |
729 | URL url = new URL("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&id=" + id); |
730 | return loadPage(url); |
731 | } |
732 | |
733 | static void checkProgramSafety(String snippetID) throws IOException { |
734 | if (!safeOnly) return; |
735 | checkProgramSafetyImpl(snippetID); |
736 | } |
737 | |
738 | static void checkProgramSafetyImpl(String snippetID) throws IOException { |
739 | URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID)); |
740 | String text = loadPage(url); |
741 | if (!text.startsWith("{\"safe\":\"1\"}")) |
742 | throw new RuntimeException("Program not safe: #" + parseSnippetID(snippetID)); |
743 | } |
744 | |
745 | private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException { |
746 | if (verbose) |
747 | System.out.println("Assuming " + snippetID + " is a library."); |
748 | |
749 | if (libraryFile == null) { |
750 | byte[] data = loadDataSnippetImpl(snippetID); |
751 | DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data); |
752 | libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); |
753 | } |
754 | |
755 | if (!libraries_out.contains(libraryFile)) |
756 | libraries_out.add(libraryFile); |
757 | } |
758 | |
759 | private static byte[] loadDataSnippetImpl(String snippetID) throws IOException { |
760 | byte[] data; |
761 | try { |
762 | URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" |
763 | + parseSnippetID(snippetID) + "&contentType=application/binary"); |
764 | System.err.println("Loading library: " + url); |
765 | data = loadBinaryPage(url.openConnection()); |
766 | if (verbose) |
767 | System.err.println("Bytes loaded: " + data.length); |
768 | } catch (FileNotFoundException e) { |
769 | throw new IOException("Binary snippet #" + snippetID + " not found or not public"); |
770 | } |
771 | return data; |
772 | } |
773 | |
774 | /** returns output dir */ |
775 | private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput, |
776 | boolean silent, boolean runInProcess, |
777 | List<File> libraries, String[] args, String cacheAs, |
778 | String programID) throws Exception { |
779 | File srcDir = new File(ioBaseDir, "src"); |
780 | File inputDir = new File(ioBaseDir, "input"); |
781 | File outputDir = new File(ioBaseDir, "output"); |
782 | copyInput(originalSrcDir, srcDir); |
783 | copyInput(originalInput, inputDir); |
784 | javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID); |
785 | return outputDir; |
786 | } |
787 | |
788 | private static void copyInput(File src, File dst) throws IOException { |
789 | copyDirectory(src, dst); |
790 | } |
791 | |
792 | public static boolean hasFile(File inputDir, String name) { |
793 | return new File(inputDir, name).exists(); |
794 | } |
795 | |
796 | public static void copyDirectory(File src, File dst) throws IOException { |
797 | if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); |
798 | dst.mkdirs(); |
799 | File[] files = src.listFiles(); |
800 | if (files == null) return; |
801 | for (File file : files) { |
802 | File dst1 = new File(dst, file.getName()); |
803 | if (file.isDirectory()) |
804 | copyDirectory(file, dst1); |
805 | else { |
806 | if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); |
807 | copy(file, dst1); |
808 | } |
809 | } |
810 | } |
811 | |
812 | /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ |
813 | public static void copy(File src, File dest) throws IOException { |
814 | FileInputStream inputStream = newFileInputStream(src); |
815 | FileOutputStream outputStream = newFileOutputStream(dest); |
816 | try { |
817 | copy(inputStream, outputStream); |
818 | inputStream.close(); |
819 | } finally { |
820 | outputStream.close(); |
821 | } |
822 | } |
823 | |
824 | static Object call(Object o, String method, Object... args) { |
825 | try { |
826 | Method m = call_findMethod(o, method, args, false); |
827 | m.setAccessible(true); |
828 | return m.invoke(o, args); |
829 | } catch (Exception e) { |
830 | throw new RuntimeException(e); |
831 | } |
832 | } |
833 | |
834 | static Object call(Class c, String method, Object... args) { |
835 | try { |
836 | Method m = call_findStaticMethod(c, method, args, false); |
837 | m.setAccessible(true); |
838 | return m.invoke(null, args); |
839 | } catch (Exception e) { |
840 | throw new RuntimeException(e); |
841 | } |
842 | } |
843 | |
844 | static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) { |
845 | while (c != null) { |
846 | for (Method m : c.getDeclaredMethods()) { |
847 | if (debug) |
848 | System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; |
849 | if (!m.getName().equals(method)) { |
850 | if (debug) System.out.println("Method name mismatch: " + method); |
851 | continue; |
852 | } |
853 | |
854 | if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug)) |
855 | continue; |
856 | |
857 | return m; |
858 | } |
859 | c = c.getSuperclass(); |
860 | } |
861 | throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + c.getName()); |
862 | } |
863 | |
864 | static Method call_findMethod(Object o, String method, Object[] args, boolean debug) { |
865 | Class c = o.getClass(); |
866 | while (c != null) { |
867 | for (Method m : c.getDeclaredMethods()) { |
868 | if (debug) |
869 | System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; |
870 | if (m.getName().equals(method) && call_checkArgs(m, args, debug)) |
871 | return m; |
872 | } |
873 | c = c.getSuperclass(); |
874 | } |
875 | throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName()); |
876 | } |
877 | |
878 | private static boolean call_checkArgs(Method m, Object[] args, boolean debug) { |
879 | Class<?>[] types = m.getParameterTypes(); |
880 | if (types.length != args.length) { |
881 | if (debug) |
882 | System.out.println("checkArgs: Bad parameter length: " + args.length + " vs " + types.length); |
883 | return false; |
884 | } |
885 | for (int i = 0; i < types.length; i++) |
886 | if (!(args[i] == null || isInstanceX(types[i], args[i]))) { |
887 | if (debug) |
888 | System.out.println("checkArgs: Bad parameter " + i + ": " + args[i] + " vs " + types[i]); |
889 | return false; |
890 | } |
891 | return true; |
892 | } |
893 | |
894 | private static FileInputStream newFileInputStream(File f) throws FileNotFoundException { |
895 | /*if (androidContext != null) |
896 | return (FileInputStream) call(androidContext, |
897 | "openFileInput", f.getPath()); |
898 | else*/ |
899 | return new FileInputStream(f); |
900 | } |
901 | |
902 | private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException { |
903 | /*if (androidContext != null) |
904 | return (FileOutputStream) call(androidContext, |
905 | "openFileOutput", f.getPath(), 0); |
906 | else*/ |
907 | return new FileOutputStream(f); |
908 | } |
909 | |
910 | public static void copy(InputStream in, OutputStream out) throws IOException { |
911 | byte[] buf = new byte[65536]; |
912 | while (true) { |
913 | int n = in.read(buf); |
914 | if (n <= 0) return; |
915 | out.write(buf, 0, n); |
916 | } |
917 | } |
918 | |
919 | /** writes safely (to temp file, then rename) */ |
920 | public static void saveTextFile(String fileName, String contents) throws IOException { |
921 | File file = new File(fileName); |
922 | File parentFile = file.getParentFile(); |
923 | if (parentFile != null) |
924 | parentFile.mkdirs(); |
925 | String tempFileName = fileName + "_temp"; |
926 | FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName)); |
927 | OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); |
928 | PrintWriter printWriter = new PrintWriter(outputStreamWriter); |
929 | printWriter.print(contents); |
930 | printWriter.close(); |
931 | if (file.exists() && !file.delete()) |
932 | throw new IOException("Can't delete " + fileName); |
933 | |
934 | if (!new File(tempFileName).renameTo(file)) |
935 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
936 | } |
937 | |
938 | /** writes safely (to temp file, then rename) */ |
939 | public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { |
940 | File file = new File(fileName); |
941 | File parentFile = file.getParentFile(); |
942 | if (parentFile != null) |
943 | parentFile.mkdirs(); |
944 | String tempFileName = fileName + "_temp"; |
945 | FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName)); |
946 | fileOutputStream.write(contents); |
947 | fileOutputStream.close(); |
948 | if (file.exists() && !file.delete()) |
949 | throw new IOException("Can't delete " + fileName); |
950 | |
951 | if (!new File(tempFileName).renameTo(file)) |
952 | throw new IOException("Can't rename " + tempFileName + " to " + fileName); |
953 | } |
954 | |
955 | public static String loadTextFile(String fileName, String defaultContents) throws IOException { |
956 | if (!new File(fileName).exists()) |
957 | return defaultContents; |
958 | |
959 | FileInputStream fileInputStream = newFileInputStream(new File(fileName)); |
960 | InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles); |
961 | return loadTextFile(inputStreamReader, (int) new File(fileName).length()); |
962 | } |
963 | |
964 | public static String loadTextFile(Reader reader, int length) throws IOException { |
965 | try { |
966 | char[] chars = new char[length]; |
967 | int n = reader.read(chars); |
968 | return new String(chars, 0, n); |
969 | } finally { |
970 | reader.close(); |
971 | } |
972 | } |
973 | |
974 | static File DiskSnippetCache_dir; |
975 | |
976 | public static void initDiskSnippetCache(File dir) { |
977 | DiskSnippetCache_dir = dir; |
978 | dir.mkdirs(); |
979 | } |
980 | |
981 | // Data files are immutable, use centralized cache |
982 | public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException { |
983 | File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); |
984 | if (verbose) |
985 | System.out.println("Checking data cache: " + file.getPath()); |
986 | return file.exists() ? file : null; |
987 | } |
988 | |
989 | public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { |
990 | return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); |
991 | } |
992 | |
993 | private static File DiskSnippetCache_getFile(long snippetID) { |
994 | return new File(DiskSnippetCache_dir, "" + snippetID); |
995 | } |
996 | |
997 | public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { |
998 | saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); |
999 | } |
1000 | |
1001 | public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { |
1002 | saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); |
1003 | } |
1004 | |
1005 | public static File DiskSnippetCache_getDir() { |
1006 | return DiskSnippetCache_dir; |
1007 | } |
1008 | |
1009 | public static void initSnippetCache() { |
1010 | if (DiskSnippetCache_dir == null) |
1011 | initDiskSnippetCache(getGlobalCache()); |
1012 | } |
1013 | |
1014 | private static File getGlobalCache() { |
1015 | File file = new File(userHome(), ".tinybrain/snippet-cache"); |
1016 | file.mkdirs(); |
1017 | return file; |
1018 | } |
1019 | |
1020 | public static String loadSnippetVerified(String snippetID, String hash) throws IOException { |
1021 | String text = loadSnippet(snippetID); |
1022 | String realHash = getHash(text.getBytes("UTF-8")); |
1023 | if (!realHash.equals(hash)) { |
1024 | String msg; |
1025 | if (hash.isEmpty()) |
1026 | msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash; |
1027 | else |
1028 | msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??"; |
1029 | throw new RuntimeException(msg); |
1030 | } |
1031 | return text; |
1032 | } |
1033 | |
1034 | public static String getHash(byte[] data) { |
1035 | return bytesToHex(getFullFingerprint(data)); |
1036 | } |
1037 | |
1038 | public static byte[] getFullFingerprint(byte[] data) { |
1039 | try { |
1040 | return MessageDigest.getInstance("MD5").digest(data); |
1041 | } catch (NoSuchAlgorithmException e) { |
1042 | throw new RuntimeException(e); |
1043 | } |
1044 | } |
1045 | |
1046 | public static String bytesToHex(byte[] bytes) { |
1047 | return bytesToHex(bytes, 0, bytes.length); |
1048 | } |
1049 | |
1050 | public static String bytesToHex(byte[] bytes, int ofs, int len) { |
1051 | StringBuilder stringBuilder = new StringBuilder(len*2); |
1052 | for (int i = 0; i < len; i++) { |
1053 | String s = "0" + Integer.toHexString(bytes[ofs+i]); |
1054 | stringBuilder.append(s.substring(s.length()-2, s.length())); |
1055 | } |
1056 | return stringBuilder.toString(); |
1057 | } |
1058 | |
1059 | public static String loadSnippet(String snippetID) throws IOException { |
1060 | return loadSnippet(parseSnippetID(snippetID)); |
1061 | } |
1062 | |
1063 | public static long parseSnippetID(String snippetID) { |
1064 | return Long.parseLong(shortenSnippetID(snippetID)); |
1065 | } |
1066 | |
1067 | private static String shortenSnippetID(String snippetID) { |
1068 | if (snippetID.startsWith("#")) |
1069 | snippetID = snippetID.substring(1); |
1070 | String httpBlaBla = "http://tinybrain.de/"; |
1071 | if (snippetID.startsWith(httpBlaBla)) |
1072 | snippetID = snippetID.substring(httpBlaBla.length()); |
1073 | return snippetID; |
1074 | } |
1075 | |
1076 | public static boolean isSnippetID(String snippetID) { |
1077 | snippetID = shortenSnippetID(snippetID); |
1078 | return isInteger(snippetID) && Long.parseLong(snippetID) != 0; |
1079 | } |
1080 | |
1081 | public static boolean isInteger(String s) { |
1082 | return Pattern.matches("\\-?\\d+", s); |
1083 | } |
1084 | |
1085 | public static String loadSnippet(long snippetID) throws IOException { |
1086 | String text = memSnippetCache.get(snippetID); |
1087 | if (text != null) { |
1088 | if (verbose) |
1089 | System.out.println("Getting " + snippetID + " from mem cache"); |
1090 | return text; |
1091 | } |
1092 | |
1093 | initSnippetCache(); |
1094 | text = DiskSnippetCache_get(snippetID); |
1095 | if (preferCached && text != null) { |
1096 | if (verbose) |
1097 | System.out.println("Getting " + snippetID + " from disk cache (preferCached)"); |
1098 | return text; |
1099 | } |
1100 | |
1101 | String md5 = text != null ? md5(text) : "-"; |
1102 | if (text != null) { |
1103 | String hash = prefetched.get(snippetID); |
1104 | if (hash != null) { |
1105 | if (md5.equals(hash)) { |
1106 | memSnippetCache.put(snippetID, text); |
1107 | if (verbose) |
1108 | System.out.println("Getting " + snippetID + " from prefetched"); |
1109 | return text; |
1110 | } else |
1111 | prefetched.remove(snippetID); // (maybe this is not necessary) |
1112 | } |
1113 | } |
1114 | |
1115 | try { |
1116 | /*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); |
1117 | text = loadPage(url);*/ |
1118 | String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1"; |
1119 | if (text != null) { |
1120 | //System.err.println("MD5: " + md5); |
1121 | theURL += "&md5=" + md5; |
1122 | } |
1123 | URL url = new URL(theURL); |
1124 | String page = loadPage(url); |
1125 | |
1126 | // parse & drop transpilation flag available line |
1127 | int i = page.indexOf('\n'); |
1128 | boolean hasTranspiled = page.substring(0, i).trim().equals("1"); |
1129 | if (hasTranspiled) |
1130 | hasTranspiledSet.add(snippetID); |
1131 | else |
1132 | hasTranspiledSet.remove(snippetID); |
1133 | page = page.substring(i+1); |
1134 | |
1135 | if (page.startsWith("==*#*==")) { |
1136 | // same, keep text |
1137 | //System.err.println("Snippet unchanged, keeping."); |
1138 | } else { |
1139 | // drop md5 line |
1140 | i = page.indexOf('\n'); |
1141 | String hash = page.substring(0, i).trim(); |
1142 | text = page.substring(i+1); |
1143 | |
1144 | String myHash = md5(text); |
1145 | if (myHash.equals(hash)) { |
1146 | //System.err.println("Hash match: " + hash); |
1147 | } else |
1148 | System.err.println("Hash mismatch"); |
1149 | } |
1150 | } catch (FileNotFoundException e) { |
1151 | e.printStackTrace(); |
1152 | throw new IOException("Snippet #" + snippetID + " not found or not public"); |
1153 | } |
1154 | |
1155 | memSnippetCache.put(snippetID, text); |
1156 | |
1157 | try { |
1158 | initSnippetCache(); |
1159 | DiskSnippetCache_put(snippetID, text); |
1160 | } catch (IOException e) { |
1161 | System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); |
1162 | } |
1163 | |
1164 | return text; |
1165 | } |
1166 | |
1167 | private static String md5(String text) { |
1168 | try { |
1169 | return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it... |
1170 | } catch (UnsupportedEncodingException e) { |
1171 | throw new RuntimeException(e); |
1172 | } |
1173 | } |
1174 | |
1175 | public static byte[] md5impl(byte[] data) { |
1176 | try { |
1177 | return MessageDigest.getInstance("MD5").digest(data); |
1178 | } catch (NoSuchAlgorithmException e) { |
1179 | throw new RuntimeException(e); |
1180 | } |
1181 | } |
1182 | |
1183 | private static String loadPage(URL url) throws IOException { |
1184 | System.err.println("Loading: " + url.toExternalForm()); |
1185 | URLConnection con = url.openConnection(); |
1186 | return loadPage(con, url); |
1187 | } |
1188 | |
1189 | public static String loadPage(URLConnection con, URL url) throws IOException { |
1190 | setHeaders(con); |
1191 | String contentType = con.getContentType(); |
1192 | if (contentType == null) |
1193 | throw new IOException("Page could not be read: " + url); |
1194 | //Log.info("Content-Type: " + contentType); |
1195 | String charset = guessCharset(contentType); |
1196 | //System.err.println("Charset: " + charset); |
1197 | Reader r = new InputStreamReader(con.getInputStream(), charset); |
1198 | StringBuilder buf = new StringBuilder(); |
1199 | while (true) { |
1200 | int ch = r.read(); |
1201 | if (ch < 0) |
1202 | break; |
1203 | //Log.info("Chars read: " + buf.length()); |
1204 | buf.append((char) ch); |
1205 | } |
1206 | return buf.toString(); |
1207 | } |
1208 | |
1209 | public static byte[] loadBinaryPage(URLConnection con) throws IOException { |
1210 | setHeaders(con); |
1211 | return loadBinaryPage_noHeaders(con); |
1212 | } |
1213 | |
1214 | private static byte[] loadBinaryPage_noHeaders(URLConnection con) throws IOException { |
1215 | ByteArrayOutputStream buf = new ByteArrayOutputStream(); |
1216 | InputStream inputStream = con.getInputStream(); |
1217 | while (true) { |
1218 | int ch = inputStream.read(); |
1219 | if (ch < 0) |
1220 | break; |
1221 | buf.write(ch); |
1222 | } |
1223 | inputStream.close(); |
1224 | return buf.toByteArray(); |
1225 | } |
1226 | |
1227 | private static void setHeaders(URLConnection con) throws IOException { |
1228 | String computerID = getComputerID(); |
1229 | if (computerID != null) |
1230 | con.setRequestProperty("X-ComputerID", computerID); |
1231 | } |
1232 | |
1233 | public static String guessCharset(String contentType) { |
1234 | Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); |
1235 | Matcher m = p.matcher(contentType); |
1236 | /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ |
1237 | return m.matches() ? m.group(1) : "ISO-8859-1"; |
1238 | } |
1239 | |
1240 | /** runs a transpiled set of sources */ |
1241 | public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess, |
1242 | List<File> libraries, String[] args, String cacheAs, |
1243 | String programID) throws Exception { |
1244 | if (android) |
1245 | javax2android(srcDir, args, programID); |
1246 | else { |
1247 | File classesDir = TempDirMaker_make(); |
1248 | String javacOutput = compileJava(srcDir, libraries, classesDir); |
1249 | |
1250 | // run |
1251 | |
1252 | if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath() |
1253 | + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n"); |
1254 | runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID); |
1255 | } |
1256 | } |
1257 | |
1258 | static void javax2android(File srcDir, String[] args, String programID) throws Exception { |
1259 | byte[] dexData; |
1260 | String isTranspiled = /*loadTextFile(new File(srcDir, "is-transpiled").getPath(), null)*/null; |
1261 | if (isTranspiled != null) { |
1262 | URL url = new URL("http://tinybrain.de:8080/dexcompile.php?id=" + isTranspiled + "&transOnly=1"); |
1263 | dexData = loadBinaryPage(url.openConnection()); |
1264 | } else { |
1265 | URL url = new URL("http://tinybrain.de:8080/dexcompile.php"); |
1266 | URLConnection conn = url.openConnection(); |
1267 | String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8"); |
1268 | dexData = doPostBinary(postData, conn); |
1269 | } |
1270 | |
1271 | javaAndroidGo(dexData, programID, args); |
1272 | } |
1273 | |
1274 | static Class<?> mainClass; |
1275 | |
1276 | static void javaAndroidGo(byte[] dexData, String programID, String[] args) throws Exception { |
1277 | if (!isDex(dexData)) |
1278 | throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8")); |
1279 | System.out.println("Dex loaded: " + dexData.length + "b"); |
1280 | |
1281 | File dexDir = TempDirMaker_make(); |
1282 | File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex"); |
1283 | File dexOutputDir = TempDirMaker_make_internal(); |
1284 | |
1285 | //System.out.println("Saving dex to: " + dexDir.getAbsolutePath()); |
1286 | try { |
1287 | saveBinaryFile(dexFile.getPath(), dexData); |
1288 | } catch (Throwable e) { |
1289 | System.out.println("Whoa!"); |
1290 | throw new RuntimeException(e); |
1291 | } |
1292 | |
1293 | //System.out.println("Getting parent class loader."); |
1294 | ClassLoader parentClassLoader = |
1295 | //ClassLoader.getSystemClassLoader(); // does not find support jar |
1296 | //getClass().getClassLoader(); // Let's try this... |
1297 | x19.class.getClassLoader().getParent(); // XXX ! |
1298 | |
1299 | //System.out.println("Making DexClassLoader."); |
1300 | //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null, |
1301 | // parentClassLoader); |
1302 | Class dcl = Class.forName("dalvik.system.DexClassLoader"); |
1303 | Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null, |
1304 | parentClassLoader); |
1305 | |
1306 | System.out.println("Loading main class."); |
1307 | //Class<?> theClass = classLoader.loadClass(mainClassName); |
1308 | Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main"); |
1309 | mainClass = theClass; |
1310 | |
1311 | //System.out.println("Main class loaded."); |
1312 | try { |
1313 | set(theClass, "androidContext", androidContext); |
1314 | } catch (Throwable e) {} |
1315 | |
1316 | try { |
1317 | set(theClass, "programID", programID); |
1318 | } catch (Throwable e) {} |
1319 | |
1320 | Method main = null; |
1321 | try { |
1322 | main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false); |
1323 | } catch (RuntimeException e) { |
1324 | } |
1325 | |
1326 | //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main); |
1327 | |
1328 | if (main != null) { |
1329 | // old style main program that returns a View |
1330 | System.out.println("Calling main (old-style)"); |
1331 | Object view = main.invoke(null, androidContext); |
1332 | System.out.println("Calling setContentView with " + view); |
1333 | call(Class.forName("main"), "setContentViewInUIThread", view); |
1334 | //call(androidContext, "setContentView", view); |
1335 | System.out.println("Done."); |
1336 | } else { |
1337 | System.out.println("New-style main method running.\n\n====\n"); |
1338 | runMainMethod(args, theClass); |
1339 | } |
1340 | } |
1341 | |
1342 | static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 }; |
1343 | |
1344 | static boolean isDex(byte[] dexData) { |
1345 | if (dexData.length < DEX_FILE_MAGIC.length) return false; |
1346 | for (int i = 0; i < DEX_FILE_MAGIC.length; i++) |
1347 | if (dexData[i] != DEX_FILE_MAGIC[i]) |
1348 | return false; |
1349 | return true; |
1350 | } |
1351 | |
1352 | static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException { |
1353 | // connect and do POST |
1354 | setHeaders(conn); |
1355 | conn.setDoOutput(true); |
1356 | |
1357 | OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); |
1358 | writer.write(urlParameters); |
1359 | writer.flush(); |
1360 | |
1361 | byte[] contents = loadBinaryPage_noHeaders(conn); |
1362 | writer.close(); |
1363 | return contents; |
1364 | } |
1365 | |
1366 | static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException { |
1367 | ++compilations; |
1368 | |
1369 | // collect sources |
1370 | |
1371 | List<File> sources = new ArrayList<File>(); |
1372 | if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); |
1373 | scanForSources(srcDir, sources, true); |
1374 | if (sources.isEmpty()) |
1375 | throw new IOException("No sources found"); |
1376 | |
1377 | // compile |
1378 | |
1379 | File optionsFile = File.createTempFile("javax", ""); |
1380 | if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); |
1381 | String options = "-d " + bashQuote(classesDir.getPath()); |
1382 | writeOptions(sources, libraries, optionsFile, options); |
1383 | classesDir.mkdirs(); |
1384 | return invokeJavaCompiler(optionsFile); |
1385 | } |
1386 | |
1387 | private static void runProgram(String javacOutput, File classesDir, File ioBaseDir, |
1388 | boolean silent, boolean runInProcess, |
1389 | List<File> libraries, String[] args, String cacheAs, |
1390 | String programID) throws Exception { |
1391 | // print javac output if compile failed and it hasn't been printed yet |
1392 | boolean didNotCompile = !didCompile(classesDir); |
1393 | if (verbose || didNotCompile) |
1394 | System.out.println(javacOutput); |
1395 | if (didNotCompile) |
1396 | return; |
1397 | |
1398 | if (runInProcess |
1399 | || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) { |
1400 | runProgramQuick(classesDir, libraries, args, cacheAs, programID); |
1401 | return; |
1402 | } |
1403 | |
1404 | boolean echoOK = false; |
1405 | // TODO: add libraries to class path |
1406 | String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " |
1407 | + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; |
1408 | if (verbose) System.out.println(bashCmd); |
1409 | String output = backtick(bashCmd); |
1410 | lastOutput = output; |
1411 | if (verbose || !silent) |
1412 | System.out.println(output); |
1413 | } |
1414 | |
1415 | static boolean didCompile(File classesDir) { |
1416 | return hasFile(classesDir, "main.class"); |
1417 | } |
1418 | |
1419 | private static void runProgramQuick(File classesDir, List<File> libraries, |
1420 | String[] args, String cacheAs, |
1421 | String programID) throws Exception { |
1422 | // collect urls |
1423 | URL[] urls = new URL[libraries.size()+1]; |
1424 | urls[0] = classesDir.toURI().toURL(); |
1425 | for (int i = 0; i < libraries.size(); i++) |
1426 | urls[i+1] = libraries.get(i).toURI().toURL(); |
1427 | |
1428 | // make class loader |
1429 | URLClassLoader classLoader = new URLClassLoader(urls); |
1430 | |
1431 | // load JavaX main class |
1432 | Class<?> mainClass = classLoader.loadClass("main"); |
1433 | |
1434 | if (cacheAs != null) |
1435 | programCache.put(cacheAs, mainClass); |
1436 | |
1437 | try { |
1438 | set(mainClass, "programID", programID); |
1439 | } catch (Throwable e) {} |
1440 | |
1441 | runMainMethod(args, mainClass); |
1442 | } |
1443 | |
1444 | |
1445 | static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { |
1446 | Method main = mainClass.getMethod("main", String[].class); |
1447 | main.invoke(null, args); |
1448 | } |
1449 | |
1450 | private static String invokeJavaCompiler(File optionsFile) throws IOException { |
1451 | String output; |
1452 | if (hasEcj() && !javacOnly) |
1453 | output = invokeEcj(optionsFile); |
1454 | else |
1455 | output = invokeJavac(optionsFile); |
1456 | if (verbose) System.out.println(output); |
1457 | return output; |
1458 | } |
1459 | |
1460 | private static boolean hasEcj() { |
1461 | try { |
1462 | Class.forName("org.eclipse.jdt.internal.compiler.batch.Main"); |
1463 | return true; |
1464 | } catch (ClassNotFoundException e) { |
1465 | return false; |
1466 | } |
1467 | } |
1468 | |
1469 | private static String invokeJavac(File optionsFile) throws IOException { |
1470 | String output; |
1471 | output = backtick("javac " + bashQuote("@" + optionsFile.getPath())); |
1472 | if (exitValue != 0) { |
1473 | System.out.println(output); |
1474 | throw new RuntimeException("javac returned errors."); |
1475 | } |
1476 | return output; |
1477 | } |
1478 | |
1479 | // throws ClassNotFoundException if ecj is not in classpath |
1480 | static String invokeEcj(File optionsFile) { |
1481 | try { |
1482 | StringWriter writer = new StringWriter(); |
1483 | PrintWriter printWriter = new PrintWriter(writer); |
1484 | |
1485 | // add more eclipse options in the line below |
1486 | |
1487 | String[] args = {"@" + optionsFile.getPath(), |
1488 | "-source", "1.7", |
1489 | "-nowarn" |
1490 | }; |
1491 | |
1492 | Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main"); |
1493 | Object main = newInstance(ecjClass, printWriter, printWriter, false); |
1494 | call(main, "compile", new Object[]{args}); |
1495 | int errors = (Integer) get(main, "globalErrorsCount"); |
1496 | |
1497 | String output = writer.toString(); |
1498 | if (errors != 0) { |
1499 | System.out.println(output); |
1500 | throw new RuntimeException("Java compiler returned errors."); |
1501 | } |
1502 | return output; |
1503 | } catch (Exception e) { |
1504 | throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); |
1505 | } |
1506 | } |
1507 | |
1508 | static Object get(Object o, String field) { |
1509 | try { |
1510 | Field f = findField(o.getClass(), field); |
1511 | f.setAccessible(true); |
1512 | return f.get(o); |
1513 | } catch (Exception e) { |
1514 | throw new RuntimeException(e); |
1515 | } |
1516 | } |
1517 | |
1518 | static Object newInstance(Class c, Object... args) { try { |
1519 | Constructor m = findConstructor(c, args); |
1520 | m.setAccessible(true); |
1521 | return m.newInstance(args); |
1522 | } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} |
1523 | |
1524 | static Constructor findConstructor(Class c, Object... args) { |
1525 | for (Constructor m : c.getDeclaredConstructors()) { |
1526 | if (!checkArgs(m.getParameterTypes(), args, verbose)) |
1527 | continue; |
1528 | return m; |
1529 | } |
1530 | throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName()); |
1531 | } |
1532 | |
1533 | static boolean checkArgs(Class[] types, Object[] args, boolean debug) { |
1534 | if (types.length != args.length) { |
1535 | if (debug) |
1536 | System.out.println("Bad parameter length: " + args.length + " vs " + types.length); |
1537 | return false; |
1538 | } |
1539 | for (int i = 0; i < types.length; i++) |
1540 | if (!(args[i] == null || isInstanceX(types[i], args[i]))) { |
1541 | if (debug) |
1542 | System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); |
1543 | return false; |
1544 | } |
1545 | return true; |
1546 | } |
1547 | |
1548 | // extended to handle primitive types |
1549 | private static boolean isInstanceX(Class type, Object arg) { |
1550 | if (type == boolean.class) return arg instanceof Boolean; |
1551 | if (type == int.class) return arg instanceof Integer; |
1552 | if (type == long.class) return arg instanceof Long; |
1553 | if (type == float.class) return arg instanceof Float; |
1554 | if (type == short.class) return arg instanceof Short; |
1555 | if (type == char.class) return arg instanceof Character; |
1556 | if (type == byte.class) return arg instanceof Byte; |
1557 | return type.isInstance(arg); |
1558 | } |
1559 | |
1560 | private static void writeOptions(List<File> sources, List<File> libraries, |
1561 | File optionsFile, String moreOptions) throws IOException { |
1562 | FileWriter writer = new FileWriter(optionsFile); |
1563 | for (File source : sources) |
1564 | writer.write(bashQuote(source.getPath()) + " "); |
1565 | if (!libraries.isEmpty()) { |
1566 | List<String> cp = new ArrayList<String>(); |
1567 | for (File lib : libraries) |
1568 | cp.add(lib.getAbsolutePath()); |
1569 | writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " "); |
1570 | } |
1571 | writer.write(moreOptions); |
1572 | writer.close(); |
1573 | } |
1574 | |
1575 | static void scanForSources(File source, List<File> sources, boolean topLevel) { |
1576 | if (source.isFile() && source.getName().endsWith(".java")) |
1577 | sources.add(source); |
1578 | else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { |
1579 | File[] files = source.listFiles(); |
1580 | for (File file : files) |
1581 | scanForSources(file, sources, false); |
1582 | } |
1583 | } |
1584 | |
1585 | private static boolean isSkippedDirectoryName(String name, boolean topLevel) { |
1586 | 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.) |
1587 | return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); |
1588 | } |
1589 | |
1590 | static int exitValue; |
1591 | public static String backtick(String cmd) throws IOException { |
1592 | ++processesStarted; |
1593 | File outFile = File.createTempFile("_backtick", ""); |
1594 | File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : ""); |
1595 | |
1596 | String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1"; |
1597 | //Log.info("[Backtick] " + command); |
1598 | try { |
1599 | saveTextFile(scriptFile.getPath(), command); |
1600 | String[] command2; |
1601 | if (isWindows()) |
1602 | command2 = new String[] { scriptFile.getPath() }; |
1603 | else |
1604 | command2 = new String[] { "/bin/bash", scriptFile.getPath() }; |
1605 | Process process = Runtime.getRuntime().exec(command2); |
1606 | try { |
1607 | process.waitFor(); |
1608 | } catch (InterruptedException e) { |
1609 | throw new RuntimeException(e); |
1610 | } |
1611 | exitValue = process.exitValue(); |
1612 | if (verbose) |
1613 | System.out.println("Process return code: " + exitValue); |
1614 | return loadTextFile(outFile.getPath(), ""); |
1615 | } finally { |
1616 | scriptFile.delete(); |
1617 | } |
1618 | } |
1619 | |
1620 | /** possibly improvable */ |
1621 | public static String javaQuote(String text) { |
1622 | return bashQuote(text); |
1623 | } |
1624 | |
1625 | /** possibly improvable */ |
1626 | public static String bashQuote(String text) { |
1627 | if (text == null) return null; |
1628 | return "\"" + text |
1629 | .replace("\\", "\\\\") |
1630 | .replace("\"", "\\\"") |
1631 | .replace("\n", "\\n") |
1632 | .replace("\r", "\\r") + "\""; |
1633 | } |
1634 | |
1635 | public final static String charsetForTextFiles = "UTF8"; |
1636 | |
1637 | static long TempDirMaker_lastValue; |
1638 | |
1639 | public static File TempDirMaker_make() { |
1640 | File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue()); |
1641 | dir.mkdirs(); |
1642 | return dir; |
1643 | } |
1644 | |
1645 | public static File TempDirMaker_make_internal() { |
1646 | File dir = new File(userHomeInternal(), ".javax/" + TempDirMaker_newValue()); |
1647 | dir.mkdirs(); |
1648 | return dir; |
1649 | } |
1650 | |
1651 | private static long TempDirMaker_newValue() { |
1652 | long value; |
1653 | do |
1654 | value = System.currentTimeMillis(); |
1655 | while (value == TempDirMaker_lastValue); |
1656 | TempDirMaker_lastValue = value; |
1657 | return value; |
1658 | } |
1659 | |
1660 | public static String join(String glue, Iterable<String> strings) { |
1661 | StringBuilder buf = new StringBuilder(); |
1662 | Iterator<String> i = strings.iterator(); |
1663 | if (i.hasNext()) { |
1664 | buf.append(i.next()); |
1665 | while (i.hasNext()) |
1666 | buf.append(glue).append(i.next()); |
1667 | } |
1668 | return buf.toString(); |
1669 | } |
1670 | |
1671 | public static boolean isWindows() { |
1672 | return System.getProperty("os.name").contains("Windows"); |
1673 | } |
1674 | |
1675 | public static String makeRandomID(int length) { |
1676 | Random random = new Random(); |
1677 | char[] id = new char[length]; |
1678 | for (int i = 0; i< id.length; i++) |
1679 | id[i] = (char) ((int) 'a' + random.nextInt(26)); |
1680 | return new String(id); |
1681 | } |
1682 | |
1683 | static String computerID; |
1684 | public static String getComputerID() throws IOException { |
1685 | if (noID) return null; |
1686 | if (computerID == null) { |
1687 | File file = new File(userHome(), ".tinybrain/computer-id"); |
1688 | computerID = loadTextFile(file.getPath(), null); |
1689 | if (computerID == null) { |
1690 | computerID = makeRandomID(12); |
1691 | saveTextFile(file.getPath(), computerID); |
1692 | } |
1693 | if (verbose) |
1694 | System.out.println("Local computer ID: " + computerID); |
1695 | } |
1696 | return computerID; |
1697 | } |
1698 | |
1699 | static int fileDeletions; |
1700 | |
1701 | static void cleanCache() { |
1702 | if (verbose) |
1703 | System.out.println("Cleaning cache"); |
1704 | fileDeletions = 0; |
1705 | File javax = new File(userHome(), ".javax"); |
1706 | long now = System.currentTimeMillis(); |
1707 | File[] files = javax.listFiles(); |
1708 | if (files != null) for (File dir : files) { |
1709 | if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) { |
1710 | long time = Long.parseLong(dir.getName()); |
1711 | long seconds = (now - time) / 1000; |
1712 | long minutes = seconds / 60; |
1713 | long hours = minutes / 60; |
1714 | if (hours >= 1) { |
1715 | //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h"); |
1716 | removeDir(dir); |
1717 | } |
1718 | } |
1719 | } |
1720 | if (verbose && fileDeletions != 0) |
1721 | System.out.println("Cleaned cache. File deletions: " + fileDeletions); |
1722 | } |
1723 | |
1724 | static void removeDir(File dir) { |
1725 | if (dir.getAbsolutePath().indexOf(".javax") < 0) // security check! |
1726 | return; |
1727 | for (File f : dir.listFiles()) { |
1728 | if (f.isDirectory()) |
1729 | removeDir(f); |
1730 | else { |
1731 | if (verbose) |
1732 | System.out.println("Deleting " + f.getAbsolutePath()); |
1733 | f.delete(); |
1734 | ++fileDeletions; |
1735 | } |
1736 | } |
1737 | dir.delete(); |
1738 | } |
1739 | |
1740 | static void showSystemProperties() { |
1741 | System.out.println("System properties:\n"); |
1742 | for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) { |
1743 | System.out.println(" " + entry.getKey() + " = " + entry.getValue()); |
1744 | } |
1745 | System.out.println(); |
1746 | } |
1747 | |
1748 | static void showVersion() { |
1749 | //showSystemProperties(); |
1750 | boolean eclipseFound = hasEcj(); |
1751 | //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version"); |
1752 | String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version"); |
1753 | String os = System.getProperty("os.name"), arch = System.getProperty("os.arch"); |
1754 | System.out.println("This is " + version + "."); |
1755 | System.out.println("[Details: " + |
1756 | (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)") |
1757 | + ", " + platform + ", " + arch + ", " + os + "]"); |
1758 | } |
1759 | |
1760 | static boolean isAndroid() { |
1761 | return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; |
1762 | } |
1763 | |
1764 | static void set(Class c, String field, Object value) { |
1765 | try { |
1766 | Field f = findStaticField(c, field); |
1767 | f.setAccessible(true); |
1768 | f.set(null, value); |
1769 | } catch (Exception e) { |
1770 | throw new RuntimeException(e); |
1771 | } |
1772 | } |
1773 | |
1774 | static Field findStaticField(Class<?> c, String field) { |
1775 | for (Field f : c.getDeclaredFields()) |
1776 | if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) |
1777 | return f; |
1778 | throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); |
1779 | } |
1780 | |
1781 | static Field findField(Class<?> c, String field) { |
1782 | for (Field f : c.getDeclaredFields()) |
1783 | if (f.getName().equals(field)) |
1784 | return f; |
1785 | throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); |
1786 | } |
1787 | } |
Began life as a copy of #676
download show line numbers debug dex old transpilations
Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #1001209 |
Snippet name: | Default boot-up code for JavaX/Android 26 (backup) |
Eternal ID of this version: | #1001209/1 |
Text MD5: | 4cf4b204f287f5df40810b1696b494ac |
Author: | stefan |
Category: | javax |
Type: | JavaX source code (Android) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-09-30 20:24:36 |
Source code size: | 63605 bytes / 1787 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 772 / 656 |
Referenced in: | [show references] |