    001    /*
    002     * Licensed to the Apache Software Foundation (ASF) under one or more
    003     * contributor license agreements.  See the NOTICE file distributed with
    004     * this work for additional information regarding copyright ownership.
    005     * The ASF licenses this file to You under the Apache License, Version 2.0
    006     * (the "License"); you may not use this file except in compliance with
    007     * the License.  You may obtain a copy of the License at
    008     *
    009     *      http://www.apache.org/licenses/LICENSE-2.0
    010     *
    011     * Unless required by applicable law or agreed to in writing, software
    012     * distributed under the License is distributed on an "AS IS" BASIS,
    013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014     * See the License for the specific language governing permissions and
    015     * limitations under the License.
    016     */
    017
    018    package org.apache.commons.jci.examples.commandline;
    019
    020    import java.io.File;
    021    import java.net.URL;
    022    import java.net.URLClassLoader;
    023    import java.util.Iterator;
    024
    025    import org.apache.commons.cli.CommandLine;
    026    import org.apache.commons.cli.CommandLineParser;
    027    import org.apache.commons.cli.GnuParser;
    028    import org.apache.commons.cli.Option;
    029    import org.apache.commons.cli.OptionBuilder;
    030    import org.apache.commons.cli.Options;
    031    import org.apache.commons.jci.compilers.CompilationResult;
    032    import org.apache.commons.jci.compilers.JavaCompiler;
    033    import org.apache.commons.jci.compilers.JavaCompilerFactory;
    034    import org.apache.commons.jci.compilers.JavaCompilerSettings;
    035    import org.apache.commons.jci.problems.CompilationProblem;
    036    import org.apache.commons.jci.problems.CompilationProblemHandler;
    037    import org.apache.commons.jci.readers.FileResourceReader;
    038    import org.apache.commons.jci.readers.ResourceReader;
    039    import org.apache.commons.jci.stores.FileResourceStore;
    040    import org.apache.commons.jci.stores.ResourceStore;
    041
    042    /**
    043     * A simple front end to jci mimicking the javac command line
    044     *
    045     * @author tcurdt
    046     */
    047    public final class CommandlineCompiler {
    048
    049        public static void main( String[] args ) throws Exception {
    050
    051            final Options options = new Options();
    052
    053            options.addOption(
    054                    OptionBuilder.withArgName("a.jar:b.jar")
    055                        .hasArg()
    056                        .withValueSeparator( ':' )
    057                        .withDescription("Specify where to find user class files")
    058                        .create( "classpath" ));
    059
    060            options.addOption(
    061                    OptionBuilder.withArgName("release")
    062                        .hasArg()
    063                        .withDescription("Provide source compatibility with specified release")
    064                        .create( "source" ));
    065
    066            options.addOption(
    067                    OptionBuilder.withArgName("release")
    068                        .hasArg()
    069                        .withDescription("Generate class files for specific VM version")
    070                        .create( "target" ));
    071
    072            options.addOption(
    073                    OptionBuilder.withArgName("path")
    074                        .hasArg()
    075                        .withDescription("Specify where to find input source files")
    076                        .create( "sourcepath" ));
    077
    078            options.addOption(
    079                    OptionBuilder.withArgName("directory")
    080                        .hasArg()
    081                        .withDescription("Specify where to place generated class files")
    082                        .create( "d" ));
    083
    084            options.addOption(
    085                    OptionBuilder.withArgName("num")
    086                        .hasArg()
    087                        .withDescription("Stop compilation after these number of errors")
    088                        .create( "Xmaxerrs" ));
    089
    090            options.addOption(
    091                    OptionBuilder.withArgName("num")
    092                        .hasArg()
    093                        .withDescription("Stop compilation after these number of warning")
    094                        .create( "Xmaxwarns" ));
    095
    096            options.addOption(
    097                    OptionBuilder.withDescription("Generate no warnings")
    098                        .create( "nowarn" ));
    099
    100    //        final HelpFormatter formatter = new HelpFormatter();
    101    //        formatter.printHelp("jci", options);
    102
    103            final CommandLineParser parser = new GnuParser();
    104            final CommandLine cmd = parser.parse(options, args, true);
    105
    106            ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    107            File sourcepath = new File(".");
    108            File targetpath = new File(".");
    109            int maxerrs = 10;
    110            int maxwarns = 10;
    111            final boolean nowarn = cmd.hasOption("nowarn");
    112
    113
    114            final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    115            final JavaCompilerSettings settings = compiler.createDefaultSettings();
    116
    117
    118            for (Iterator it = cmd.iterator(); it.hasNext();) {
    119                final Option option = (Option) it.next();
    120                if ("classpath".equals(option.getOpt())) {
    121                    final String[] values = option.getValues();
    122                    final URL[] urls = new URL[values.length];
    123                    for (int i = 0; i < urls.length; i++) {
    124                        urls[i] = new File(values[i]).toURL();
    125                    }
    126                    classloader = new URLClassLoader(urls);
    127                } else if ("source".equals(option.getOpt())) {
    128                    settings.setSourceVersion(option.getValue());
    129                } else if ("target".equals(option.getOpt())) {
    130                    settings.setTargetVersion(option.getValue());
    131                } else if ("sourcepath".equals(option.getOpt())) {
    132                    sourcepath = new File(option.getValue());
    133                } else if ("d".equals(option.getOpt())) {
    134                    targetpath = new File(option.getValue());
    135                } else if ("Xmaxerrs".equals(option.getOpt())) {
    136                    maxerrs = Integer.parseInt(option.getValue());
    137                } else if ("Xmaxwarns".equals(option.getOpt())) {
    138                    maxwarns = Integer.parseInt(option.getValue());
    139                }
    140            }
    141
    142            final ResourceReader reader = new FileResourceReader(sourcepath);
    143            final ResourceStore store = new FileResourceStore(targetpath);
    144
    145            final int maxErrors = maxerrs;
    146            final int maxWarnings = maxwarns;
    147            compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
    148                int errors = 0;
    149                int warnings = 0;
    150                public boolean handle(final CompilationProblem pProblem) {
    151
    152                    if (pProblem.isError()) {
    153                        System.err.println(pProblem);
    154
    155                        errors++;
    156
    157                        if (errors >= maxErrors) {
    158                            return false;
    159                        }
    160                    } else {
    161                        if (!nowarn) {
    162                            System.err.println(pProblem);
    163                        }
    164
    165                        warnings++;
    166
    167                        if (warnings >= maxWarnings) {
    168                            return false;
    169                        }
    170                    }
    171
    172                    return true;
    173                }
    174            });
    175
    176            final String[] resource = cmd.getArgs();
    177
    178            for (int i = 0; i < resource.length; i++) {
    179                System.out.println("compiling " + resource[i]);
    180            }
    181
    182            final CompilationResult result = compiler.compile(resource, reader, store, classloader);
    183
    184            System.out.println( result.getErrors().length + " errors");
    185            System.out.println( result.getWarnings().length + " warnings");
    186
    187        }
    188    }