Example usage for org.apache.commons.jci.compilers JavaCompilerSettings setTargetVersion

List of usage examples for org.apache.commons.jci.compilers JavaCompilerSettings setTargetVersion

Introduction

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

Prototype

public void setTargetVersion(final String pTargetVersion) 

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  w  w .  jav a2  s  . 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  www . ja  v  a 2s.  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));/*from  www .  j av  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));//  w  w  w . j av  a2 s  .  c  om

    // 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()));
}