src/share/jaxws_classes/com/sun/tools/internal/jxc/SchemaGenerator.java

Print this page


   1 /*
   2  * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.internal.jxc;
  27 
  28 import com.sun.tools.internal.jxc.ap.Options;
  29 import com.sun.tools.internal.xjc.BadCommandLineException;
  30 import com.sun.tools.internal.xjc.api.util.ApClassLoader;
  31 import com.sun.tools.internal.xjc.api.util.ToolsJarNotFoundException;
  32 import com.sun.xml.internal.bind.util.Which;
  33 
  34 import javax.lang.model.SourceVersion;
  35 import javax.tools.DiagnosticCollector;
  36 import javax.tools.JavaCompiler;
  37 import javax.tools.JavaFileObject;
  38 import javax.tools.OptionChecker;
  39 import javax.tools.StandardJavaFileManager;
  40 import javax.tools.ToolProvider;
  41 import javax.xml.bind.JAXBContext;
  42 import java.io.File;
  43 import java.lang.reflect.InvocationTargetException;
  44 import java.lang.reflect.Method;
  45 import java.net.MalformedURLException;
  46 import java.net.URISyntaxException;
  47 import java.net.URL;

  48 import java.util.ArrayList;

  49 import java.util.Collections;
  50 import java.util.List;
  51 import java.util.logging.Level;
  52 import java.util.logging.Logger;
  53 
  54 /**
  55  * CLI entry-point to the schema generator.
  56  *
  57  * @author Bhakti Mehta
  58  */
  59 public class SchemaGenerator {
  60     /**
  61      * Runs the schema generator.
  62      */
  63     public static void main(String[] args) throws Exception {
  64         System.exit(run(args));
  65     }
  66 
  67     public static int run(String[] args) throws Exception {
  68         try {
  69             ClassLoader cl = SecureLoader.getClassClassLoader(SchemaGenerator.class);
  70             if (cl==null) {
  71                 cl = SecureLoader.getSystemClassLoader();
  72             }
  73 //            ClassLoader classLoader = new ApClassLoader(cl, packagePrefixes); // todo: check if can be removed
  74             return run(args, cl);
  75         } catch(Exception e) {
  76             System.err.println(e.getMessage());
  77             return -1;
  78         }
  79     }
  80 
  81     /**
  82      * List of package prefixes we want to load in the same package
  83      */
  84     private static final String[] packagePrefixes = {
  85         "com.sun.tools.internal.jxc.",
  86         "com.sun.tools.internal.xjc.",
  87         "com.sun.istack.internal.tools.",
  88         "com.sun.tools.javac.",
  89         "com.sun.tools.javadoc.",
  90         "javax.annotation.processing.",
  91         "javax.lang.model."
  92     };
  93 
  94     /**
  95      * Runs the schema generator.
  96      *
  97      * @param classLoader
  98      *      the schema generator will run in this classLoader.
  99      *      It needs to be able to load annotation processing and JAXB RI classes. Note that
 100      *      JAXB RI classes refer to annotation processing classes. Must not be null.
 101      *
 102      * @return
 103      *      exit code. 0 if success.
 104      *
 105      */
 106     public static int run(String[] args, ClassLoader classLoader) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
 107         final Options options = new Options();
 108         if (args.length ==0) {
 109             usage();
 110             return -1;
 111         }
 112         for (String arg : args) {
 113             if (arg.equals("-help")) {
 114                 usage();


 131             options.parseArguments(args);
 132         } catch (BadCommandLineException e) {
 133             // there was an error in the command line.
 134             // print usage and abort.
 135             System.out.println(e.getMessage());
 136             System.out.println();
 137             usage();
 138             return -1;
 139         }
 140 
 141         Class schemagenRunner = classLoader.loadClass(Runner.class.getName());
 142         Method compileMethod = schemagenRunner.getDeclaredMethod("compile",String[].class,File.class);
 143 
 144         List<String> aptargs = new ArrayList<String>();
 145 
 146         if (options.encoding != null) {
 147             aptargs.add("-encoding");
 148             aptargs.add(options.encoding);
 149         }
 150 
 151         // make jaxb-api.jar visible to classpath
 152         File jaxbApi = findJaxbApiJar();
 153         if(jaxbApi!=null) {
 154             if(options.classpath!=null) {
 155                 options.classpath = options.classpath+File.pathSeparatorChar+jaxbApi;
 156             } else {
 157                 options.classpath = jaxbApi.getPath();
 158             }
 159         }
 160 
 161         aptargs.add("-cp");
 162         aptargs.add(options.classpath);
 163 
 164         if(options.targetDir!=null) {
 165             aptargs.add("-d");
 166             aptargs.add(options.targetDir.getPath());
 167         }
 168 
 169         aptargs.addAll(options.arguments);
 170 
 171         String[] argsarray = aptargs.toArray(new String[aptargs.size()]);
 172         return ((Boolean) compileMethod.invoke(null, argsarray, options.episodeFile)) ? 0 : 1;
 173     }
 174 

























 175     /**
 176      * Computes the file system path of <tt>jaxb-api.jar</tt> so that
 177      * Annotation Processing will see them in the <tt>-cp</tt> option.
 178      *
 179      * <p>
 180      * In Java, you can't do this reliably (for that matter there's no guarantee
 181      * that such a jar file exists, such as in Glassfish), so we do the best we can.
 182      *
 183      * @return
 184      *      null if failed to locate it.
 185      */
 186     private static File findJaxbApiJar() {
 187         String url = Which.which(JAXBContext.class);
 188         if(url==null)       return null;    // impossible, but hey, let's be defensive
 189 
 190         if(!url.startsWith("jar:") || url.lastIndexOf('!')==-1)
 191             // no jar file
 192             return null;
 193 
 194         String jarFileUrl = url.substring(4,url.lastIndexOf('!'));
 195         if(!jarFileUrl.startsWith("file:"))
 196             return null;    // not from file system
 197 
 198         try {
 199             File f = new File(new URL(jarFileUrl).toURI());
 200             if (f.exists() && f.getName().endsWith(".jar")) { // see 6510966
 201                 return f;
 202             }
 203             f = new File(new URL(jarFileUrl).getFile());
 204             if (f.exists() && f.getName().endsWith(".jar")) { // this is here for potential backw. compatibility issues
 205                 return f;
 206             }
 207         } catch (URISyntaxException ex) {
 208             Logger.getLogger(SchemaGenerator.class.getName()).log(Level.SEVERE, null, ex);
 209         } catch (MalformedURLException ex) {
 210             Logger.getLogger(SchemaGenerator.class.getName()).log(Level.SEVERE, null, ex);
 211         }
 212         return null;
 213     }
 214 
 215     /**
 216      * Returns true if the list of arguments have an argument
 217      * that looks like a class name.
 218      */
 219     private static boolean hasClass(List<String> args) {
 220         for (String arg : args) {
 221             if(!arg.endsWith(".java"))
 222                 return true;
 223         }
 224         return false;
 225     }
 226 
 227     private static void usage( ) {
 228         System.out.println(Messages.USAGE.format());
 229     }
 230 
 231     public static final class Runner {
 232         public static boolean compile(String[] args, File episode) throws Exception {
 233 
 234             JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
 235             DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
 236             StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
 237             JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
 238             List<String> unrecognizedOptions = options.getUnrecognizedOptions();
 239             if (!unrecognizedOptions.isEmpty())
 240                 Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
 241             Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
 242             JavaCompiler.CompilationTask task = compiler.getTask(
 243                     null,
 244                     fileManager,


   1 /*
   2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.internal.jxc;
  27 
  28 import com.sun.tools.internal.jxc.ap.Options;
  29 import com.sun.tools.internal.xjc.BadCommandLineException;


  30 import com.sun.xml.internal.bind.util.Which;
  31 
  32 import javax.lang.model.SourceVersion;
  33 import javax.tools.DiagnosticCollector;
  34 import javax.tools.JavaCompiler;
  35 import javax.tools.JavaFileObject;
  36 import javax.tools.OptionChecker;
  37 import javax.tools.StandardJavaFileManager;
  38 import javax.tools.ToolProvider;
  39 import javax.xml.bind.JAXBContext;
  40 import java.io.File;
  41 import java.lang.reflect.InvocationTargetException;
  42 import java.lang.reflect.Method;
  43 import java.net.MalformedURLException;
  44 import java.net.URISyntaxException;
  45 import java.net.URL;
  46 import java.net.URLClassLoader;
  47 import java.util.ArrayList;
  48 import java.util.Collection;
  49 import java.util.Collections;
  50 import java.util.List;
  51 import java.util.logging.Level;
  52 import java.util.logging.Logger;
  53 
  54 /**
  55  * CLI entry-point to the schema generator.
  56  *
  57  * @author Bhakti Mehta
  58  */
  59 public class SchemaGenerator {
  60     /**
  61      * Runs the schema generator.
  62      */
  63     public static void main(String[] args) throws Exception {
  64         System.exit(run(args));
  65     }
  66 
  67     public static int run(String[] args) throws Exception {
  68         try {
  69             ClassLoader cl = SecureLoader.getClassClassLoader(SchemaGenerator.class);
  70             if (cl==null) {
  71                 cl = SecureLoader.getSystemClassLoader();
  72             }

  73             return run(args, cl);
  74         } catch(Exception e) {
  75             System.err.println(e.getMessage());
  76             return -1;
  77         }
  78     }
  79 
  80     /**













  81      * Runs the schema generator.
  82      *
  83      * @param classLoader
  84      *      the schema generator will run in this classLoader.
  85      *      It needs to be able to load annotation processing and JAXB RI classes. Note that
  86      *      JAXB RI classes refer to annotation processing classes. Must not be null.
  87      *
  88      * @return
  89      *      exit code. 0 if success.
  90      *
  91      */
  92     public static int run(String[] args, ClassLoader classLoader) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  93         final Options options = new Options();
  94         if (args.length ==0) {
  95             usage();
  96             return -1;
  97         }
  98         for (String arg : args) {
  99             if (arg.equals("-help")) {
 100                 usage();


 117             options.parseArguments(args);
 118         } catch (BadCommandLineException e) {
 119             // there was an error in the command line.
 120             // print usage and abort.
 121             System.out.println(e.getMessage());
 122             System.out.println();
 123             usage();
 124             return -1;
 125         }
 126 
 127         Class schemagenRunner = classLoader.loadClass(Runner.class.getName());
 128         Method compileMethod = schemagenRunner.getDeclaredMethod("compile",String[].class,File.class);
 129 
 130         List<String> aptargs = new ArrayList<String>();
 131 
 132         if (options.encoding != null) {
 133             aptargs.add("-encoding");
 134             aptargs.add(options.encoding);
 135         }
 136 










 137         aptargs.add("-cp");
 138         aptargs.add(setClasspath(options.classpath)); // set original classpath + jaxb-api to be visible to annotation processor
 139 
 140         if(options.targetDir!=null) {
 141             aptargs.add("-d");
 142             aptargs.add(options.targetDir.getPath());
 143         }
 144 
 145         aptargs.addAll(options.arguments);
 146 
 147         String[] argsarray = aptargs.toArray(new String[aptargs.size()]);
 148         return ((Boolean) compileMethod.invoke(null, argsarray, options.episodeFile)) ? 0 : 1;
 149     }
 150 
 151     private static String setClasspath(String givenClasspath) {
 152         StringBuilder cp = new StringBuilder();
 153         appendPath(cp, givenClasspath);
 154         ClassLoader cl = Thread.currentThread().getContextClassLoader();
 155         while (cl != null) {
 156             if (cl instanceof URLClassLoader) {
 157                 for (URL url : ((URLClassLoader) cl).getURLs()) {
 158                     appendPath(cp, url.getPath());
 159                 }
 160             }
 161             cl = cl.getParent();
 162         }
 163 
 164         appendPath(cp, findJaxbApiJar());
 165         return cp.toString();
 166     }
 167 
 168     private static void appendPath(StringBuilder cp, String url) {
 169         if (url == null || url.trim().isEmpty())
 170             return;
 171         if (cp.length() != 0)
 172             cp.append(File.pathSeparatorChar);
 173         cp.append(url);
 174     }
 175 
 176     /**
 177      * Computes the file system path of <tt>jaxb-api.jar</tt> so that
 178      * Annotation Processing will see them in the <tt>-cp</tt> option.
 179      *
 180      * <p>
 181      * In Java, you can't do this reliably (for that matter there's no guarantee
 182      * that such a jar file exists, such as in Glassfish), so we do the best we can.
 183      *
 184      * @return
 185      *      null if failed to locate it.
 186      */
 187     private static String findJaxbApiJar() {
 188         String url = Which.which(JAXBContext.class);
 189         if(url==null)       return null;    // impossible, but hey, let's be defensive
 190 
 191         if(!url.startsWith("jar:") || url.lastIndexOf('!')==-1)
 192             // no jar file
 193             return null;
 194 
 195         String jarFileUrl = url.substring(4,url.lastIndexOf('!'));
 196         if(!jarFileUrl.startsWith("file:"))
 197             return null;    // not from file system
 198 
 199         try {
 200             File f = new File(new URL(jarFileUrl).toURI());
 201             if (f.exists() && f.getName().endsWith(".jar")) { // see 6510966
 202                 return f.getPath();
 203             }
 204             f = new File(new URL(jarFileUrl).getFile());
 205             if (f.exists() && f.getName().endsWith(".jar")) { // this is here for potential backw. compatibility issues
 206                 return f.getPath();
 207             }
 208         } catch (URISyntaxException ex) {
 209             Logger.getLogger(SchemaGenerator.class.getName()).log(Level.SEVERE, null, ex);
 210         } catch (MalformedURLException ex) {
 211             Logger.getLogger(SchemaGenerator.class.getName()).log(Level.SEVERE, null, ex);
 212         }
 213         return null;












 214     }
 215 
 216     private static void usage( ) {
 217         System.out.println(Messages.USAGE.format());
 218     }
 219 
 220     public static final class Runner {
 221         public static boolean compile(String[] args, File episode) throws Exception {
 222 
 223             JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
 224             DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
 225             StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
 226             JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
 227             List<String> unrecognizedOptions = options.getUnrecognizedOptions();
 228             if (!unrecognizedOptions.isEmpty())
 229                 Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
 230             Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
 231             JavaCompiler.CompilationTask task = compiler.getTask(
 232                     null,
 233                     fileManager,