Advertisement
Guest User

JavaCodeGenerator.java

a guest
May 4th, 2024
28
0
338 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.87 KB | Source Code | 0 0
  1. import java.io.BufferedWriter;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStreamWriter;
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.UUID;
  12.  
  13. public class JavaCodeGenerator {
  14.     private static List<String> generateSource(String className, Map<String, String> fields)
  15.     throws IllegalArgumentException {
  16.         if (!validName(className)) { throw new IllegalArgumentException("className"); }
  17.         if (fields == null) { throw new IllegalArgumentException("fields"); }
  18.         final List<String> source = new ArrayList<>();
  19.         source.add(String.format("public class %s {", className));
  20.         for (Map.Entry<String, String> pair : fields.entrySet()) {
  21.           if (!validName(pair.getKey())) { throw new IllegalArgumentException("fields"); }
  22.           source.add("");
  23.           source.add(String.format("    public %s %s;", pair.getValue(), pair.getKey()));
  24.         }
  25.         source.add("}");
  26.         return source;
  27.     }
  28.  
  29.     private static String buildClassFile(String className, List<String> source, String path)
  30.     throws IllegalArgumentException, IOException, InterruptedException {
  31.         if (!validName(className)) { throw new IllegalArgumentException("className"); }
  32.         if (source == null || source.isEmpty()) { throw new IllegalArgumentException("source"); }
  33.         if (path == null || path.isEmpty()) { throw new IllegalArgumentException("path"); }
  34.         final File directory = new File(path,  UUID.randomUUID().toString());
  35.         directory.mkdir();
  36.         final File sourceFile = new File(directory, className + ".java");
  37.         try (
  38.             FileOutputStream fos = new FileOutputStream(sourceFile);
  39.             OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
  40.             BufferedWriter bw = new BufferedWriter(osw)
  41.         ) {
  42.             for (String line : source) {
  43.                 bw.write(line);
  44.                 bw.newLine();
  45.             }
  46.         } catch (IOException ex) {
  47.             throw ex;
  48.         }
  49.         if (sourceFile.exists()) {
  50.             final String fs = System.getProperty("file.separator");
  51.             final Process process = new ProcessBuilder(
  52.                 System.getenv("JAVA_HOME") + fs + "bin" + fs + "javac",
  53.                 "-source",
  54.                 "8",
  55.                 "-target",
  56.                 "8",
  57.                 "-encoding",
  58.                 "utf8",
  59.                 "-cp",
  60.                 directory.getAbsolutePath(),
  61.                 "-d",
  62.                 directory.getAbsolutePath(),
  63.                 sourceFile.getAbsolutePath()
  64.             ).start();
  65.             final int exitCode = process.waitFor();
  66.             sourceFile.delete();
  67.             if (exitCode != 0) {
  68.                 final File classFile = new File(directory, className + ".class");
  69.                 if (classFile.exists()) {
  70.                     classFile.delete();
  71.                 }
  72.                 directory.delete();
  73.                 return "";
  74.             }
  75.         }
  76.         return directory.getAbsolutePath();
  77.     }
  78.  
  79.     private static boolean validName(String name) {
  80.         if (name == null || name.isEmpty()) return false;
  81.         final char[] chars = name.toCharArray();
  82.         if (chars[0] != '_' && !Character.isLetter(chars[0])) return false;
  83.         for (int i = 1; i < chars.length; i++) {
  84.             if (chars[i] != '_' && !Character.isLetter(chars[i]) && !Character.isDigit(chars[i])) return false;
  85.         }
  86.         return true;
  87.     }
  88.  
  89.     private static void usingClass(String className, String path) {
  90.         // User user = new User();
  91.         // user.id = 1;
  92.         // user.name = "admin";
  93.         // user.password = "qwerty";
  94.         // System.out.printf(
  95.         //     "{ 'id': '%d', 'name': '%s', 'password': '%s'}",
  96.         //     user.id,
  97.         //     user.name,
  98.         //     user.password
  99.         // );
  100.         // System.out.println();
  101.     }
  102.  
  103.     public static void main(String[] args) {
  104.         try {
  105.             final Map<String, String> fields = new HashMap<>();
  106.             fields.put("id", "Integer");
  107.             fields.put("name", "String");
  108.             fields.put("password", "String");
  109.             final List<String> source = generateSource("User", fields);
  110.             final String path = buildClassFile("User", source, System.getProperty("user.dir"));
  111.             if (!path.isEmpty() && (new File(path, "User.class")).exists()) {
  112.                 System.out.println("Class User created in: " + path);
  113.                 usingClass("User", path);
  114.                 (new File(path, "User.class")).delete();
  115.                 (new File(path)).delete();
  116.             }
  117.         } catch (Exception ex) {
  118.             System.err.println("[ERROR] " + ex.getMessage());
  119.         }
  120.     }
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement