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

157
LINES

< > BotCompany Repo | #581 // x1.java (JavaX Level 1)

Java source code

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;

/**
 * javax by Stefan Reich (www.superinformatiker.de, info@superinformatiker.de)
 *
 * jaxax compiles and runs a bunch of Java sources in one step.
 *
 * Syntax:
 *   javax         (searches for sources in current dir)
 *   javax srcdir  (searches in given directory)
 *
 * Main class must be called "main" in default package.
 *
 * Requirements:
 *   Java 6 or higher - JDK (javac) must be in path
 *
 * Limitations:
 *   Linux only, right now (invokes bash to call javac)
 *   Can't pass arguments to invoked program yet (would be easy to add)
 *
 * TODO: delete .class files at program end
 */

 public class x1 {
  public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    File srcDir = new File(args.length == 0 ? "." : args[0]);
    List<File> sources = new ArrayList<File>();
    System.out.println("Scanning for sources in " + srcDir.getPath());
    scanForSources(srcDir, sources);
    if (sources.isEmpty()) {
      System.out.println("No sources found");
      return;
    }
    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);
    System.out.println("Running program (class main.java)\n");
    runProgram(classesDir);
  }

  private static void runProgram(File classesDir) throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    URLClassLoader classLoader = new URLClassLoader(new URL[]{classesDir.toURI().toURL()});
    Class<?> mainClass = classLoader.loadClass("main");
    Method main = mainClass.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[0]);
  }

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

Author comment

Same as #562, just different class name ("x1" rather than "javax"). Think it's clearer that way.

download  show line numbers   

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

No comments. add comment

Snippet ID: #581
Snippet name: x1.java (JavaX Level 1)
Eternal ID of this version: #581/1
Text MD5: 792b1f3dc0b66cb1c2fd7cdb6b860776
Author: stefan
Category:
Type: Java source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-04-20 21:06:09
Source code size: 6106 bytes / 157 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 730 / 173
Referenced in: [show references]