List of usage examples for javax.tools Diagnostic getSource
S getSource();
From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java
/** * F2 test.//from w ww . ja va 2s . c o m * * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException * @throws MalformedURLException */ @Test public void f2Test() throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException { /** Compilation Requirements *********************************************************************************************/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.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... List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar"); File helloWorldJava = new File(System.getProperty("user.dir") + "/generated-code/caserunners/org/bigtester/ate/model/project/CaseRunner8187856223134148550.java"); Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /********************************************************************************************* Compilation Requirements **/ if (task.call()) { /** Load and execute *************************************************************************************************/ System.out.println("Yipe"); // 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! URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() }); // Load the class from the classloader by name.... Class<?> loadedClass = classLoader .loadClass("org.bigtester.ate.model.project.CaseRunner8187856223134148550"); // Create a new instance... Object obj = loadedClass.newInstance(); // Santity check if (obj instanceof IRunTestCase) { ((IRunTestCase) obj).setCurrentExecutingTCName("test case name example"); Assert.assertEquals(((IRunTestCase) obj).getCurrentExecutingTCName(), "test case name example"); System.out.println("pass"); } /************************************************************************************************* Load and execute **/ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri()); } } }
From source file:org.kantega.dogmaticmvc.java.JavaScriptCompiler.java
@Override public Class compile(HttpServletRequest request) { String className = request.getServletPath().substring(1).replace('/', '.'); List<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>(); for (String path : (Set<String>) servletContext.getResourcePaths("/WEB-INF/dogmatic/")) { if (path.endsWith("java")) { try { String classNAme = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); compilationUnits.add(new JavaSourceFromURL(classNAme, servletContext.getResource(path))); } catch (MalformedURLException e) { throw new RuntimeException(e); }/*from ww w . j a v a 2 s . co m*/ } } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager( compiler.getStandardFileManager(null, null, null), new ClassLoaderImpl(getClass().getClassLoader())); String cp = ""; for (ClassLoader cl : Arrays.asList(getClass().getClassLoader(), getClass().getClassLoader().getParent())) { if (cl instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) cl; for (URL url : ucl.getURLs()) { if (cp.length() > 0) { cp += File.pathSeparator; } cp += url.getFile(); } } } List<String> options = new ArrayList(Arrays.asList("-classpath", cp)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); boolean success = task.call(); StringWriter sw = new StringWriter(); PrintWriter w = new PrintWriter(sw); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { w.println(diagnostic.getCode()); w.println(diagnostic.getKind()); w.println(diagnostic.getPosition()); w.println(diagnostic.getStartPosition()); w.println(diagnostic.getEndPosition()); w.println(diagnostic.getSource()); w.println(diagnostic.getMessage(null)); } System.out.println("Success: " + success); if (success) { try { return fileManager.getClassLoader(null).loadClass(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Compilation failed: " + sw); } }
From source file:rita.compiler.CompileString.java
/** * El mtodo compile crea el archivo compilado a partir de un codigo fuente * y lo deja en un directorio determinado * /*w w w.jav a 2 s. co m*/ * @param sourceCode * el codigo fuente * @param className * el nombre que debera llevar la clase * @param packageName * nombre del paquete * @param outputDirectory * directorio donde dejar el archivo compilado * */ public static final Collection<File> compile(File sourceCode, File outputDirectory) throws Exception { diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>(); JavaCompiler compiler = new EclipseCompiler(); System.out.println(sourceCode); DiagnosticListener<JavaFileObject> listener = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) { System.err.println("=======================ERROR=========================="); System.err.println("Tipo: " + diagnostic.getKind()); System.err.println("mensaje: " + diagnostic.getMessage(Locale.ENGLISH)); System.err.println("linea: " + diagnostic.getLineNumber()); System.err.println("columna: " + diagnostic.getColumnNumber()); System.err.println("CODE: " + diagnostic.getCode()); System.err.println( "posicion: de " + diagnostic.getStartPosition() + " a " + diagnostic.getEndPosition()); System.err.println(diagnostic.getSource()); diagnostics.add(diagnostic); } } }; StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); /* guardar los .class y directorios (packages) en un directorio separado; de esta manera * si se genera mas de 1 clase (porque p.ej. hay inner classes en el codigo) podemos identificar * a todas las clases resultantes de esta compilacion */ File tempOutput = createTempDirectory(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempOutput)); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceCode); try { if (compiler.getTask(null, fileManager, listener, null, null, compilationUnits).call()) { // copiar .class y directorios (packages) generados por el compilador en tempOutput al directorio final FileUtils.copyDirectory(tempOutput, outputDirectory); // a partir de los paths de los archivos .class generados en el dir temp, modificarlos para que sean relativos a outputDirectory Collection<File> compilationResults = new ArrayList<File>(); final int tempPrefix = tempOutput.getAbsolutePath().length(); for (File classFile : FileUtils.listFiles(tempOutput, new SuffixFileFilter(".class"), TrueFileFilter.INSTANCE)) { compilationResults .add(new File(outputDirectory, classFile.getAbsolutePath().substring(tempPrefix))); } // retornar los paths de todos los .class generados return compilationResults; } } catch (Exception e) { e.printStackTrace(); System.out.println("Error al realizar el compilado"); } finally { FileUtils.deleteDirectory(tempOutput); fileManager.close(); } return null; }