package com.sun.tools.internal.jxc;
import com.sun.tools.internal.jxc.ap.Options;
import com.sun.tools.internal.xjc.BadCommandLineException;
import com.sun.xml.internal.bind.util.Which;
import javax.lang.model.SourceVersion;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.OptionChecker;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.xml.bind.JAXBContext;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SchemaGenerator {
private static final Logger LOGGER = Logger.getLogger(SchemaGenerator.class.getName());
public static void main(String[] args) throws Exception {
System.exit(run(args));
}
public static int run(String[] args) throws Exception {
try {
ClassLoader cl = SecureLoader.getClassClassLoader(SchemaGenerator.class);
if (cl==null) {
cl = SecureLoader.getSystemClassLoader();
}
return run(args, cl);
} catch(Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return -1;
}
}
public static int run(String[] args, ClassLoader classLoader) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
final Options options = new Options();
if (args.length ==0) {
usage();
return -1;
}
for (String arg : args) {
if (arg.equals("-help")) {
usage();
return -1;
}
if (arg.equals("-version")) {
System.out.println(Messages.VERSION.format());
return -1;
}
if (arg.equals("-fullversion")) {
System.out.println(Messages.FULLVERSION.format());
return -1;
}
}
try {
options.parseArguments(args);
} catch (BadCommandLineException e) {
System.out.println(e.getMessage());
System.out.println();
usage();
return -1;
}
Class schemagenRunner = classLoader.loadClass(Runner.class.getName());
Method compileMethod = schemagenRunner.getDeclaredMethod("compile",String[].class,File.class);
List<String> aptargs = new ArrayList<String>();
if (options.encoding != null) {
aptargs.add("-encoding");
aptargs.add(options.encoding);
}
aptargs.add("-cp");
aptargs.add(setClasspath(options.classpath));
aptargs.add("--add-modules");
aptargs.add("java.xml.bind");
if(options.targetDir!=null) {
aptargs.add("-d");
aptargs.add(options.targetDir.getPath());
}
aptargs.addAll(options.arguments);
String[] argsarray = aptargs.toArray(new String[aptargs.size()]);
return ((Boolean) compileMethod.invoke(null, argsarray, options.episodeFile)) ? 0 : 1;
}
private static String setClasspath(String givenClasspath) {
StringBuilder cp = new StringBuilder();
appendPath(cp, givenClasspath);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
while (cl != null) {
if (cl instanceof URLClassLoader) {
for (URL url : ((URLClassLoader) cl).getURLs()) {
try {
appendPath(cp,new File(url.toURI()).getPath());
} catch(URISyntaxException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
cl = cl.getParent();
}
appendPath(cp, findJaxbApiJar());
return cp.toString();
}
private static void appendPath(StringBuilder cp, String url) {
if (url == null || url.trim().isEmpty())
return;
if (cp.length() != 0)
cp.append(File.pathSeparatorChar);
cp.append(url);
}
private static String findJaxbApiJar() {
String url = Which.which(JAXBContext.class);
if(url==null) return null;
if(!url.startsWith("jar:") || url.lastIndexOf('!')==-1)
return null;
String jarFileUrl = url.substring(4,url.lastIndexOf('!'));
if(!jarFileUrl.startsWith("file:"))
return null;
try {
File f = new File(new URL(jarFileUrl).toURI());
if (f.exists() && f.getName().endsWith(".jar")) {
return f.getPath();
}
f = new File(new URL(jarFileUrl).getFile());
if (f.exists() && f.getName().endsWith(".jar")) {
return f.getPath();
}
} catch (URISyntaxException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
} catch (MalformedURLException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
return null;
}
private static void usage( ) {
System.out.println(Messages.USAGE.format());
}
public static final class Runner {
public static boolean compile(String[] args, File episode) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
List<String> unrecognizedOptions = options.getUnrecognizedOptions();
if (!unrecognizedOptions.isEmpty()) {
LOGGER.log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
}
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
JavaCompiler.CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
options.getRecognizedOptions(),
options.getClassNames(),
compilationUnits);
com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
if (episode != null)
r.setEpisodeFile(episode);
task.setProcessors(Collections.singleton(r));
boolean res = task.call();
for( Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics() ) {
System.err.println(d.toString());
}
return res;
}
}
private static final class JavacOptions {
private final List<String> recognizedOptions;
private final List<String> classNames;
private final List<File> files;
private final List<String> unrecognizedOptions;
private JavacOptions(List<String> recognizedOptions, List<String> classNames, List<File> files,
List<String> unrecognizedOptions) {
this.recognizedOptions = recognizedOptions;
this.classNames = classNames;
this.files = files;
this.unrecognizedOptions = unrecognizedOptions;
}
public static JavacOptions parse(OptionChecker primary, OptionChecker secondary, String... arguments) {
List<String> recognizedOptions = new ArrayList<String>();
List<String> unrecognizedOptions = new ArrayList<String>();
List<String> classNames = new ArrayList<String>();
List<File> files = new ArrayList<File>();
for (int i = 0; i < arguments.length; i++) {
String argument = arguments[i];
int optionCount = primary.isSupportedOption(argument);
if (optionCount < 0) {
optionCount = secondary.isSupportedOption(argument);
}
if (optionCount < 0) {
File file = new File(argument);
if (file.exists())
files.add(file);
else if (SourceVersion.isName(argument))
classNames.add(argument);
else
unrecognizedOptions.add(argument);
} else {
for (int j = 0; j < optionCount + 1; j++) {
int index = i + j;
if (index == arguments.length) throw new IllegalArgumentException(argument);
recognizedOptions.add(arguments[index]);
}
i += optionCount;
}
}
return new JavacOptions(recognizedOptions, classNames, files, unrecognizedOptions);
}
public List<String> getRecognizedOptions() {
return Collections.unmodifiableList(recognizedOptions);
}
public List<File> getFiles() {
return Collections.unmodifiableList(files);
}
public List<String> getClassNames() {
return Collections.unmodifiableList(classNames);
}
public List<String> getUnrecognizedOptions() {
return Collections.unmodifiableList(unrecognizedOptions);
}
@Override
public String toString() {
return String.format("recognizedOptions = %s; classNames = %s; " + "files = %s; unrecognizedOptions = %s", recognizedOptions, classNames, files, unrecognizedOptions);
}
}
}