Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

487
LINES

< > BotCompany Repo | #594 // x7.java

Java source code

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

download  show line numbers   

Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

Comments [hide]

ID Author/Program Comment Date
402 #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.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
Changes to v6:
-v2mode stuff removed
-compiler errors are automatically printed if compilation fails

Still Linux only. (Where are the Windows porters?)
*/

public class x7 {
static boolean verbose = false;

static List<String> translators = new ArrayList<String>();

public static void main(String[] args) throws IOException {
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"))
verbose = true;
else if (arg.equals("-finderror"))
verbose = true;
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"))
translators.add(args[++i]);
else
src = arg;
}

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);

if (outputDir != null) {
copyInput(new File(ioBaseDir, "output"), outputDir);
System.out.println("Output copied to: " + outputDir.getAbsolutePath());
}
}

public static void javax4(String src, File ioDir) throws IOException {
File srcDir;
if (isSnippetID(src))
srcDir = loadSnippetAsMainJava(src);
else
srcDir = new File(src);
File X = programToInput(srcDir);

X = applyTranslators(X);

File Y = luaPrintToJavaPrint(X);
javax2(Y, ioDir, false);
}

private static File applyTranslators(File x) throws IOException {
for (String translator : translators) {
if (verbose)
System.out.println("Using translator " + translator + " on sources in " + x.getPath());
File newDir = runJavaX2_src_from_snippet(translator, null, x, true);
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, false));
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 runJavaX2_src_from_snippet(String snippetID, String hash, File input, boolean silent) throws IOException {
File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
: loadSnippetAsMainJavaVerified(snippetID, hash);
return runJavaX(srcDir, input, silent);
}

/** returns output dir */
private static File runJavaX(File originalSrcDir, File originalInput, boolean silent) throws IOException {
File ioBaseDir = TempDirMaker_make();
File srcDir = new File(ioBaseDir, "src");
File inputDir = new File(ioBaseDir, "input");
File input = inputDir;
File outputDir = new File(ioBaseDir, "output");
File output = outputDir;
copyInput(originalSrcDir, srcDir);
copyInput(originalInput, input);
javax2(srcDir, ioBaseDir, silent);
return output;
}

private static void copyInput(File src, File dst) throws IOException {
copyDirectory(src, dst);
}

private static File programToInput(File srcDir) {
return srcDir;
}

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);
}

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();
}

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 File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}

public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
}

public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
String text = loadSnippet(snippetID, !hash.isEmpty());
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, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}

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, boolean preferCached) throws IOException {
if (preferCached) {
initSnippetCache();
String text = DiskSnippetCache_get(snippetID);
if (text != null)
return text;
}

String 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");
}

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.out.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 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";
}

public static void javax2(File srcDir, File ioBaseDir, boolean silent) throws IOException {
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;
}
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, optionsFile, options);
classesDir.mkdirs();
String javacOutput = invokeJavac(optionsFile);
if (verbose) System.out.println("Running program (class main.java)\n");
runProgram(javacOutput, classesDir, ioBaseDir, silent);
}

private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
boolean silent) throws IOException {
// print javac output if compile failed and it hasn't been printed yet
if (!verbose && !hasFile(classesDir, "main.class"))
System.out.println(javacOutput);

boolean echoOK = false;
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 (!silent)
System.out.println(output);
}

private static String invokeJavac(File optionsFile) throws IOException {
String javacOutput = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
if (verbose) System.out.println(javacOutput);
return javacOutput;
}

private static void writeOptions(List<File> sources, File sourcesFile, String moreOptions) throws IOException {
FileWriter writer = new FileWriter(sourcesFile);
for (File source : sources)
writer.write(bashQuote(source.getPath()) + " ");
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 {
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);
}
int value = process.exitValue();
//Log.info("exit value: " + value);
return loadTextFile(outFile.getPath(), "");
} finally {
scriptFile.delete();
}
}

/** 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;
}
}

}}
2015-08-18 12:29:31  delete 
400 #1000604 (pitcher) 2015-08-18 00:07:22

add comment

Snippet ID: #594
Snippet name: x7.java
Eternal ID of this version: #594/1
Text MD5: a16b96d171108ac4c34f608cce46f12d
Author: stefan
Category: javax
Type: Java source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-04-28 19:01:48
Source code size: 17606 bytes / 487 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1044 / 168
Referenced in: [show references]