Java Code Examples for javax.tools.StandardJavaFileManager#close()

The following examples show how to use javax.tools.StandardJavaFileManager#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationProcessorTestCompiler.java    From spring-configuration-validation-processor with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the java class specified. This implementation only parses and processes the java classes and does not
 * fully compile them - i.e. it does not write class files back to the disk. Basically, {@code javac} is called with
 * {@code -proc:only}.
 *
 * @param classToCompile the Java class to compile
 * @param processor the annotation {@link Processor} to use during compilation
 * @return a list of {@link Diagnostic} messages emitted during the compilation
 */
public static List<Diagnostic<? extends JavaFileObject>> compileClass(String classToCompile, Processor processor)
    throws IOException {

  DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>();

  StandardJavaFileManager fileManager = null;
  try {
    fileManager = getFileManager(collector);
    Iterable<? extends JavaFileObject> compilationUnits = getCompilationUnitOfClass(fileManager, classToCompile);

    CompilationTask task = COMPILER.getTask(null, fileManager, collector, COMPILER_OPTIONS, null, compilationUnits);
    task.setProcessors(Arrays.asList(processor));
    task.call();

    return collector.getDiagnostics();
  } finally {
    if (fileManager != null) {
      fileManager.close();
    }
  }
}
 
Example 2
Source File: MyProxy.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * @param proxyClassString 代理类的代码
 * @param myProxyFile 代理类的Java文件
 * @throws IOException
 */
private static void compile(StringBuffer proxyClassString, File myProxyFile) throws IOException {
    // in out
    FileCopyUtils.copy(proxyClassString.toString().getBytes(), myProxyFile);
    // 调用系统编译器
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null);

    Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(myProxyFile);

    JavaCompiler.CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, null, null, null, javaFileObjects);

    task.call();

    standardJavaFileManager.close();
}
 
Example 3
Source File: CompilerJavac.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public int compile(Map<File, Resource<File>> sources) throws MojoExecutionException, IOException {
  if (sources.isEmpty()) {
    return 0;
  }

  final JavaCompiler compiler = getSystemJavaCompiler();
  final StandardJavaFileManager javaFileManager = compiler.getStandardFileManager(null, null, getSourceEncoding());
  try {
    compile(compiler, javaFileManager, sources);
  } finally {
    javaFileManager.flush();
    javaFileManager.close();
  }
  return sources.size();
}
 
Example 4
Source File: Evaluator.java    From java-repl with Apache License 2.0 6 votes vote down vote up
private void compile(File file) throws Exception {
    String classpath =
            sequence(System.getProperty("java.class.path"))
                    .join(sequence(classLoader.getURLs()).map(urlAsFilePath()))
                    .toString(pathSeparator);
    JavaCompiler compiler = getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sequence(file));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, sequence("-cp", classpath), null, compilationUnits);

    try {
        if (!task.call())
            throw new ExpressionCompilationException(file, diagnostics.getDiagnostics());
    } finally {
        fileManager.close();
    }
}
 
Example 5
Source File: ModelCompiler.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Class<?> compile(Logger log, URLClassLoader loader, String name, String src) throws Exception {
    log.fine("Expernal compiler");
    File classDir = new File(System.getProperty("oms.prj") + File.separatorChar + "dist");
    File srcDir = new File(System.getProperty("java.io.tmpdir"));

    File javaFile = new File(srcDir, name + ".java");
    write(javaFile, src);

    StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null);

    Iterable fileObjects = fm.getJavaFileObjects(javaFile);
    String[] options = new String[]{"-d", classDir.toString()};
    jc.getTask(null, null, null, Arrays.asList(options), null, fileObjects).call();

    fm.close();
    
    return loader.loadClass(name);
}
 
Example 6
Source File: covered_covered_t.java    From coming with MIT License 6 votes vote down vote up
private void compile(File file) throws Exception {
    String classpath =
            sequence(System.getProperty("java.class.path"))
                    .join(sequence(classLoader.getURLs()).map(urlAsFilePath()))
                    .toString(pathSeparator);
    JavaCompiler compiler = getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sequence(file));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, sequence("-cp", classpath), null, compilationUnits);

    try {
        if (!task.call())
            throw new ExpressionCompilationException(file, diagnostics.getDiagnostics());
    } finally {
        fileManager.close();
    }
}
 
Example 7
Source File: TestUtilities.java    From JReFrameworker with MIT License 6 votes vote down vote up
public static List<File> compileSources(List<File> sourceFiles, File workingDirectory) throws IOException {
	JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
	
	if(javaCompiler == null){
		throw new RuntimeException("Could not find Java compiler.");
	}
	
	DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
	StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(diagnostics, Locale.ENGLISH, Charset.forName("UTF-8"));
	Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles);
	javaCompiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
	    
	for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
		throw new RuntimeException(String.format("Error on line %d in %d%n", diagnostic.getLineNumber(), diagnostic.getSource().toString()));
	}        
	 
	fileManager.close();
	
	List<File> classFiles = new LinkedList<File>();
	for(File sourceFile : sourceFiles){
		File outputFile = new File(workingDirectory.getAbsolutePath() + File.separator + sourceFile.getName().replace(".java", ".class"));
		new File(sourceFile.getAbsolutePath().replace(".java", ".class")).renameTo(outputFile);
		classFiles.add(outputFile);
	}
	return classFiles;
}
 
Example 8
Source File: MultiReleaseJarAwareSJFM.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "versions")
public void test(String version, int expected) throws Throwable {
    StandardJavaFileManager jfm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null);
    jfm.setLocation(jloc, List.of(new File("multi-release.jar")));

    if (version.length() > 0) {
        jfm.handleOption("--multi-release", List.of(version).iterator());
    }

    CustomClassLoader cldr = new CustomClassLoader(jfm);
    Class<?> versionClass = cldr.loadClass("version.Version");
    MethodType mt = MethodType.methodType(int.class);
    MethodHandle mh = MethodHandles.lookup().findVirtual(versionClass, "getVersion", mt);
    int v = (int)mh.invoke(versionClass.newInstance());
    Assert.assertEquals(v, expected);

    jfm.close();
}
 
Example 9
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public static void compileModel(final File destinationFolder) throws IOException {

        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        final File[] javaFiles = destinationFolder.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                return name.endsWith(".java");
            }
        });

        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFiles);
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        fileManager.close();
    }
 
Example 10
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public static void compileModel(final File destinationFolder) throws IOException {

        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        final File[] javaFiles = destinationFolder.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                return name.endsWith(".java");
            }
        });

        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFiles);
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        fileManager.close();
    }
 
Example 11
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public static void compileModel(final File destinationFolder) throws IOException {

        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        final File[] javaFiles = destinationFolder.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                return name.endsWith(".java");
            }
        });

        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFiles);
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        fileManager.close();
    }
 
Example 12
Source File: TestCompile.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void testCompile() throws Exception {
	final JavaCompiler systemJavaCompiler = ToolProvider
			.getSystemJavaCompiler();
	final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
	final StandardJavaFileManager standardFileManager = systemJavaCompiler
			.getStandardFileManager(diagnostics, null, null);

	final Iterable<? extends JavaFileObject> fileObjects = standardFileManager
			.getJavaFileObjects(new File(getSourceDir(),
					"org/jvnet/hyperjaxb3/tools/tests/Test.java"));

	final String[] options = new String[] { "-d",
			getTargetDir().getAbsolutePath() };

	getTargetDir().mkdirs();

	systemJavaCompiler.getTask(null, standardFileManager, null,
			Arrays.asList(options), null, fileObjects).call();
	standardFileManager.close();

	final URL[] urls = new URL[] { getTargetDir().toURI().toURL() };
	final URLClassLoader ucl = new URLClassLoader(urls, Thread
			.currentThread().getContextClassLoader());
	final Class clazz = ucl
			.loadClass("org.jvnet.hyperjaxb3.tools.tests.Test");
	Assert.assertEquals("Wrong value.", "This is a test.", clazz
			.newInstance().toString());

}
 
Example 13
Source File: CompilerInterface.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public static void compile(String directory, String file) throws Exception {
    File toCompile = new File(directory, file);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> javaFileObjects =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile));
    compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call();

    fileManager.close();
}
 
Example 14
Source File: JdkCompilerImpl.java    From tac with MIT License 5 votes vote down vote up
private boolean compile(InstCodeInfo codeInfo, StringWriter compileInfo, String outputName) throws Exception {
    long start = 0;
    if (LOG.isInfoEnabled()) {
        start = System.currentTimeMillis();
    }
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    File[] outputs = new File[] {new File(tacFileService.getClassFileOutputPath(outputName))};
    for (File file : outputs) {
        if (!file.exists()) {
            file.mkdirs();
        } else {
            TacFileService.deleteRecursively(file);
            file.mkdirs();
        }
    }

    LOG.debug("compile classpath.  size:{}  CLASS-PATH:{}", CLASSPATH.size(), CLASSPATH);

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputs));
    fileManager.setLocation(StandardLocation.CLASS_PATH, CLASSPATH);
    List<TacJavaFileObject> fileObjects = new ArrayList<TacJavaFileObject>();
    for (JavaSourceCode unit : codeInfo.getJavaSourceCodes()) {
        TacJavaFileObject sourceObject = new TacJavaFileObject(unit.getFullClassName(), unit.getSource());
        fileObjects.add(sourceObject);
    }
    CompilationTask task = compiler.getTask(compileInfo, fileManager, null, OPTIONS, null, fileObjects);
    Boolean resultSuccess = task.call();
    if (resultSuccess == null || !resultSuccess) {
        return false;
    }
    fileManager.close();
    if (LOG.isInfoEnabled()) {
        LOG.info("compile complete . name :{}  instClassName:{} cost: {} resultSucess:{} ", codeInfo.getName(),
            codeInfo.getInstClassName(), (System.currentTimeMillis() - start), resultSuccess);
    }
    return true;
}
 
Example 15
Source File: MyProxy.java    From DesignPatterns with Apache License 2.0 5 votes vote down vote up
public static Object newProxyInstance(MyClassLoader classLoader, Class<?> [] interfaces, MyInvocationHandler h){

       try {
           //1、动态生成源代码.java文件

           String src = generateSrc(interfaces);

           //2、Java文件输出磁盘
           String filePath = MyProxy.class.getResource("").getPath();
           System.out.println(filePath);
           File f = new File(filePath + "$Proxy0.java");
           FileWriter fw = new FileWriter(f);
           fw.write(src);
           fw.flush();
           fw.close();

           //3、把生成的.java文件编译成.class文件
           JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
           StandardJavaFileManager manage = compiler.getStandardFileManager(null,null,null);
           Iterable iterable = manage.getJavaFileObjects(f);

          JavaCompiler.CompilationTask task = compiler.getTask(null,manage,null,null,null,iterable);
          task.call();
          manage.close();

           //4、编译生成的.class文件加载到JVM中来
          Class proxyClass =  classLoader.findClass("$Proxy0");
          Constructor c = proxyClass.getConstructor(MyInvocationHandler.class);
          f.delete();

           //5、返回字节码重组以后的新的代理对象
           return c.newInstance(h);
       }catch (Exception e){
           e.printStackTrace();
       }
        return null;
    }
 
Example 16
Source File: JavaNativeCompiler.java    From Repeat with Apache License 2.0 4 votes vote down vote up
@Override
public DynamicCompilationResult compile(String sourceCode) {
	String originalPath = System.getProperty("java.home");
	// This no longer works in JDK 9 (but why?).
	// We are forced to run the program in JDK in order to be
	// able to retrieve the compiler.
	System.setProperty("java.home", home.getAbsolutePath());

	if (!sourceCode.contains("class " + defaultClassName)) {
		getLogger().warning("Cannot find class " + defaultClassName + " in source code.");
		return DynamicCompilationResult.of(DynamicCompilerOutput.SOURCE_MISSING_PREFORMAT_ELEMENTS, null);
	}

	String newClassName = className;
	if (newClassName == null) {
		newClassName = getDummyPrefix() + RandomUtil.randomID();
	}
	sourceCode = sourceCode.replaceFirst("class " + defaultClassName, "class " + newClassName);

	try {
		File compiling = getSourceFile(newClassName);
        if (compiling.getParentFile().exists() || compiling.getParentFile().mkdirs()) {
            try {
                if (!FileUtility.writeToFile(sourceCode, compiling, false)) {
                	getLogger().warning("Cannot write source code to file.");
                	return DynamicCompilationResult.of(DynamicCompilerOutput.SOURCE_NOT_ACCESSIBLE, new DormantUserDefinedTask(sourceCode, Language.JAVA));
                }

                /** Compilation Requirements *********************************************************************************************/
                DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
				if (compiler == null) {
					getLogger().warning("No java compiler found. Set class path points to JDK in setting?\nNote that for Java 9 an above. Setting class path no longer "
							+ "works. You will need to launch this program using a JDK instead of a JRE.");
					return DynamicCompilationResult.of(DynamicCompilerOutput.COMPILER_MISSING, new DormantUserDefinedTask(sourceCode, Language.JAVA));
				}
                StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.US, StandardCharsets.UTF_8);

                // This sets up the class path that the compiler will use.
                // Added the .jar file that contains the [className] interface within in it...
                List<String> optionList = new ArrayList<String>();
                optionList.add("-classpath");
                String paths = System.getProperty("java.class.path");
                if (classPaths.length > 0) {
                	 paths += ";" + StringUtilities.join(classPaths, ";");
                }
                optionList.add(paths);

                Iterable<? extends JavaFileObject> compilationUnit
                        = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(compiling));
                JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    optionList,
                    null,
                    compilationUnit);
                /********************************************************************************************* Compilation Requirements **/
                if (task.call()) {
                	DynamicCompilationResult output = loadClass(newClassName);
                	getLogger().info("Successfully compiled class " + defaultClassName);
               		return output;
                } else {
                    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
                    	getLogger().warning("Error on line " + diagnostic.getLineNumber() +" in " + diagnostic.getSource().toUri() + ".");
                    	getLogger().warning(diagnostic.getMessage(Locale.US));
                    }
                }
                fileManager.close();
            } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {
            	getLogger().log(Level.WARNING, "Error during compilation...", exp);
            }
        }
        getLogger().warning("Cannot compile class " + defaultClassName);
        return DynamicCompilationResult.of(DynamicCompilerOutput.COMPILATION_ERROR, null);
	} finally {
		className = null;
		System.setProperty("java.home", originalPath);
	}
}
 
Example 17
Source File: FileSystemClosedTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void run() throws Exception {
    ToolBox tb = new ToolBox();
    Path jar = createJar(tb);

    Path src = Paths.get("src");
    tb.writeJavaFiles(src, "class C { p1.C1 c1; }");

    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    PrintWriter out = new PrintWriter(System.err, true);
    StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
    List<String> options = Arrays.asList("-classpath", jar.toString(), "-proc:none");
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(src.resolve("C.java"));
    com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) comp.getTask(out, fm, null, options, null, files);
    task.parse();

    Elements elems = task.getElements();

    try {
        // Use  p1, p1.C1 as a control to verify normal behavior
        PackageElement p1 = elems.getPackageElement("p1");
        TypeElement p1C1 = elems.getTypeElement("p1.C1");
        System.err.println("p1: " + p1 + ";  p1C1: " + p1C1);
        if (p1C1 == null) {
            throw new Exception("p1.C1 not found");
        }

        // Now repeat for p2, p2.C2, closing the file manager early
        PackageElement p2 = elems.getPackageElement("p2");
        System.err.println("closing file manager");
        fm.close();
        TypeElement p2C2 = elems.getTypeElement("p2.C2");
        System.err.println("p2: " + p2 + ";  p2C2: " + p2C2);
        if (p2C2 != null) {
            throw new Exception("p2.C2 found unexpectedly");
        }
    } catch (ClosedFileSystemException e) {
        throw new Exception("unexpected exception thrown", e);
    }

}
 
Example 18
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "crawler")
public void testFile(String fileName) throws IOException {
    File file = getSourceFile(fileName);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    boolean success = true;
    StringWriter writer = new StringWriter();
    writer.write("Testing : " + file.toString() + "\n");
    String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Trees trees = Trees.instance(task);
    SourcePositions sp = trees.getSourcePositions();

    for (CompilationUnitTree cut : asts) {
        for (ImportTree imp : cut.getImports()) {
            success &= testStatement(writer, sp, text, cut, imp);
        }
        for (Tree decl : cut.getTypeDecls()) {
            success &= testStatement(writer, sp, text, cut, decl);
            if (decl instanceof ClassTree) {
                ClassTree ct = (ClassTree) decl;
                for (Tree mem : ct.getMembers()) {
                    if (mem instanceof MethodTree) {
                        MethodTree mt = (MethodTree) mem;
                        BlockTree bt = mt.getBody();
                        // No abstract methods or constructors
                        if (bt != null && mt.getReturnType() != null) {
                            // The modifiers synchronized, abstract, and default are not allowed on
                            // top-level declarations and are errors.
                            Set<Modifier> modifier = mt.getModifiers().getFlags();
                            if (!modifier.contains(Modifier.ABSTRACT)
                                    && !modifier.contains(Modifier.SYNCHRONIZED)
                                    && !modifier.contains(Modifier.DEFAULT)) {
                                success &= testStatement(writer, sp, text, cut, mt);
                            }
                            testBlock(writer, sp, text, cut, bt);
                        }
                    }
                }
            }
        }
    }
    fileManager.close();
    if (!success) {
        throw new AssertionError(writer.toString());
    }
}
 
Example 19
Source File: Business.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean buildAllTable() throws Exception {
	boolean result = false;
	File dir = new File(Config.dir_local_temp_dynamic(true), StringTools.uniqueToken());
	FileUtils.forceMkdir(dir);
	File src = new File(dir, "src");
	FileUtils.forceMkdir(src);
	File target = new File(dir, "target");
	FileUtils.forceMkdir(target);
	File resources = new File(dir, "resources");
	FileUtils.forceMkdir(resources);
	List<Table> tables = emc.listEqual(Table.class, Table.status_FIELDNAME, Table.STATUS_build);
	/* 产生用于创建persistence.xml */
	List<String> classNames = new ArrayList<>();
	for (Table table : tables) {
		try {
			emc.beginTransaction(Table.class);
			if (StringUtils.isNotEmpty(table.getData())) {
				DynamicEntity dynamicEntity = XGsonBuilder.instance().fromJson(table.getData(),
						DynamicEntity.class);
				dynamicEntity.setName(table.getName());
				DynamicEntityBuilder builder = new DynamicEntityBuilder(dynamicEntity, src);
				builder.build();
				classNames.add(dynamicEntity.className());
			}
			table.setBuildSuccess(true);
			emc.commit();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	if (!classNames.isEmpty()) {

		PersistenceXmlHelper.directWrite(new File(resources, "META-INF/persistence.xml").getAbsolutePath(),
				classNames);

		List<File> classPath = new ArrayList<>();
		classPath.addAll(FileUtils.listFiles(Config.dir_commons_ext(), FileFilterUtils.suffixFileFilter(DOT_JAR),
				DirectoryFileFilter.INSTANCE));
		classPath.addAll(FileUtils.listFiles(Config.dir_store_jars(), FileFilterUtils.suffixFileFilter(DOT_JAR),
				DirectoryFileFilter.INSTANCE));

		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null,
				DefaultCharset.charset_utf_8);

		fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(target));
		fileManager.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(src, resources));
		fileManager.setLocation(StandardLocation.CLASS_PATH, classPath);

		Iterable<JavaFileObject> res = fileManager.list(StandardLocation.SOURCE_PATH, DynamicEntity.CLASS_PACKAGE,
				EnumSet.of(JavaFileObject.Kind.SOURCE), true);

		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

		StringWriter out = new StringWriter();

		if (!compiler.getTask(out, fileManager, diagnostics, null, null, res).call()) {
			for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
				out.append("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic).append('\n');
			}
			throw new ExceptionCompileError(out.toString());
		}

		result = true;

		fileManager.close();

		this.enhance(target, resources);

		File jar = new File(Config.dir_dynamic_jars(true), DynamicEntity.JAR_NAME + DOT_JAR);

		JarTools.jar(target, jar);
	}
	return result;
}
 
Example 20
Source File: FileBasedWorkflowRepository.java    From copper-engine with Apache License 2.0 4 votes vote down vote up
private Map<String, File> compile(File compileTargetDir, File additionalSourcesDir) throws IOException {
    logger.info("Compiling workflows");
    List<String> options = new ArrayList<String>();
    String extraOptions = System.getProperty("org.copperengine.workflow.compiler.options", "");
    if(!extraOptions.isEmpty()) {
        for(String opt: extraOptions.split(",")) {
            options.add(opt);
        }
    }
    options.add("-g");
    options.add("-d");
    options.add(compileTargetDir.getAbsolutePath());
    for (CompilerOptionsProvider cop : compilerOptionsProviders) {
        options.addAll(cop.getOptions());
    }
    if(Collections.disjoint(options, Arrays.asList("--class-path", "-classpath", "-cp"))) {
        String modulePath = System.getProperty("jdk.module.path", "");
        if(!modulePath.isEmpty()) {
            options.add("-cp");
            options.add(modulePath);
        }
    }
    logger.info("Compiler options: " + options.toString());
    JavaCompiler compiler = getJavaCompiler();
    if (compiler == null)
        throw new IllegalStateException("No Java compiler available! Please make sure that either tools.jar is provided, or that you start with a full JDK (not an JRE!), or that any other JSR-199 compatible Java compiler is available on the classpath, e.g. the Eclipse compiler ecj");
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final Map<String, File> files = new HashMap<String, File>();
    try {
        for (String dir : sourceDirs) {
            files.putAll(findFiles(new File(dir), ".java"));
        }
        files.putAll(findFiles(additionalSourcesDir, ".java"));
        if (files.size() > 0) {
            final Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files.values());
            final StringWriter sw = new StringWriter();
            final CompilationTask task = compiler.getTask(sw, fileManager, null, options, null, compilationUnits1);
            lastBuildResults = null;
            if (!task.call()) {
                lastBuildResults = "Compilation failed!\n" + sw.toString();
                logger.error(lastBuildResults);
                throw new CopperRuntimeException("Compilation failed, see logfile for details");
            }
        }
    } finally {
        fileManager.close();
    }
    return files;
}