Example usage for org.apache.commons.jci.compilers JavaCompilerFactory JavaCompilerFactory

List of usage examples for org.apache.commons.jci.compilers JavaCompilerFactory JavaCompilerFactory

Introduction

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

Prototype

JavaCompilerFactory

Source Link

Usage

From source file:me.jaimegarza.syntax.test.AbstractGenerationBase.java

protected CompilationResult compileJavaFile(File source, File sourceDir) {
    JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    String sources[] = new String[1];
    sources[0] = source.getName();/*from w w  w  .j  a  v a 2 s  . c  o  m*/
    CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir),
            new FileResourceStore(sourceDir));
    return result;
}

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   ww w. j av  a2 s  . co  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.apache.commons.jci.examples.serverpages.ServerPageServlet.java

public void init() throws ServletException {
    super.init();

    final File serverpagesDir = new File(
            getServletContext().getRealPath("/") + getInitParameter("serverpagesDir"));

    log("Monitoring serverpages in " + serverpagesDir);

    final TransactionalResourceStore store = new TransactionalResourceStore(new MemoryResourceStore()) {

        private Set<String> newClasses;
        private Map<String, HttpServlet> newServletsByClassname;

        public void onStart() {
            super.onStart();

            newClasses = new HashSet<String>();
            newServletsByClassname = new HashMap<String, HttpServlet>(servletsByClassname);
        }/*from  ww  w . j  av a  2 s  .  c o m*/

        public void onStop() {
            super.onStop();

            boolean reload = false;
            for (String clazzName : newClasses) {
                try {
                    final Class clazz = classloader.loadClass(clazzName);

                    if (!HttpServlet.class.isAssignableFrom(clazz)) {
                        log(clazzName + " is not a servlet");
                        continue;
                    }

                    // create new instance of jsp page
                    final HttpServlet servlet = (HttpServlet) clazz.newInstance();
                    newServletsByClassname.put(clazzName, servlet);

                    reload = true;
                } catch (Exception e) {
                    log("", e);
                }
            }

            if (reload) {
                log("Activating new map of servlets " + newServletsByClassname);
                servletsByClassname = newServletsByClassname;
            }
        }

        public void write(String pResourceName, byte[] pResourceData) {
            super.write(pResourceName, pResourceData);

            if (pResourceName.endsWith(".class")) {

                // compiler writes a new class, remember the classes to reload
                newClasses.add(pResourceName.replace('/', '.').substring(0,
                        pResourceName.length() - ".class".length()));
            }
        }

    };

    // listener that generates the java code from the jsp page and provides that to the compiler
    jspListener = new CompilingListener(new JavaCompilerFactory().createCompiler("eclipse"), store) {

        private final JspGenerator transformer = new JspGenerator();
        private final Map<String, byte[]> sources = new HashMap<String, byte[]>();
        private final Set<String> resourceToCompile = new HashSet<String>();

        public void onStart(FilesystemAlterationObserver pObserver) {
            super.onStart(pObserver);

            resourceToCompile.clear();
        }

        public void onFileChange(File pFile) {
            if (pFile.getName().endsWith(".jsp")) {
                final String resourceName = ConversionUtils
                        .stripExtension(getSourceNameFromFile(observer, pFile)) + ".java";

                log("Updating " + resourceName);

                sources.put(resourceName, transformer.generateJavaSource(resourceName, pFile));

                resourceToCompile.add(resourceName);
            }
            super.onFileChange(pFile);
        }

        public void onFileCreate(File pFile) {
            if (pFile.getName().endsWith(".jsp")) {
                final String resourceName = ConversionUtils
                        .stripExtension(getSourceNameFromFile(observer, pFile)) + ".java";

                log("Creating " + resourceName);

                sources.put(resourceName, transformer.generateJavaSource(resourceName, pFile));

                resourceToCompile.add(resourceName);
            }
            super.onFileCreate(pFile);
        }

        public String[] getResourcesToCompile(FilesystemAlterationObserver pObserver) {
            // we only want to compile the jsp pages
            final String[] resourceNames = new String[resourceToCompile.size()];
            resourceToCompile.toArray(resourceNames);
            return resourceNames;
        }

        public ResourceReader getReader(final FilesystemAlterationObserver pObserver) {
            return new JspReader(sources, super.getReader(pObserver));
        }
    };
    jspListener.addReloadNotificationListener(classloader);

    fam = new FilesystemAlterationMonitor();
    fam.addListener(serverpagesDir, jspListener);
    fam.start();
}

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  .j a v a  2 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));/*from   w w w. j  a v a 2 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);

    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 ww w  . java 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  w w  .j a va2s .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

public void init(ClassLoader classLoader) {
    this.templateClassLoader = new TemplateClassLoader(classLoader);

    resourceReader = new WrappedResourceReader(new MemoryResourceReader(), templateClassLoader);

    settings = new JavaCompilerSettings();
    settings.setSourceVersion(SOURCE_VERSION);
    settings.setSourceEncoding(SOURCE_ENCODING);
    settings.setTargetVersion(TARGET_VERSION);

    compiler = new JavaCompilerFactory().createCompiler("eclipse");
}