List of usage examples for javax.tools DiagnosticCollector DiagnosticCollector
DiagnosticCollector
From source file:com.haulmont.cuba.core.sys.javacl.JavaClassLoader.java
@Override public Class loadClass(final String fullClassName, boolean resolve) throws ClassNotFoundException { String containerClassName = StringUtils.substringBefore(fullClassName, "$"); StopWatch loadingWatch = new Slf4JStopWatch("LoadClass"); try {/* w w w .jav a2s.c o m*/ lock(containerClassName); Class clazz; if (!sourceProvider.getSourceFile(containerClassName).exists()) { clazz = super.loadClass(fullClassName, resolve); return clazz; } CompilationScope compilationScope = new CompilationScope(this, containerClassName); if (!compilationScope.compilationNeeded()) { TimestampClass timestampClass = getTimestampClass(fullClassName); if (timestampClass == null) { throw new ClassNotFoundException(fullClassName); } return timestampClass.clazz; } String src; try { src = sourceProvider.getSourceString(containerClassName); } catch (IOException e) { throw new ClassNotFoundException("Could not load java sources for class " + containerClassName); } try { log.debug("Compiling " + containerClassName); final DiagnosticCollector<JavaFileObject> errs = new DiagnosticCollector<>(); SourcesAndDependencies sourcesAndDependencies = new SourcesAndDependencies(rootDir, this); sourcesAndDependencies.putSource(containerClassName, src); sourcesAndDependencies.collectDependencies(containerClassName); Map<String, CharSequence> sourcesForCompilation = sourcesAndDependencies .collectSourcesForCompilation(containerClassName); @SuppressWarnings("unchecked") Map<String, Class> compiledClasses = createCompiler().compile(sourcesForCompilation, errs); Map<String, TimestampClass> compiledTimestampClasses = wrapCompiledClasses(compiledClasses); compiled.putAll(compiledTimestampClasses); linkDependencies(compiledTimestampClasses, sourcesAndDependencies.dependencies); clazz = compiledClasses.get(fullClassName); springBeanLoader.updateContext(compiledClasses.values()); return clazz; } catch (Exception e) { proxyClassLoader.restoreRemoved(); throw new RuntimeException(e); } finally { proxyClassLoader.cleanupRemoved(); } } finally { unlock(containerClassName); loadingWatch.stop(); } }
From source file:com.qwazr.compiler.JavaCompiler.java
private void compile(javax.tools.JavaCompiler compiler, Collection<File> javaFiles) throws IOException { final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); try {//from www . j a v a 2 s. c o m Iterable<? extends JavaFileObject> sourceFileObjects = fileManager .getJavaFileObjectsFromFiles(javaFiles); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); final List<String> options = new ArrayList<String>(); if (classPath != null) { options.add("-classpath"); options.add(classPath); } options.add("-d"); options.add(javaClassesDirectory.getAbsolutePath()); options.add("-sourcepath"); options.add(javaSourceDirectory.getAbsolutePath()); javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(pw, fileManager, diagnostics, options, null, sourceFileObjects); if (!task.call()) { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) pw.format("Error on line %d in %s%n%s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri(), diagnostic.getMessage(null)); pw.flush(); pw.close(); sw.close(); throw new IOException(sw.toString()); } } finally { IOUtils.close(fileManager); } }
From source file:neembuu.uploader.zip.generator.NUCompiler.java
/** * Compile all the given files in the given build directory. * * @param files The array of files to compiles. * @param buildDirectory The build directory in which put all the compiled * files.// w w w. j a v a2s. c om * @throws FileNotFoundException * @throws IOException */ private void compileFiles(File[] files, File buildDirectory) throws FileNotFoundException, IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); buildDirectory.mkdir(); /**/ List<String> optionList = new ArrayList<String>(); // set compiler's classpath to be same as the runtime's //optionList.addAll(Arrays.asList("-classpath", "C:\\neembuuuploader\\modules\\libs\\jsoup-1.7.2.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-codec-1.6.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-logging-1.1.1.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-cache-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpcore-4.2.4.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpmime-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\json-java.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-utils\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-api\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-interfaces-abstractimpl\\build\\classes;C:\\neembuuuploader\\modules\\libs\\neembuu-now-api-ui.jar;C:\\neembuuuploader\\modules\\libs\\neembuu-release1-ui-mc.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-uploaders\\build\\classes;C:\\neembuuuploader\\modules\\NeembuuUploader\\build\\classes")); optionList.addAll(Arrays.asList("-classpath", classPath)); optionList.addAll(Arrays.asList("-d", buildDirectory.getAbsolutePath())); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(files)); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, optionList, null, compilationUnits); boolean result = task.call(); if (result) { System.out.println("Compilation was successful"); } else { System.out.println("Compilation failed"); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic); } } }
From source file:com.tojc.ormlite.android.compiler.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p>//from w ww . jav a2 s . c o m * The compilation units and all their dependencies are expected to be on the classpath. * @param compilationUnitPaths * the paths of the source files to compile, as would be expected by * {@link ClassLoader#getResource(String)} * @return the {@link Diagnostic diagnostics} returned by the compilation, as demonstrated in * the documentation for {@link JavaCompiler} * @see #compileTestCase(Class...) */ protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) { assert compilationUnitPaths != null; Collection<File> compilationUnits; try { compilationUnits = findClasspathFiles(compilationUnitPaths); } catch (IOException exception) { throw new IllegalArgumentException("Unable to resolve compilation units " + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception); } DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null); /* * Call the compiler with the "-proc:only" option. The "class names" option (which could, in * principle, be used instead of compilation units for annotation processing) isn't useful * in this case because only annotations on the classes being compiled are accessible. * Information about the classes being compiled (such as what they are annotated with) is * *not* available via the RoundEnvironment. However, if these classes are annotations, they * certainly need to be validated. */ CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, mergeCompilerOptions(Arrays.asList("-proc:only")), null, fileManager.getJavaFileObjectsFromFiles(compilationUnits)); task.setProcessors(getProcessors()); task.call(); try { fileManager.close(); } catch (IOException exception) { exception.printStackTrace(); } return diagnosticCollector.getDiagnostics(); }
From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java
private void compileWebServiceInterface() { java.util.Set<String> processedFocusDomainSet = (java.util.Set<String>) getScriptContext().getMemory() .get("processedFocusDomainSet"); if (processedFocusDomainSet == null) { processedFocusDomainSet = new java.util.HashSet<String>(); getScriptContext().getMemory().put("processedFocusDomainSet", processedFocusDomainSet); }// w ww . j ava 2 s. c o m processedFocusDomainSet.add(getScriptContext().getFocusDomain()); if (processedFocusDomainSet.containsAll(getScriptContext().retrieveDomainSet()) == true) { //All domains have been processed so now we can compile and generate WSDL StandardJavaFileManager fileManager = null; try { String jaxbPojoPath = GeneratorUtil.getJaxbPojoPath(getScriptContext()); String servicePath = GeneratorUtil.getServicePath(getScriptContext()); String serviceImplPath = GeneratorUtil.getServiceImplPath(getScriptContext()); String projectRoot = getScriptContext().getProperties().getProperty("PROJECT_ROOT"); List<String> compilerFiles = GeneratorUtil.getFiles(jaxbPojoPath, new String[] { "java" }); compilerFiles.addAll(GeneratorUtil.getFiles(servicePath, new String[] { "java" })); compilerFiles.addAll(GeneratorUtil.getFiles(serviceImplPath, new String[] { "java" })); getScriptContext().logInfo("Compiling files: " + compilerFiles); // Check if output directory exist, create it GeneratorUtil.createOutputDir(projectRoot + File.separator + "classes"); List<String> options = new ArrayList<String>(); options.add("-classpath"); String classPathStr = GeneratorUtil .getFiles(new java.io.File(getScriptContext().getGeneratorBase()).getAbsolutePath() + File.separator + "lib", new String[] { "jar" }, File.pathSeparator) + File.pathSeparator + new java.io.File(projectRoot + File.separatorChar + "classes").getAbsolutePath(); getScriptContext().logInfo("compiler classpath is: " + classPathStr); options.add(classPathStr); options.add("-d"); options.add(projectRoot + File.separator + "classes"); options.add("-s"); options.add(projectRoot + File.separator + "src/generated"); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(compilerFiles); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); boolean success = task.call(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { getScriptContext().logInfo(diagnostic.getCode()); getScriptContext().logInfo(diagnostic.getKind().toString()); getScriptContext().logInfo(diagnostic.getPosition() + ""); getScriptContext().logInfo(diagnostic.getStartPosition() + ""); getScriptContext().logInfo(diagnostic.getEndPosition() + ""); getScriptContext().logInfo(diagnostic.getSource().toString()); getScriptContext().logInfo(diagnostic.getMessage(null)); } } catch (Throwable t) { getScriptContext().logError(t); } finally { try { fileManager.close(); } catch (Throwable t) { } } for (String focusDomain : getScriptContext().retrieveDomainSet()) { generateWebServiceArtifacts(focusDomain); } } }
From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java
private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException { /** Compilation Requirements *********************************************************************************************/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null); // This sets up the class path that the compiler will use. // I've added the .jar file that contains the DoStuff interface within // in it...//from w w w . ja va 2s .c om List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(getAllJarsClassPathInMavenLocalRepo()); optionList.add("-verbose"); File helloWorldJava = new File(classFilePathName); Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /********************************************************************************************* Compilation Requirements **/ if (task.call()) { /** Load and execute *************************************************************************************************/ // Create a new custom class loader, pointing to the directory that // contains the compiled // classes, this should point to the top of the package structure! //TODO the / separator needs to be revised to platform awared URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() }, Thread.currentThread().getContextClassLoader()); String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/"; ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent()); classLoader.loadClass(className); classLoader.close(); /************************************************************************************************* Load and execute **/ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(), diagnostic.getSource(), diagnostic.getMessage(new Locale("en"))); } } }
From source file:iristk.flow.FlowCompiler.java
public static void compileJavaFlow(File srcFile) throws FlowCompilerException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (ToolProvider.getSystemJavaCompiler() == null) { throw new FlowCompilerException("Could not find Java Compiler"); }/* w w w. ja va 2s . c o m*/ if (!srcFile.exists()) { throw new FlowCompilerException(srcFile.getAbsolutePath() + " does not exist"); } File outputDir = new File(srcFile.getAbsolutePath().replaceFirst("([\\\\/])src[\\\\/].*", "$1") + "bin"); if (!outputDir.exists()) { throw new FlowCompilerException("Directory " + outputDir.getAbsolutePath() + " does not exist"); } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.US, StandardCharsets.UTF_8); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(Arrays.asList(srcFile.getAbsolutePath())); Iterable<String> args = Arrays.asList("-d", outputDir.getAbsolutePath()); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, args, null, compilationUnits); boolean success = task.call(); try { fileManager.close(); } catch (IOException e) { } for (Diagnostic<? extends JavaFileObject> diag : diagnostics.getDiagnostics()) { if (diag.getKind() == Kind.ERROR) { int javaLine = (int) diag.getLineNumber(); int flowLine = mapLine(javaLine, srcFile); String message = diag.getMessage(Locale.US); message = message.replace("line " + javaLine, "line " + flowLine); throw new FlowCompilerException(message, flowLine); } } if (!success) { throw new FlowCompilerException("Compilation failed for unknown reason"); } }
From source file:org.abstractmeta.toolbox.compilation.compiler.impl.JavaSourceCompilerImpl.java
protected boolean compile(JavaCompiler compiler, ClassLoader parentClassLoader, CompilationUnit compilationUnit, String... options) {/* w w w . j a v a 2 s.c o m*/ if (compiler == null) { throw new IllegalStateException( "Failed to create the system Java compiler. Check that your class path includes tools.jar"); } JavaFileObjectRegistry registry = compilationUnit.getRegistry(); SimpleClassLoader result = new SimpleClassLoader(parentClassLoader, registry, compilationUnit.getOutputClassDirectory()); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaFileManager standardFileManager = compiler.getStandardFileManager(diagnostics, null, null); JavaFileManager javaFileManager = new SimpleJavaFileManager(standardFileManager, result, registry); Iterable<JavaFileObject> sources = registry.get(JavaFileObject.Kind.SOURCE); Collection<String> compilationOptions = buildOptions(compilationUnit, result, options); JavaCompiler.CompilationTask task = compiler.getTask(null, javaFileManager, diagnostics, compilationOptions, null, sources); task.call(); if (getDiagnosticCountByType(diagnostics, Diagnostic.Kind.ERROR) > 0) { String diagnosticString = getDiagnosticString(registry, diagnostics); if (diagnosticString.contains("missing return statement")) { return false; } throw new IllegalStateException(diagnosticString); } if (getDiagnosticCountByType(diagnostics, Diagnostic.Kind.WARNING) > 0) { logger.warn(getDiagnosticString(registry, diagnostics)); } result.addClassPathEntries(compilationUnit.getClassPathsEntries()); return true; }
From source file:org.androidtransfuse.adapter.ASTEquivalenceTest.java
@Test public void testClassEquivalence() throws Exception { PackageClass testImplClassName = new PackageClass("example.test", "TestClass"); PackageClass baseClassName = new PackageClass("example.test", "Base"); PackageClass testClassName = new PackageClass("example.test", "Test"); final String testImplValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader() .getResourceAsStream(testImplClassName.getCanonicalName().replace(".", "/") + ".java")); final String baseValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader() .getResourceAsStream(baseClassName.getCanonicalName().replace(".", "/") + ".java")); final String testValue = IOUtils.toString(ASTEquivalenceTest.class.getClassLoader() .getResourceAsStream(testClassName.getCanonicalName().replace(".", "/") + ".java")); MemoryClassLoader classLoader = new MemoryClassLoader(); Map<PackageClass, String> targetClassMap = new HashMap<PackageClass, String>(); targetClassMap.put(testImplClassName, testImplValue); targetClassMap.put(baseClassName, baseValue); targetClassMap.put(testClassName, testValue); classLoader.add(targetClassMap);//from www .j a v a 2 s . co m Class<?> testClass = Class.forName(testImplClassName.getCanonicalName(), true, classLoader); ASTType testClassType = classFactory.getType(testClass); MemoryClassLoader processorRunningClassLoader = new MemoryClassLoader(); DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>(); boolean pass = processorRunningClassLoader.add(targetClassMap, diagnosticListener, Collections.singletonList(new CompareProcessor(testClassType))); StringBuilder builder = new StringBuilder(); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticListener.getDiagnostics()) { builder.append(diagnostic.getMessage(Locale.US)); } assertTrue(builder.toString(), pass); }
From source file:org.apache.struts2.JSPLoader.java
/** * Compiles the given source code into java bytecode *//*from w ww . jav a 2s . c o m*/ private void compileJava(String className, final String source, Set<String> extraClassPath) throws IOException { if (LOG.isTraceEnabled()) LOG.trace("Compiling [#0], source: [#1]", className, source); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); //the generated bytecode is fed to the class loader JavaFileManager jfm = new ForwardingJavaFileManager<StandardJavaFileManager>( compiler.getStandardFileManager(diagnostics, null, null)) { @Override public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException { MemoryJavaFileObject fileObject = new MemoryJavaFileObject(name, kind); classLoader.addMemoryJavaFileObject(name, fileObject); return fileObject; } }; //read java source code from memory String fileName = className.replace('.', '/') + ".java"; SimpleJavaFileObject sourceCodeObject = new SimpleJavaFileObject(toURI(fileName), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException, IllegalStateException, UnsupportedOperationException { return source; } }; //build classpath //some entries will be added multiple times, hence the set List<String> optionList = new ArrayList<String>(); Set<String> classPath = new HashSet<String>(); FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class) .getFileManager(); //find available jars ClassLoaderInterface classLoaderInterface = getClassLoaderInterface(); UrlSet urlSet = new UrlSet(classLoaderInterface); //find jars List<URL> urls = urlSet.getUrls(); for (URL url : urls) { URL normalizedUrl = fileManager.normalizeToFileProtocol(url); File file = FileUtils.toFile(ObjectUtils.defaultIfNull(normalizedUrl, url)); if (file.exists()) classPath.add(file.getAbsolutePath()); } //these should be in the list already, but I am feeling paranoid //this jar classPath.add(getJarUrl(EmbeddedJSPResult.class)); //servlet api classPath.add(getJarUrl(Servlet.class)); //jsp api classPath.add(getJarUrl(JspPage.class)); try { Class annotationsProcessor = Class.forName("org.apache.AnnotationProcessor"); classPath.add(getJarUrl(annotationsProcessor)); } catch (ClassNotFoundException e) { //ok ignore } //add extra classpath entries (jars where tlds were found will be here) for (Iterator<String> iterator = extraClassPath.iterator(); iterator.hasNext();) { String entry = iterator.next(); classPath.add(entry); } String classPathString = StringUtils.join(classPath, File.pathSeparator); if (LOG.isDebugEnabled()) { LOG.debug("Compiling [#0] with classpath [#1]", className, classPathString); } optionList.addAll(Arrays.asList("-classpath", classPathString)); //compile JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, diagnostics, optionList, null, Arrays.asList(sourceCodeObject)); if (!task.call()) { throw new StrutsException("Compilation failed:" + diagnostics.getDiagnostics().get(0).toString()); } }