Example usage for javax.tools Diagnostic getKind

List of usage examples for javax.tools Diagnostic getKind

Introduction

In this page you can find the example usage for javax.tools Diagnostic getKind.

Prototype

Kind getKind();

Source Link

Document

Returns the kind of this diagnostic, for example, error or warning.

Usage

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

@Test
public void testDiamondOptimizedHierarchyCompilation() {

    OntoModel results = factory.buildModel("diamond",
            ResourceFactory.newClassPathResource("ontologies/diamondProp2.manchester.owl"),
            DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED));

    assertTrue(results.isHierarchyConsistent());

    compiler = new OntoModelCompiler(results, folder.getRoot());

    // ****** Stream the java interfaces
    boolean javaOut = compiler.streamJavaInterfaces(true);

    assertTrue(javaOut);/*from  w  w w.  ja  v  a2  s  . c o m*/

    // ****** Stream the XSDs, the JaxB customizations abd the persistence configuration
    boolean xsdOut = compiler.streamXSDsWithBindings(true);

    assertTrue(xsdOut);
    File f = new File(compiler.getMetaInfDir() + File.separator + results.getDefaultPackage() + ".xsd");
    try {
        Document dox = parseXML(f, true);

        NodeList types = dox.getElementsByTagName("xsd:complexType");
        assertEquals(10, types.getLength());

        NodeList elements = dox.getElementsByTagName("xsd:element");
        assertEquals(12 + 14, elements.getLength());
    } catch (Exception e) {
        fail(e.getMessage());
    }

    showDirContent(folder);

    File b = new File(compiler.getMetaInfDir() + File.separator + results.getDefaultPackage() + ".xjb");
    try {
        Document dox = parseXML(b, false);

        NodeList types = dox.getElementsByTagName("bindings");
        assertEquals(28, types.getLength());
    } catch (Exception e) {
        fail(e.getMessage());
    }

    showDirContent(folder);

    // ****** Generate sources
    boolean mojo = compiler.mojo(
            Arrays.asList("-extension", "-Xjaxbindex", "-Xannotate", "-Xinheritance", "-XtoString",
                    "-Xcopyable", "-Xmergeable", "-Xvalue-constructor", "-Xfluent-api", "-Xkey-equality",
                    "-Xsem-accessors", "-Xdefault-constructor", "-Xmetadata", "-Xinject-code"),
            OntoModelCompiler.MOJO_VARIANTS.JPA2);

    assertTrue(mojo);

    File klass = new File(compiler.getXjcDir().getPath() + File.separator
            + results.getDefaultPackage().replace(".", File.separator) + File.separator + "BottomImpl.java");
    printSourceFile(klass, System.out);

    showDirContent(folder);

    // ****** Do compile sources
    List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler.doCompile();

    boolean success = true;
    for (Diagnostic diag : diagnostics) {
        System.out.println("ERROR : " + diag);
        if (diag.getKind() == Diagnostic.Kind.ERROR) {
            success = false;
        }
    }
    assertTrue(success);

    showDirContent(folder);

    try {
        parseXML(new File(compiler.getBinDir() + "/META-INF/" + "persistence.xml"), true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        ClassLoader urlKL = new URLClassLoader(new URL[] { compiler.getBinDir().toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        testPersistenceWithInstance(urlKL, "org.jboss.drools.semantics.diamond2.Bottom", results.getName());

    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        fail(e.getMessage());
    }

}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

@Test
public void testIncrementalCompilation() {
    try {//from w  w w  .  j a va2 s .co m

        OntoModel diamond = factory.buildModel("diamondX",
                ResourceFactory.newClassPathResource("ontologies/diamondProp.manchester.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED));

        compiler = new OntoModelCompiler(diamond, folder.getRoot());

        List<Diagnostic<? extends JavaFileObject>> diag1 = compiler
                .compileOnTheFly(OntoModelCompiler.minimalOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        for (Diagnostic<?> dx : diag1) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        ClassLoader urlKL = new URLClassLoader(new URL[] { compiler.getBinDir().toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        OntoModel results = factory.buildModel("diamondInc",
                ResourceFactory.newClassPathResource("ontologies/dependency.test.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED), urlKL);

        System.out.println(results);

        Class bot = Class.forName("org.jboss.drools.semantics.diamond.BottomImpl", true, urlKL);
        Class botIF = Class.forName("org.jboss.drools.semantics.diamond.Bottom", true, urlKL);
        Assert.assertNotNull(bot);
        Assert.assertNotNull(botIF);
        Object botInst = bot.newInstance();
        Assert.assertNotNull(botInst);

        OntoModelCompiler compiler2 = new OntoModelCompiler(results, folder.getRoot());

        compiler2.fixResolvedClasses();

        compiler2.streamJavaInterfaces(false);
        compiler2.streamXSDsWithBindings(true);

        compiler2.mojo(OntoModelCompiler.defaultOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        showDirContent(folder);

        File unImplBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");
        assertFalse(unImplBoundLeft.exists());
        File implBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "LeftImpl.java");
        assertTrue(implBoundLeft.exists());

        File leftInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");

        assertTrue(leftInterface.exists());

        List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler2.doCompile();

        for (Diagnostic<?> dx : diagnostics) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        Document dox = parseXML(new File(compiler2.getBinDir().getPath() + "/META-INF/persistence.xml"), false);
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile("//persistence-unit/@name");
        assertEquals("diamondX", (String) expr.evaluate(dox, XPathConstants.STRING));

        File YInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "X.java");
        assertTrue(YInterface.exists());

        Class colf = Class.forName("some.dependency.test.ChildOfLeftImpl", true, urlKL);
        Assert.assertNotNull(colf);
        Object colfInst = colf.newInstance();

        List<String> hierarchy = getHierarchy(colf);
        assertTrue(hierarchy.contains("some.dependency.test.ChildOfLeftImpl"));
        assertTrue(hierarchy.contains("some.dependency.test.org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.C0Impl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.TopImpl"));
        assertTrue(hierarchy.contains("org.w3._2002._07.owl.ThingImpl"));

        Set<String> itfHierarchy = getIFHierarchy(colf);

        System.err.println(itfHierarchy.containsAll(
                Arrays.asList("org.jboss.drools.semantics.diamond.C1", "org.jboss.drools.semantics.diamond.C0",
                        "some.dependency.test.org.jboss.drools.semantics.diamond.Left",
                        "some.dependency.test.ChildOfLeft", "org.jboss.drools.semantics.diamond.Left",
                        "org.jboss.drools.semantics.diamond.Top", "com.clarkparsia.empire.EmpireGenerated",
                        "org.w3._2002._07.owl.Thing", "java.io.Serializable", "org.drools.semantics.Thing",
                        "com.clarkparsia.empire.SupportsRdfId")));

        Method getter1 = colf.getMethod("getAnotherLeftProp");
        assertNotNull(getter1);
        Method getter2 = colf.getMethod("getImportantProp");
        assertNotNull(getter2);

        for (Method m : colf.getMethods()) {
            if (m.getName().equals("addImportantProp")) {
                m.getName();
            }
        }

        Method adder = colf.getMethod("addImportantProp", botIF);
        assertNotNull(adder);
        adder.invoke(colfInst, botInst);
        List l = (List) getter2.invoke(colfInst);
        assertEquals(1, l.size());

        File off = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left_Off.java");
        assertFalse(off.exists());

        testPersistenceWithInstance(urlKL, "org.jboss.drools.semantics.diamond.Bottom", diamond.getName());
        System.out.println(" Done");

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

}

From source file:org.jdto.tools.verifiercases.NestedIncorrectVerifierCase.java

@Override
public void test(List<Diagnostic<? extends JavaFileObject>> diagnostics, String stdoutS, Boolean result) {

    //in this case we should have a compilation error saying that annotation has no effect on setters.

    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        if (diagnostic.getKind() == Kind.MANDATORY_WARNING) {

            if (!StringUtils.containsIgnoreCase(diagnostic.getMessage(null), "not found on type")) {
                continue;
            } else {
                //test should succeed.
                return;
            }// ww  w .ja va 2 s.c o  m

        }
    }

    fail("No relevant compilation warning found.");
}

From source file:org.jdto.tools.verifiercases.SetterAnnotatedVerifierCase.java

@Override
public void test(List<Diagnostic<? extends JavaFileObject>> diagnostics, String stdoutS, Boolean result) {

    //in this case we should have a compilation error saying that annotation has no effect on setters.

    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        if (diagnostic.getKind() == Kind.MANDATORY_WARNING) {

            if (!StringUtils.containsIgnoreCase(diagnostic.getMessage(null), "Setter")) {
                continue;
            } else {
                //test should succeed.
                return;
            }//  w  w  w  .ja v  a  2s  .  c o  m

        }
    }

    fail("A warning saying that setters mustn't be annotated should have been printed.");
}

From source file:org.jsonschema2pojo.integration.CompilerWarningIT.java

public static List<Diagnostic<? extends JavaFileObject>> warnings(
        List<Diagnostic<? extends JavaFileObject>> all) {
    List<Diagnostic<? extends JavaFileObject>> warnings = new ArrayList<Diagnostic<? extends JavaFileObject>>();
    for (Diagnostic<? extends JavaFileObject> entry : all) {
        if (entry.getKind() == Kind.WARNING) {
            warnings.add(entry);/*from w  w  w. j a  va 2  s .  com*/
        }
    }
    return warnings;
}

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 w  ww  . j a  va2s.c  om
        }
    }
    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:org.wso2.carbon.config.annotationprocessor.AnnotationProcessorTest.java

private void verifyCompilationErrors(List<Diagnostic<? extends JavaFileObject>> diagnostics, Boolean result) {
    //no mandatory warnings or compilation errors should be found.
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        if (diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING
                || diagnostic.getKind() == Diagnostic.Kind.ERROR) {
            fail("Failed with message: " + diagnostic.getMessage(null));
        }/* ww  w .  j av a 2 s . co  m*/
    }
    assertEquals("Files should have no compilation errors", Boolean.TRUE, result);
}

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.j  a  v a 2 s  . 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.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.
                     *//*www  .  ja va  2 s.c o m*/
                    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"));
}