List of usage examples for javax.tools Diagnostic getLineNumber
long getLineNumber();
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"); }//from w ww. j a v a 2 s. 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.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 ww . jav a2 s. c o m*/ 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:org.apidesign.bck2brwsr.dew.Dew.java
@Override public void service(Request request, Response response) throws Exception { if (request.getMethod() == Method.POST) { InputStream is = request.getInputStream(); JSONTokener tok = new JSONTokener(new InputStreamReader(is)); JSONObject obj = new JSONObject(tok); String tmpHtml = obj.getString("html"); String tmpJava = obj.getString("java"); Compile res = Compile.create(tmpHtml, tmpJava); List<Diagnostic<? extends JavaFileObject>> err = res.getErrors(); if (err.isEmpty()) { data = res;//from w w w . j a v a 2 s. co m response.getOutputStream().write("[]".getBytes()); response.setStatus(HttpStatus.OK_200); } else { JSONArray errors = new JSONArray(); for (Diagnostic<? extends JavaFileObject> d : err) { JSONObject e = new JSONObject(); e.put("col", d.getColumnNumber()); e.put("line", d.getLineNumber()); e.put("kind", d.getKind().toString()); e.put("msg", d.getMessage(Locale.ENGLISH)); errors.put(e); } errors.write(response.getWriter()); response.setStatus(HttpStatus.PRECONDITION_FAILED_412); } return; } String r = request.getHttpHandlerPath(); if (r == null || r.equals("/")) { r = "index.html"; } if (r.equals("/result.html")) { response.setContentType("text/html"); if (data != null) { response.getOutputBuffer().write(data.getHtml()); } response.setStatus(HttpStatus.OK_200); return; } if (r.startsWith("/")) { r = r.substring(1); } if (r.endsWith(".html") || r.endsWith(".xhtml")) { response.setContentType("text/html"); } OutputStream os = response.getOutputStream(); try (InputStream is = Dew.class.getResourceAsStream(r)) { copyStream(is, os, request.getRequestURL().toString()); } catch (IOException ex) { response.setDetailMessage(ex.getLocalizedMessage()); response.setError(); response.setStatus(404); } }
From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java
/** * F2 test.//from w w w . j a v a 2 s . c om * * @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.dspace.installer_edm.InstallerCrosswalk.java
/** * Compila el java en tiempo real/* w ww.jav a 2s . c o m*/ * * @return xito de la operacin */ protected boolean compileEDMCrossWalk() { boolean status = false; SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(canonicalCrosswalkName, edmCrossWalkContent); JavaFileObject javaFileObjects[] = new JavaFileObject[] { fileObject }; Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects); // libreras necesarias para linkar con el fuente a compilar String myInstallerPackagesDirPath = myInstallerDirPath + fileSeparator + "packages" + fileSeparator; StringBuilder jars = (fileSeparator.equals("\\")) ? new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar;") .append(myInstallerPackagesDirPath).append("jdom-1.0.jar;") .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar") : new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar:") .append(myInstallerPackagesDirPath).append("jdom-1.0.jar:") .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar"); String[] compileOptions = new String[] { "-d", myInstallerWorkDirPath, "-source", "1.6", "-target", "1.6", "-cp", jars.toString() }; Iterable<String> compilationOptionss = Arrays.asList(compileOptions); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null); JavaCompiler.CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptionss, null, compilationUnits); status = compilerTask.call(); if (!status) { for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { installerEDMDisplay .showMessage("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic); } } try { stdFileManager.close(); } catch (IOException e) { showException(e); } return status; }
From source file:org.evosuite.junit.JUnitAnalyzer.java
private static List<File> compileTests(List<TestCase> tests, File dir) { TestSuiteWriter suite = new TestSuiteWriter(); suite.insertAllTests(tests);//from www. jav a 2 s .com //to get name, remove all package before last '.' int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1; String name = Properties.TARGET_CLASS.substring(beginIndex); name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX; //postfix try { //now generate the JUnit test case List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST); for (File file : generated) { if (!file.exists()) { logger.error("Supposed to generate " + file + " but it does not exist"); return null; } } //try to compile the test cases JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { logger.error("No Java compiler is available"); return null; } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); Locale locale = Locale.getDefault(); Charset charset = Charset.forName("UTF-8"); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(generated); List<String> optionList = new ArrayList<>(); String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath(); if (JarPathing.containsAPathingJar(evosuiteCP)) { evosuiteCP = JarPathing.expandPathingJars(evosuiteCP); } String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath(); if (JarPathing.containsAPathingJar(targetProjectCP)) { targetProjectCP = JarPathing.expandPathingJars(targetProjectCP); } String classpath = targetProjectCP + File.pathSeparator + evosuiteCP; optionList.addAll(Arrays.asList("-classpath", classpath)); CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits); boolean compiled = task.call(); fileManager.close(); if (!compiled) { logger.error("Compilation failed on compilation units: " + compilationUnits); logger.error("Classpath: " + classpath); //TODO remove logger.error("evosuiteCP: " + evosuiteCP); for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) { if (diagnostic.getMessage(null).startsWith("error while writing")) { logger.error("Error is due to file permissions, ignoring..."); return generated; } logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber()); } StringBuffer buffer = new StringBuffer(); for (JavaFileObject sourceFile : compilationUnits) { List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath())); buffer.append(compilationUnits.iterator().next().toString() + "\n"); for (int i = 0; i < lines.size(); i++) { buffer.append((i + 1) + ": " + lines.get(i) + "\n"); } } logger.error(buffer.toString()); return null; } return generated; } catch (IOException e) { logger.error("" + e, e); return null; } }
From source file:org.openmrs.logic.CompilingClassLoader.java
private String compile(String javaFile) throws IOException { String errorMessage = null;/*from w w w. j a va 2s. c o m*/ String ruleClassDir = Context.getAdministrationService() .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER); String ruleJavaDir = Context.getAdministrationService() .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); log.info("JavaCompiler is null: " + compiler == null); if (compiler != null) { // java compiler only available on JDK. This part of "IF" will not get executed when we run JUnit test File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir); String[] options = {}; DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Context.getLocale(), Charset.defaultCharset()); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFolder)); // create compiling classpath String stringProperties = System.getProperty("java.class.path"); if (log.isDebugEnabled()) log.debug("Compiler classpath: " + stringProperties); String[] properties = StringUtils.split(stringProperties, File.pathSeparator); List<File> classpathFiles = new ArrayList<File>(); for (String property : properties) { File f = new File(property); if (f.exists()) classpathFiles.add(f); } classpathFiles.addAll(getCompilerClasspath()); fileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles); // create the compilation task CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnosticCollector, Arrays.asList(options), null, fileManager.getJavaFileObjects(javaFile)); boolean success = compilationTask.call(); fileManager.close(); if (success) { return null; } else { errorMessage = ""; for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) { errorMessage += diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Context.getLocale()) + "\n"; } return errorMessage; } } else { File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir); String[] commands = { "javac", "-classpath", System.getProperty("java.class.path"), "-d", outputFolder.getAbsolutePath(), javaFile }; // Start up the compiler File workingDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir); boolean success = LogicUtil.executeCommand(commands, workingDirectory); return success ? null : "Compilation error. (You must be using the JDK to see details.)"; } }
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 * /*from w w w . ja va 2s .c om*/ * @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; }
From source file:rita.compiler.CompileString.java
public static boolean containsPosition(int pos) { for (Diagnostic<? extends JavaFileObject> d : diagnostics) { if (d.getLineNumber() == pos) { diagnosticSelected = d;//ww w . j ava 2 s . co m return true; } } diagnosticSelected = null; return false; }
From source file:rita.widget.SourceCode.java
private void createCompileButton() { ImageIcon imgIcon = new ImageIcon(getClass().getResource("/images/sourcecode/bytecode.png")); this.compileButton = new JButton(imgIcon); this.compileButton.setToolTipText(Language.get("compileButton.tooltip")); final File basePathRobots = new File(Settings.getRobotsPath()); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // guardar el codigo fuente File sourcePath = saveSourceCode(); // COMPILA EN EL DIRECTORIO POR DEFAULT + LA RUTA DEL PACKAGE Collection<File> inFiles = createClassFiles(sourcePath); if (inFiles != null) { /* transformar el codigo fuente, que no tiene errores, para que los println aparezcan en una ventana. * La transformacin no deberia generar errores. *//*from w w w . j ava 2s .com*/ writeSourceFile(sourcePath, AgregadorDeConsola.getInstance().transformar(readSourceFile(sourcePath))); // volver a compilar, ahora con el codigo transformado inFiles = createClassFiles(sourcePath); if (inFiles != null) { createJarFile(inFiles); System.out.println("INSTALLPATH=" + Settings.getInstallPath()); System.out.println("SE ENVIA ROBOT:" + HelperEditor.currentRobotPackage + "." + HelperEditor.currentRobotName); // si quiere seleccionar enemigos if (Settings.getProperty("level.default").equals(Language.get("level.four"))) { try { DialogSelectEnemies.getInstance(); } catch (NoEnemiesException e2) { new MessageDialog(Language.get("robot.noEnemies"), MessageType.ERROR); } return; } else { callBatalla(null, null); } } else { System.out.println("Error en codigo transformado por AgregadorDeConsola"); } } } catch (Exception e1) { e1.printStackTrace(); } } /** Recibe un archivo conteniendo codigo fuente java, y crea el .class correspondiente * @param sourcePath El archivo .java * @return Un archivo conteniendo el path al .class generado, o null si no fue posible compilar porque hubo errores en el codigo fuente. */ private Collection<File> createClassFiles(File sourcePath) throws Exception, IOException { Collection<File> f = CompileString.compile(sourcePath, basePathRobots); if (CompileString.hasError()) { int cantErrores = 0; for (Diagnostic<?> diag : CompileString.diagnostics) { if (!diag.getKind().equals(Kind.WARNING)) { int line = (int) diag.getLineNumber(); int col = (int) diag.getColumnNumber(); if (line > 0 && col > 0) { highlightCode(line, col); cantErrores++; } } } if (cantErrores > 0) { new MessageDialog(Language.get("compile.error"), MessageType.ERROR); } return null; } else { return f; } } /* crea un jar con todas las clases del robot. el nombre del jar es el nombre del robot */ private void createJarFile(Collection<File> inFiles) throws FileNotFoundException, IOException { File jarFile = new File(basePathRobots, HelperEditor.currentRobotName + ".jar"); if (jarFile.exists()) { jarFile.delete(); } System.out.println("Path del JAR ==" + jarFile); jarFile.createNewFile(); FileOutputStream fos = new FileOutputStream(jarFile); BufferedOutputStream bo = new BufferedOutputStream(fos); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(fos, manifest); int basePathLength = basePathRobots.getAbsolutePath().length() + 1; // +1 para incluir al "/" final byte[] buf = new byte[1024]; int anz; try { // para todas las clases... for (File inFile : inFiles) { BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inFile)); try { String relative = inFile.getAbsolutePath().substring(basePathLength); // copia y agrega el archivo .class al jar JarEntry je2 = new JarEntry(relative); jarOutput.putNextEntry(je2); while ((anz = bi.read(buf)) != -1) { jarOutput.write(buf, 0, anz); } jarOutput.closeEntry(); } finally { try { bi.close(); } catch (IOException ignored) { } } } } finally { try { jarOutput.close(); } catch (IOException ignored) { } try { fos.close(); } catch (IOException ignored) { } try { bo.close(); } catch (IOException ignored) { } } } }); compileButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setCursor(Cursor.getDefaultCursor()); } }); compileButton.setBounds(MIN_WIDTH, 0, MAX_WIDTH - MIN_WIDTH, BUTTON_HEIGHT); compileButton.setFont(smallButtonFont); compileButton.setAlignmentX(LEFT_ALIGNMENT); compileButton.setText(Language.get("compileButton.title")); }