View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.jci.examples.commandline;
19  
20  import java.io.File;
21  import java.net.URL;
22  import java.net.URLClassLoader;
23  import java.util.Iterator;
24  
25  import org.apache.commons.cli.CommandLine;
26  import org.apache.commons.cli.CommandLineParser;
27  import org.apache.commons.cli.GnuParser;
28  import org.apache.commons.cli.Option;
29  import org.apache.commons.cli.OptionBuilder;
30  import org.apache.commons.cli.Options;
31  import org.apache.commons.jci.compilers.CompilationResult;
32  import org.apache.commons.jci.compilers.JavaCompiler;
33  import org.apache.commons.jci.compilers.JavaCompilerFactory;
34  import org.apache.commons.jci.compilers.JavaCompilerSettings;
35  import org.apache.commons.jci.problems.CompilationProblem;
36  import org.apache.commons.jci.problems.CompilationProblemHandler;
37  import org.apache.commons.jci.readers.FileResourceReader;
38  import org.apache.commons.jci.readers.ResourceReader;
39  import org.apache.commons.jci.stores.FileResourceStore;
40  import org.apache.commons.jci.stores.ResourceStore;
41  
42  /**
43   * A simple front end to jci mimicking the javac command line
44   *
45   * @author tcurdt
46   */
47  public final class CommandlineCompiler {
48      
49      public static void main( String[] args ) throws Exception {
50  
51          final Options options = new Options();
52  
53          options.addOption(
54                  OptionBuilder.withArgName("a.jar:b.jar")
55                      .hasArg()
56                      .withValueSeparator( ':' )
57                      .withDescription("Specify where to find user class files")
58                      .create( "classpath" ));
59  
60          options.addOption(
61                  OptionBuilder.withArgName("release")
62                      .hasArg()
63                      .withDescription("Provide source compatibility with specified release")
64                      .create( "source" ));
65  
66          options.addOption(
67                  OptionBuilder.withArgName("release")
68                      .hasArg()
69                      .withDescription("Generate class files for specific VM version")
70                      .create( "target" ));
71  
72          options.addOption(
73                  OptionBuilder.withArgName("path")
74                      .hasArg()
75                      .withDescription("Specify where to find input source files")
76                      .create( "sourcepath" ));
77  
78          options.addOption(
79                  OptionBuilder.withArgName("directory")
80                      .hasArg()
81                      .withDescription("Specify where to place generated class files")
82                      .create( "d" ));
83  
84          options.addOption(
85                  OptionBuilder.withArgName("num")
86                      .hasArg()
87                      .withDescription("Stop compilation after these number of errors")
88                      .create( "Xmaxerrs" ));
89  
90          options.addOption(
91                  OptionBuilder.withArgName("num")
92                      .hasArg()
93                      .withDescription("Stop compilation after these number of warning")
94                      .create( "Xmaxwarns" ));
95  
96          options.addOption(
97                  OptionBuilder.withDescription("Generate no warnings")
98                      .create( "nowarn" ));
99  
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 }