src/share/jaxws_classes/com/sun/tools/internal/ws/wscompile/WsgenTool.java

changeset 286
f50545b5e2f1
child 368
0989ad8c0860
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/jaxws_classes/com/sun/tools/internal/ws/wscompile/WsgenTool.java	Tue Mar 06 16:09:35 2012 -0800
     1.3 @@ -0,0 +1,399 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package com.sun.tools.internal.ws.wscompile;
    1.30 +
    1.31 +import com.sun.istack.internal.tools.ParallelWorldClassLoader;
    1.32 +import com.sun.tools.internal.ws.ToolVersion;
    1.33 +import com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAp;
    1.34 +import com.sun.tools.internal.ws.processor.modeler.wsdl.ConsoleErrorReporter;
    1.35 +import com.sun.tools.internal.ws.resources.WscompileMessages;
    1.36 +import com.sun.tools.internal.xjc.util.NullStream;
    1.37 +import com.sun.xml.internal.txw2.TXW;
    1.38 +import com.sun.xml.internal.txw2.TypedXmlWriter;
    1.39 +import com.sun.xml.internal.txw2.annotation.XmlAttribute;
    1.40 +import com.sun.xml.internal.txw2.annotation.XmlElement;
    1.41 +import com.sun.xml.internal.txw2.output.StreamSerializer;
    1.42 +import com.sun.xml.internal.ws.api.BindingID;
    1.43 +import com.sun.xml.internal.ws.api.databinding.DatabindingConfig;
    1.44 +import com.sun.xml.internal.ws.api.databinding.DatabindingFactory;
    1.45 +import com.sun.xml.internal.ws.api.databinding.WSDLGenInfo;
    1.46 +import com.sun.xml.internal.ws.api.server.Container;
    1.47 +import com.sun.xml.internal.ws.api.wsdl.writer.WSDLGeneratorExtension;
    1.48 +import com.sun.xml.internal.ws.binding.WebServiceFeatureList;
    1.49 +import com.sun.xml.internal.ws.model.AbstractSEIModelImpl;
    1.50 +import com.sun.xml.internal.ws.util.ServiceFinder;
    1.51 +import com.sun.xml.internal.ws.wsdl.writer.WSDLResolver;
    1.52 +import org.xml.sax.SAXParseException;
    1.53 +
    1.54 +import javax.tools.DiagnosticCollector;
    1.55 +import javax.tools.JavaCompiler;
    1.56 +import javax.tools.JavaFileObject;
    1.57 +import javax.tools.StandardJavaFileManager;
    1.58 +import javax.tools.ToolProvider;
    1.59 +import javax.xml.bind.annotation.XmlSeeAlso;
    1.60 +import javax.xml.namespace.QName;
    1.61 +import javax.xml.transform.Result;
    1.62 +import javax.xml.transform.stream.StreamResult;
    1.63 +import javax.xml.ws.EndpointReference;
    1.64 +import javax.xml.ws.Holder;
    1.65 +import java.io.BufferedOutputStream;
    1.66 +import java.io.File;
    1.67 +import java.io.FileNotFoundException;
    1.68 +import java.io.FileOutputStream;
    1.69 +import java.io.IOException;
    1.70 +import java.io.OutputStream;
    1.71 +import java.io.PrintStream;
    1.72 +import java.net.URLClassLoader;
    1.73 +import java.util.ArrayList;
    1.74 +import java.util.Collection;
    1.75 +import java.util.Collections;
    1.76 +import java.util.HashMap;
    1.77 +import java.util.Map;
    1.78 +
    1.79 +/**
    1.80 + * @author Vivek Pandey
    1.81 + */
    1.82 +
    1.83 +/*
    1.84 + * All annotation types are supported.
    1.85 + */
    1.86 +public class WsgenTool {
    1.87 +    private final PrintStream out;
    1.88 +    private final WsgenOptions options = new WsgenOptions();
    1.89 +
    1.90 +
    1.91 +    public WsgenTool(OutputStream out, Container container) {
    1.92 +        this.out = (out instanceof PrintStream)?(PrintStream)out:new PrintStream(out);
    1.93 +        this.container = container;
    1.94 +    }
    1.95 +
    1.96 +
    1.97 +    public WsgenTool(OutputStream out) {
    1.98 +        this(out, null);
    1.99 +    }
   1.100 +
   1.101 +    public boolean run(String[] args){
   1.102 +        final Listener listener = new Listener();
   1.103 +        for (String arg : args) {
   1.104 +            if (arg.equals("-version")) {
   1.105 +                listener.message(
   1.106 +                        WscompileMessages.WSGEN_VERSION(ToolVersion.VERSION.MAJOR_VERSION));
   1.107 +                return true;
   1.108 +            }
   1.109 +            if (arg.equals("-fullversion")) {
   1.110 +                listener.message(
   1.111 +                        WscompileMessages.WSGEN_FULLVERSION(ToolVersion.VERSION.toString()));
   1.112 +                return true;
   1.113 +            }
   1.114 +        }
   1.115 +        try {
   1.116 +            options.parseArguments(args);
   1.117 +            options.validate();
   1.118 +            if(!buildModel(options.endpoint.getName(), listener)){
   1.119 +                return false;
   1.120 +            }
   1.121 +        }catch (Options.WeAreDone done){
   1.122 +            usage((WsgenOptions)done.getOptions());
   1.123 +        }catch (BadCommandLineException e) {
   1.124 +            if(e.getMessage()!=null) {
   1.125 +                System.out.println(e.getMessage());
   1.126 +                System.out.println();
   1.127 +            }
   1.128 +            usage((WsgenOptions)e.getOptions());
   1.129 +            return false;
   1.130 +        }catch(AbortException e){
   1.131 +            //error might have been reported
   1.132 +        }finally{
   1.133 +            if(!options.keep){
   1.134 +                options.removeGeneratedFiles();
   1.135 +            }
   1.136 +        }
   1.137 +        return true;
   1.138 +    }
   1.139 +
   1.140 +    private final Container container;
   1.141 +
   1.142 +    private int round = 0;
   1.143 +
   1.144 +    /*
   1.145 +     * To take care of JDK6-JDK6u3, where 2.1 API classes are not there
   1.146 +     */
   1.147 +    private static boolean useBootClasspath(Class clazz) {
   1.148 +        try {
   1.149 +            ParallelWorldClassLoader.toJarUrl(clazz.getResource('/'+clazz.getName().replace('.','/')+".class"));
   1.150 +            return true;
   1.151 +        } catch(Exception e) {
   1.152 +            return false;
   1.153 +        }
   1.154 +    }
   1.155 +
   1.156 +
   1.157 +    public boolean buildModel(String endpoint, Listener listener) throws BadCommandLineException {
   1.158 +        final ErrorReceiverFilter errReceiver = new ErrorReceiverFilter(listener);
   1.159 +
   1.160 +        boolean bootCP = useBootClasspath(EndpointReference.class) || useBootClasspath(XmlSeeAlso.class);
   1.161 +        Collection<String> args = new ArrayList<String>(6 + (bootCP ? 1 : 0) + (options.nocompile ? 1 : 0)
   1.162 +                + (options.encoding != null ? 2 : 0));
   1.163 +        args.add("-d");
   1.164 +        args.add(options.destDir.getAbsolutePath());
   1.165 +        args.add("-classpath");
   1.166 +        args.add(options.classpath);
   1.167 +        args.add("-s");
   1.168 +        args.add(options.sourceDir.getAbsolutePath());
   1.169 +        if (options.nocompile) {
   1.170 +            args.add("-proc:only");
   1.171 +        }
   1.172 +        if (options.encoding != null) {
   1.173 +            args.add("-encoding");
   1.174 +            args.add(options.encoding);
   1.175 +        }
   1.176 +        if (bootCP) {
   1.177 +            args.add(new StringBuilder()
   1.178 +                    .append("-Xbootclasspath/p:")
   1.179 +                    .append(JavaCompilerHelper.getJarFile(EndpointReference.class))
   1.180 +                    .append(File.pathSeparator)
   1.181 +                    .append(JavaCompilerHelper.getJarFile(XmlSeeAlso.class)).toString());
   1.182 +        }
   1.183 +
   1.184 +        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   1.185 +        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
   1.186 +        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
   1.187 +        JavaCompiler.CompilationTask task = compiler.getTask(
   1.188 +                null,
   1.189 +                fileManager,
   1.190 +                diagnostics,
   1.191 +                args,
   1.192 +                Collections.singleton(endpoint.replaceAll("\\$", ".")),
   1.193 +                null);
   1.194 +        task.setProcessors(Collections.singleton(new WebServiceAp(options, out)));
   1.195 +        boolean result = task.call();
   1.196 +
   1.197 +        if (!result) {
   1.198 +            out.println(WscompileMessages.WSCOMPILE_ERROR(WscompileMessages.WSCOMPILE_COMPILATION_FAILED()));
   1.199 +            return false;
   1.200 +        }
   1.201 +        if (options.genWsdl) {
   1.202 +                DatabindingConfig config = new DatabindingConfig();
   1.203 +            String tmpPath = options.destDir.getAbsolutePath()+ File.pathSeparator+options.classpath;
   1.204 +            ClassLoader classLoader = new URLClassLoader(Options.pathToURLs(tmpPath),
   1.205 +                    this.getClass().getClassLoader());
   1.206 +            Class<?> endpointClass;
   1.207 +            try {
   1.208 +                endpointClass = classLoader.loadClass(endpoint);
   1.209 +            } catch (ClassNotFoundException e) {
   1.210 +                throw new BadCommandLineException(WscompileMessages.WSGEN_CLASS_NOT_FOUND(endpoint));
   1.211 +            }
   1.212 +
   1.213 +            BindingID bindingID = options.getBindingID(options.protocol);
   1.214 +            if (!options.protocolSet) {
   1.215 +                bindingID = BindingID.parse(endpointClass);
   1.216 +            }
   1.217 +            WebServiceFeatureList wsfeatures = new WebServiceFeatureList(endpointClass);
   1.218 +//            RuntimeModeler rtModeler = new RuntimeModeler(endpointClass, options.serviceName, bindingID, wsfeatures.toArray());
   1.219 +//            rtModeler.setClassLoader(classLoader);
   1.220 +            if (options.portName != null)
   1.221 +                config.getMappingInfo().setPortName(options.portName);//rtModeler.setPortName(options.portName);
   1.222 +//            AbstractSEIModelImpl rtModel = rtModeler.buildRuntimeModel();
   1.223 +
   1.224 +                DatabindingFactory fac = DatabindingFactory.newInstance();
   1.225 +                config.setEndpointClass(endpointClass);
   1.226 +                config.getMappingInfo().setServiceName(options.serviceName);
   1.227 +                config.setFeatures(wsfeatures.toArray());
   1.228 +                config.setClassLoader(classLoader);
   1.229 +                config.getMappingInfo().setBindingID(bindingID);
   1.230 +                com.sun.xml.internal.ws.db.DatabindingImpl rt = (com.sun.xml.internal.ws.db.DatabindingImpl)fac.createRuntime(config);
   1.231 +
   1.232 +            final File[] wsdlFileName = new File[1]; // used to capture the generated WSDL file.
   1.233 +            final Map<String,File> schemaFiles = new HashMap<String,File>();
   1.234 +
   1.235 +            WSDLGenInfo wsdlGenInfo = new WSDLGenInfo();
   1.236 +            wsdlGenInfo.setWsdlResolver(
   1.237 +                    new WSDLResolver() {
   1.238 +                        private File toFile(String suggestedFilename) {
   1.239 +                            return new File(options.nonclassDestDir, suggestedFilename);
   1.240 +                        }
   1.241 +                        private Result toResult(File file) {
   1.242 +                            Result result;
   1.243 +                            try {
   1.244 +                                result = new StreamResult(new FileOutputStream(file));
   1.245 +                                result.setSystemId(file.getPath().replace('\\', '/'));
   1.246 +                            } catch (FileNotFoundException e) {
   1.247 +                                errReceiver.error(e);
   1.248 +                                return null;
   1.249 +                            }
   1.250 +                            return result;
   1.251 +                        }
   1.252 +
   1.253 +                        public Result getWSDL(String suggestedFilename) {
   1.254 +                            File f = toFile(suggestedFilename);
   1.255 +                            wsdlFileName[0] = f;
   1.256 +                            return toResult(f);
   1.257 +                        }
   1.258 +                        public Result getSchemaOutput(String namespace, String suggestedFilename) {
   1.259 +                            if (namespace == null)
   1.260 +                                return null;
   1.261 +                            File f = toFile(suggestedFilename);
   1.262 +                            schemaFiles.put(namespace,f);
   1.263 +                            return toResult(f);
   1.264 +                        }
   1.265 +                        public Result getAbstractWSDL(Holder<String> filename) {
   1.266 +                            return toResult(toFile(filename.value));
   1.267 +                        }
   1.268 +                        public Result getSchemaOutput(String namespace, Holder<String> filename) {
   1.269 +                            return getSchemaOutput(namespace, filename.value);
   1.270 +                        }
   1.271 +                        // TODO pass correct impl's class name
   1.272 +                    });
   1.273 +
   1.274 +            wsdlGenInfo.setContainer(container);
   1.275 +            wsdlGenInfo.setExtensions(ServiceFinder.find(WSDLGeneratorExtension.class).toArray());
   1.276 +            wsdlGenInfo.setInlineSchemas(options.inlineSchemas);
   1.277 +            rt.generateWSDL(wsdlGenInfo);
   1.278 +
   1.279 +
   1.280 +            if(options.wsgenReport!=null)
   1.281 +                generateWsgenReport(endpointClass,(AbstractSEIModelImpl)rt.getModel(),wsdlFileName[0],schemaFiles);
   1.282 +        }
   1.283 +        return true;
   1.284 +    }
   1.285 +
   1.286 +    /**
   1.287 +     * Generates a small XML file that captures the key activity of wsgen,
   1.288 +     * so that test harness can pick up artifacts.
   1.289 +     */
   1.290 +    private void generateWsgenReport(Class<?> endpointClass, AbstractSEIModelImpl rtModel, File wsdlFile, Map<String,File> schemaFiles) {
   1.291 +        try {
   1.292 +            ReportOutput.Report report = TXW.create(ReportOutput.Report.class,
   1.293 +                new StreamSerializer(new BufferedOutputStream(new FileOutputStream(options.wsgenReport))));
   1.294 +
   1.295 +            report.wsdl(wsdlFile.getAbsolutePath());
   1.296 +            ReportOutput.writeQName(rtModel.getServiceQName(), report.service());
   1.297 +            ReportOutput.writeQName(rtModel.getPortName(), report.port());
   1.298 +            ReportOutput.writeQName(rtModel.getPortTypeName(), report.portType());
   1.299 +
   1.300 +            report.implClass(endpointClass.getName());
   1.301 +
   1.302 +            for (Map.Entry<String,File> e : schemaFiles.entrySet()) {
   1.303 +                ReportOutput.Schema s = report.schema();
   1.304 +                s.ns(e.getKey());
   1.305 +                s.location(e.getValue().getAbsolutePath());
   1.306 +            }
   1.307 +
   1.308 +            report.commit();
   1.309 +        } catch (IOException e) {
   1.310 +            // this is code for the test, so we can be lousy in the error handling
   1.311 +            throw new Error(e);
   1.312 +        }
   1.313 +    }
   1.314 +
   1.315 +    /**
   1.316 +     * "Namespace" for code needed to generate the report file.
   1.317 +     */
   1.318 +    static class ReportOutput {
   1.319 +        @XmlElement("report")
   1.320 +        interface Report extends TypedXmlWriter {
   1.321 +            @XmlElement
   1.322 +            void wsdl(String file); // location of WSDL
   1.323 +            @XmlElement
   1.324 +            QualifiedName portType();
   1.325 +            @XmlElement
   1.326 +            QualifiedName service();
   1.327 +            @XmlElement
   1.328 +            QualifiedName port();
   1.329 +
   1.330 +            /**
   1.331 +             * Name of the class that has {@link javax.jws.WebService}.
   1.332 +             */
   1.333 +            @XmlElement
   1.334 +            void implClass(String name);
   1.335 +
   1.336 +            @XmlElement
   1.337 +            Schema schema();
   1.338 +        }
   1.339 +
   1.340 +        interface QualifiedName extends TypedXmlWriter {
   1.341 +            @XmlAttribute
   1.342 +            void uri(String ns);
   1.343 +            @XmlAttribute
   1.344 +            void localName(String localName);
   1.345 +        }
   1.346 +
   1.347 +        interface Schema extends TypedXmlWriter {
   1.348 +            @XmlAttribute
   1.349 +            void ns(String ns);
   1.350 +            @XmlAttribute
   1.351 +            void location(String filePath);
   1.352 +        }
   1.353 +
   1.354 +        private static void writeQName( QName n, QualifiedName w ) {
   1.355 +            w.uri(n.getNamespaceURI());
   1.356 +            w.localName(n.getLocalPart());
   1.357 +        }
   1.358 +    }
   1.359 +
   1.360 +    protected void usage(WsgenOptions options) {
   1.361 +        // Just don't see any point in passing WsgenOptions
   1.362 +        // BadCommandLineException also shouldn't have options
   1.363 +        if (options == null)
   1.364 +            options = this.options;
   1.365 +        System.out.println(WscompileMessages.WSGEN_HELP("WSGEN", options.protocols, options.nonstdProtocols.keySet()));
   1.366 +        System.out.println(WscompileMessages.WSGEN_USAGE_EXAMPLES());
   1.367 +    }
   1.368 +
   1.369 +    class Listener extends WsimportListener {
   1.370 +        ConsoleErrorReporter cer = new ConsoleErrorReporter(out == null ? new PrintStream(new NullStream()) : out);
   1.371 +
   1.372 +        @Override
   1.373 +        public void generatedFile(String fileName) {
   1.374 +            message(fileName);
   1.375 +        }
   1.376 +
   1.377 +        @Override
   1.378 +        public void message(String msg) {
   1.379 +            out.println(msg);
   1.380 +        }
   1.381 +
   1.382 +        @Override
   1.383 +        public void error(SAXParseException exception) {
   1.384 +            cer.error(exception);
   1.385 +        }
   1.386 +
   1.387 +        @Override
   1.388 +        public void fatalError(SAXParseException exception) {
   1.389 +            cer.fatalError(exception);
   1.390 +        }
   1.391 +
   1.392 +        @Override
   1.393 +        public void warning(SAXParseException exception) {
   1.394 +            cer.warning(exception);
   1.395 +        }
   1.396 +
   1.397 +        @Override
   1.398 +        public void info(SAXParseException exception) {
   1.399 +            cer.info(exception);
   1.400 +        }
   1.401 +    }
   1.402 +}

mercurial