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

127
LINES

< > BotCompany Repo | #564 // isCompilable (JavaX)

JavaX source code - run with: x30.jar

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/** isCompilable */
public class main {
  public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    File srcDir = new File("input");
    List<File> sources = new ArrayList<File>();
    System.out.println("Scanning for sources in " + srcDir.getPath());
    scanForSources(srcDir, sources);
    File optionsFile = File.createTempFile("javax", "");
    File classesDir = new File(System.getProperty("user.home"), ".javax/" + System.currentTimeMillis());
    System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
    String options = "-d " + bashQuote(classesDir.getPath());
    writeOptions(sources, optionsFile, options);
    classesDir.mkdirs();
    invokeJavac(optionsFile);
    boolean isCompilable = new File(classesDir, "main.class").exists();
    System.out.println("Compilable: " + isCompilable);
    saveTextFile(isCompilable ? "output/is-compilable" : "output/is-not-compilable", "x");
  }

  private static void invokeJavac(File optionsFile) throws IOException {
    String javacOutput = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
    System.out.println(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) {
    if (source.isFile() && source.getName().endsWith(".java"))
      sources.add(source);
    else if (source.isDirectory()) {
      File[] files = source.listFiles();
      for (File file : files)
        scanForSources(file, sources);
    }
  }

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

  /** possoibly 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";

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

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: #564
Snippet name: isCompilable (JavaX)
Eternal ID of this version: #564/1
Text MD5: 7c44c0023a32bd252d038c3a90b5c9e5
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-04-10 21:47:27
Source code size: 5062 bytes / 127 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 639 / 596
Referenced in: [show references]