Example usage for org.apache.commons.jci.compilers CompilationResult getWarnings

List of usage examples for org.apache.commons.jci.compilers CompilationResult getWarnings

Introduction

In this page you can find the example usage for org.apache.commons.jci.compilers CompilationResult getWarnings.

Prototype

public CompilationProblem[] getWarnings() 

Source Link

Usage

From source file:org.apache.commons.jci.examples.commandline.CommandlineCompiler.java

public static void main(String[] args) throws Exception {

    final Options options = new Options();

    options.addOption(OptionBuilder.withArgName("a.jar:b.jar").hasArg().withValueSeparator(':')
            .withDescription("Specify where to find user class files").create("classpath"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Provide source compatibility with specified release").create("source"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Generate class files for specific VM version").create("target"));

    options.addOption(OptionBuilder.withArgName("path").hasArg()
            .withDescription("Specify where to find input source files").create("sourcepath"));

    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("Specify where to place generated class files").create("d"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of errors").create("Xmaxerrs"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of warning").create("Xmaxwarns"));

    options.addOption(OptionBuilder.withDescription("Generate no warnings").create("nowarn"));

    //        final HelpFormatter formatter = new HelpFormatter();
    //        formatter.printHelp("jci", options);

    final CommandLineParser parser = new GnuParser();
    final CommandLine cmd = parser.parse(options, args, true);

    ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    File sourcepath = new File(".");
    File targetpath = new File(".");
    int maxerrs = 10;
    int maxwarns = 10;
    final boolean nowarn = cmd.hasOption("nowarn");

    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    final JavaCompilerSettings settings = compiler.createDefaultSettings();

    for (Iterator it = cmd.iterator(); it.hasNext();) {
        final Option option = (Option) it.next();
        if ("classpath".equals(option.getOpt())) {
            final String[] values = option.getValues();
            final URL[] urls = new URL[values.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(values[i]).toURL();
            }/*from w  ww  . java2s  . c  o  m*/
            classloader = new URLClassLoader(urls);
        } else if ("source".equals(option.getOpt())) {
            settings.setSourceVersion(option.getValue());
        } else if ("target".equals(option.getOpt())) {
            settings.setTargetVersion(option.getValue());
        } else if ("sourcepath".equals(option.getOpt())) {
            sourcepath = new File(option.getValue());
        } else if ("d".equals(option.getOpt())) {
            targetpath = new File(option.getValue());
        } else if ("Xmaxerrs".equals(option.getOpt())) {
            maxerrs = Integer.parseInt(option.getValue());
        } else if ("Xmaxwarns".equals(option.getOpt())) {
            maxwarns = Integer.parseInt(option.getValue());
        }
    }

    final ResourceReader reader = new FileResourceReader(sourcepath);
    final ResourceStore store = new FileResourceStore(targetpath);

    final int maxErrors = maxerrs;
    final int maxWarnings = maxwarns;
    compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
        int errors = 0;
        int warnings = 0;

        public boolean handle(final CompilationProblem pProblem) {

            if (pProblem.isError()) {
                System.err.println(pProblem);

                errors++;

                if (errors >= maxErrors) {
                    return false;
                }
            } else {
                if (!nowarn) {
                    System.err.println(pProblem);
                }

                warnings++;

                if (warnings >= maxWarnings) {
                    return false;
                }
            }

            return true;
        }
    });

    final String[] resource = cmd.getArgs();

    for (int i = 0; i < resource.length; i++) {
        System.out.println("compiling " + resource[i]);
    }

    final CompilationResult result = compiler.compile(resource, reader, store, classloader);

    System.out.println(result.getErrors().length + " errors");
    System.out.println(result.getWarnings().length + " warnings");

}

From source file:org.raml.jaxrs.codegen.core.GeneratorTestCase.java

private void run(final JaxrsVersion jaxrsVersion, final boolean useJsr303Annotations) throws Exception {
    final Set<String> generatedSources = new HashSet<String>();

    final Configuration configuration = new Configuration();
    configuration.setJaxrsVersion(jaxrsVersion);
    configuration.setUseJsr303Annotations(useJsr303Annotations);
    configuration.setOutputDirectory(codegenOutputFolder.getRoot());

    configuration.setBasePackageName(TEST_BASE_PACKAGE);
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/full-config-with-patch.yaml")),
            configuration));//from   ww  w  .  ja  v a2 s . c  o  m

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".params");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(
                    getClass().getResourceAsStream("/org/raml/params/param-types-with-repeat.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".integration");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass()
                    .getResourceAsStream("/org/raml/integration/sales-enablement-api-with-collections.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".rules");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/rules/resource-full-ok.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(
                    getClass().getResourceAsStream("/org/raml/rules/resource-with-description-ok.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/rules/resource-with-uri.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".schema");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/schema/valid-xml-global.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/schema/valid-xml.yaml")),
            configuration));

    // test compile the classes
    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");

    final JavaCompilerSettings settings = compiler.createDefaultSettings();
    settings.setSourceVersion("1.5");
    settings.setTargetVersion("1.5");
    settings.setDebug(true);

    final String[] sources = generatedSources.toArray(EMPTY_STRING_ARRAY);
    System.out.println("Test compiling: " + Arrays.toString(sources));

    final FileResourceReader sourceReader = new FileResourceReader(codegenOutputFolder.getRoot());
    final FileResourceStore classWriter = new FileResourceStore(compilationOutputFolder.getRoot());
    final CompilationResult result = compiler.compile(sources, sourceReader, classWriter,
            Thread.currentThread().getContextClassLoader(), settings);

    assertThat(ToStringBuilder.reflectionToString(result.getErrors(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getErrors(), is(emptyArray()));

    assertThat(ToStringBuilder.reflectionToString(result.getWarnings(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getWarnings(), is(emptyArray()));

    // test load the classes with Jersey
    final URLClassLoader resourceClassLoader = new URLClassLoader(
            new URL[] { compilationOutputFolder.getRoot().toURI().toURL() });

    final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(resourceClassLoader);
        final ResourceConfig config = new PackagesResourceConfig(TEST_BASE_PACKAGE);

        assertThat("Found: " + config.getRootResourceClasses(), config.getRootResourceClasses(), hasSize(13));

        // TODO testing: actually send HTTP requests at the resources
    } finally {
        Thread.currentThread().setContextClassLoader(initialClassLoader);
    }
}

From source file:org.raml.jaxrs.codegen.core.MediaTypeGeneratorTestCase.java

private void run(final JaxrsVersion jaxrsVersion, final boolean useJsr303Annotations) throws Exception {
    final Set<String> generatedSources = new HashSet<String>();

    final Configuration configuration = new Configuration();
    configuration.setJaxrsVersion(jaxrsVersion);
    configuration.setUseJsr303Annotations(useJsr303Annotations);
    configuration.setOutputDirectory(codegenOutputFolder.getRoot());

    configuration.setBasePackageName(TEST_BASE_PACKAGE);
    String dirPath = getClass().getResource("/org/raml").getPath();

    configuration.setSourceDirectory(new File(dirPath));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(
                    getClass().getResourceAsStream("/org/raml/mediatype/application_octet-stream.yaml")),
            configuration));/* ww  w.  ja v  a  2s . c o m*/

    // test compile the classes
    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");

    final JavaCompilerSettings settings = compiler.createDefaultSettings();
    settings.setSourceVersion("1.5");
    settings.setTargetVersion("1.5");
    settings.setDebug(true);

    final String[] sources = generatedSources.toArray(EMPTY_STRING_ARRAY);

    final FileResourceReader sourceReader = new FileResourceReader(codegenOutputFolder.getRoot());
    final FileResourceStore classWriter = new FileResourceStore(compilationOutputFolder.getRoot());
    final CompilationResult result = compiler.compile(sources, sourceReader, classWriter,
            Thread.currentThread().getContextClassLoader(), settings);

    assertThat(ToStringBuilder.reflectionToString(result.getErrors(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getErrors(), is(emptyArray()));

    assertThat(ToStringBuilder.reflectionToString(result.getWarnings(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getWarnings(), is(emptyArray()));

    // test load the classes with Jersey
    final URLClassLoader resourceClassLoader = new URLClassLoader(
            new URL[] { compilationOutputFolder.getRoot().toURI().toURL() });

    final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(resourceClassLoader);
        final ResourceConfig config = new PackagesResourceConfig(TEST_BASE_PACKAGE);

        Set<Class<?>> classes = config.getClasses();

        Iterator<Class<?>> it = classes.iterator();
        Class<?> something = it.next();
        Method[] methods = something.getDeclaredMethods();

        Method methodWithInputStreamParam = methods[0];

        assertEquals(InputStream.class.getName(), methodWithInputStreamParam.getParameterTypes()[0].getName());
    } finally {
        Thread.currentThread().setContextClassLoader(initialClassLoader);
    }
}

From source file:org.raml.jaxrs.codegen.core.ResponseWrapperGeneratorTestCase.java

private void run(final JaxrsVersion jaxrsVersion, final boolean useJsr303Annotations) throws Exception {
    final Set<String> generatedSources = new HashSet<String>();

    final Configuration configuration = new Configuration();
    configuration.setJaxrsVersion(jaxrsVersion);
    configuration.setUseJsr303Annotations(useJsr303Annotations);
    configuration.setOutputDirectory(codegenOutputFolder.getRoot());

    configuration.setBasePackageName(TEST_BASE_PACKAGE);
    String dirPath = getClass().getResource("/org/raml").getPath();

    configuration.setSourceDirectory(new File(dirPath));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/responses/wrapper.yaml")),
            configuration));/*from w w w .  ja v a  2 s .  co m*/

    // test compile the classes
    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");

    final JavaCompilerSettings settings = compiler.createDefaultSettings();
    settings.setSourceVersion("1.5");
    settings.setTargetVersion("1.5");
    settings.setDebug(true);

    final String[] sources = generatedSources.toArray(EMPTY_STRING_ARRAY);

    final FileResourceReader sourceReader = new FileResourceReader(codegenOutputFolder.getRoot());
    final FileResourceStore classWriter = new FileResourceStore(compilationOutputFolder.getRoot());
    final CompilationResult result = compiler.compile(sources, sourceReader, classWriter,
            Thread.currentThread().getContextClassLoader(), settings);
    CompilationProblem[] errors = result.getErrors();
    assertThat(ToStringBuilder.reflectionToString(errors, ToStringStyle.SHORT_PREFIX_STYLE), errors,
            is(emptyArray()));
    assertThat(ToStringBuilder.reflectionToString(result.getWarnings(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getWarnings(), is(emptyArray()));
}

From source file:org.vafer.drift.generator.JavaGeneratorTestCase.java

private CompilationResult compile(final InputStream input) throws IOException {
    final Schema schema = Schema.build(input);

    final JavaGenerator javaGenerator = new JavaGenerator("org.vafer.drift.generator.generated");
    final MemoryCodeWriter writer = new MemoryCodeWriter();
    javaGenerator.generate(schema, writer);

    final ResourceStore store = new MemoryResourceStore();
    final ResourceReader reader = writer;
    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");

    assertNotNull(compiler);/*from   w  ww.j ava 2 s  . c o  m*/

    final CompilationResult result = compiler.compile(writer.getNames(), reader, store);

    final CompilationProblem[] errors = result.getErrors();

    final Set<String> fileNames = new HashSet<String>();

    for (int i = 0; i < errors.length; i++) {
        System.out.println(errors[i]);
        fileNames.add(errors[i].getFileName());
    }

    final CompilationProblem[] warnings = result.getWarnings();
    for (int i = 0; i < warnings.length; i++) {
        System.out.println(warnings[i]);
        fileNames.add(warnings[i].getFileName());
    }

    if (fileNames.size() > 0) {
        System.out.println("Writing out files with problems");

        for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
            final String name = it.next();
            final String content = new String(reader.getBytes(name));

            final File fullPath = new File(dir, name);

            fullPath.getParentFile().mkdirs();

            System.out.println(" writing " + fullPath.getAbsolutePath());

            FileUtils.writeStringToFile(fullPath, content);
        }
    }

    return result;
}

From source file:org.xchain.framework.jsl.TemplateCompiler.java

/**
 * Compiles the source result.// w  w w.j a  v  a 2  s .  c om
 *
 * @throws SAXException if there is a compilation error in the source file.
 */
public Class compileTemplate(SourceResult result) throws SAXException {
    // add the resource to the reader.
    try {
        resourceReader.add(result.getSourceResourceName(), result.getSource().getBytes(SOURCE_ENCODING));
    } catch (UnsupportedEncodingException uee) {
        throw new SAXException("Could not build source in the encoding '" + SOURCE_ENCODING + "'.", uee);
    }

    // create the resource store.
    ResourceStore resourceStore = new MemoryResourceStore();

    // compile the result.
    CompilationResult compilationResult = compiler.compile(new String[] { result.getSourceResourceName() },
            resourceReader, resourceStore, templateClassLoader, settings);

    // handle any errors.
    if (compilationResult.getErrors().length > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Source that would not complile:\n" + result.getSource());
            for (CompilationProblem error : compilationResult.getErrors()) {
                log.debug("Error (" + error.getStartLine() + ", " + error.getStartColumn() + "):"
                        + error.getMessage());
            }
        }
        // TODO: Make this message better.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Could not compile template source. Errors:\n");
        for (CompilationProblem error : compilationResult.getErrors()) {
            stringBuilder.append("(" + error.getStartLine() + ", " + error.getStartColumn() + "):"
                    + error.getMessage() + "\n");
        }
        throw new SAXException(stringBuilder.toString());
    }

    // handle any errors.
    if (log.isDebugEnabled()) {
        for (CompilationProblem warning : compilationResult.getWarnings()) {
            log.debug("Compilation warning(" + warning.getStartLine() + ", " + warning.getStartColumn() + "):"
                    + warning.getMessage());
        }
    }

    byte[] compiledBytes = resourceStore.read(result.getClassResourceName());

    templateClassLoader.publicDefineClass(result.getClassName(), compiledBytes, 0, compiledBytes.length);
    Class templateClass = null;

    try {
        templateClass = templateClassLoader.loadClass(result.getClassName());
    } catch (Exception e) {
        throw new SAXException("Could not load the class '" + result.getClassName() + "'.", e);
    }

    return templateClass;
}