feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
/**
* @author Vivek Pandey
*/
/**
* Signals the abortion of the compilation.
* <p>
* This exception should be only thrown from {@link ErrorReceiver}
* for the consistent error handling.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class AbortException extends RuntimeException {
public AbortException() {
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.istack.internal.NotNull;
import java.net.URL;
import java.util.regex.Pattern;
/**
* Represents authorization information needed by {@link com.sun.tools.internal.ws.wscompile.DefaultAuthenticator} to
* authenticate wsimport to access the wsdl.
*
* @author Vivek Pandey
*/
public final class AuthInfo {
private final String user;
private final String password;
private final Pattern urlPattern;
public AuthInfo(@NotNull URL url, @NotNull String user, @NotNull String password) {
String u = url.toExternalForm().replaceFirst("\\?", "\\\\?");
this.urlPattern = Pattern.compile(u.replace("*", ".*"), Pattern.CASE_INSENSITIVE);
this.user = user;
this.password = password;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
/**
* Returns if the requesting host and port are associated with this {@link AuthInfo}
*/
public boolean matchingHost(@NotNull URL requestingURL) {
return urlPattern.matcher(requestingURL.toExternalForm()).matches();
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.istack.internal.Nullable;
/**
* @author Vivek Pandey
*/
public class BadCommandLineException extends Exception {
private transient Options options;
public BadCommandLineException(String msg) {
super(msg);
}
public BadCommandLineException(String message, Throwable cause) {
super(message, cause);
}
public BadCommandLineException() {
this(null);
}
public void initOptions(Options opt) {
assert this.options==null;
this.options = opt;
}
/**
* Gets the partly parsed option object, if any.
*/
public @Nullable
Options getOptions() {
return options;
}
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.istack.internal.Nullable;
import com.sun.istack.internal.SAXParseException2;
import com.sun.tools.internal.ws.resources.ModelMessages;
import com.sun.tools.internal.xjc.api.ErrorListener;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
/**
* Implemented by the driver of the compiler engine to handle
* errors found during the compiliation.
*
* <p>
* This class implements {@link org.xml.sax.ErrorHandler} so it can be
* passed to anywhere where {@link org.xml.sax.ErrorHandler} is expected.
*
* <p>
* However, to make the error handling easy (and make it work
* with visitor patterns nicely),
* none of the methods on this class throws {@link org.xml.sax.SAXException}.
* Instead, when the compilation needs to be aborted,
* it throws {@link AbortException}, which is unchecked.
*
* <p>
* This also implements the externally visible {@link com.sun.tools.internal.xjc.api.ErrorListener}
* so that we can reuse our internal implementation for testing and such.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* @author Vivek Pandey
*/
public abstract class ErrorReceiver implements ErrorHandler, ErrorListener {
//
//
// convenience methods for callers
//
//
/**
* @param loc
* can be null if the location is unknown
*/
public final void error( Locator loc, String msg ) {
error( new SAXParseException2(msg,loc) );
}
public final void error( Locator loc, String msg, Exception e ) {
error( new SAXParseException2(msg,loc,e) );
}
public final void error( String msg, Exception e ) {
error( new SAXParseException2(msg,null,e) );
}
public void error(Exception e) {
error(e.getMessage(),e);
}
/**
* Reports a warning.
*/
public final void warning( @Nullable Locator loc, String msg ) {
warning( new SAXParseException(msg,loc) );
}
//
//
// ErrorHandler implementation, but can't throw SAXException
//
//
public abstract void error(SAXParseException exception) throws AbortException;
public abstract void fatalError(SAXParseException exception) throws AbortException;
public abstract void warning(SAXParseException exception) throws AbortException;
/**
* This method will be invoked periodically to allow {@link com.sun.tools.internal.xjc.AbortException}
* to be thrown, especially when this is driven by some kind of GUI.
*/
public void pollAbort() throws AbortException {
}
/**
* Reports verbose messages to users.
*
* This method can be used to report additional non-essential
* messages. The implementation usually discards them
* unless some specific debug option is turned on.
*/
public abstract void info(SAXParseException exception) /*REVISIT:throws AbortException*/;
/**
* Reports a debug message to users.
*
* @see #info(SAXParseException)
*/
public final void debug( String msg ) {
info( new SAXParseException(msg,null) );
}
public abstract void debug(SAXParseException exception);
//
//
// convenience methods for derived classes
//
//
/**
* Returns the human readable string representation of the
* {@link org.xml.sax.Locator} part of the specified
* {@link SAXParseException}.
*
* @return non-null valid object.
*/
protected final String getLocationString( SAXParseException e ) {
if(e.getLineNumber()!=-1 || e.getSystemId()!=null) {
int line = e.getLineNumber();
return ModelMessages.CONSOLE_ERROR_REPORTER_LINE_X_OF_Y(line==-1?"?":Integer.toString( line ),
getShortName( e.getSystemId()));
} else {
return ""; //for unkown location just return empty string
}
}
/** Computes a short name of a given URL for display. */
private String getShortName( String url ) {
if(url==null)
return ModelMessages.CONSOLE_ERROR_REPORTER_UNKNOWN_LOCATION();
return url;
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.tools.internal.xjc.api.ErrorListener;
import org.xml.sax.SAXParseException;
/**
* Filter implementation of the ErrorReceiver.
*
* If an error is encountered, this filter sets a flag.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* @author Vivek Pandey
*/
public class ErrorReceiverFilter extends ErrorReceiver {
public ErrorReceiverFilter() {}
public ErrorReceiverFilter( ErrorListener h ) {
setErrorReceiver(h);
}
private ErrorListener core;
public void setErrorReceiver( ErrorListener handler ) {
core = handler;
}
private boolean hadError = false;
public final boolean hadError() { return hadError; }
/**
* Resets the error state its currently in. It allows to ignore the error reported by
* any sub-system.
*/
public void reset(){
hadError = false;
}
public void info(SAXParseException exception) {
if(core!=null) core.info(exception);
}
public void debug(SAXParseException exception) {
}
public void warning(SAXParseException exception) {
if(core!=null) core.warning(exception);
}
public void error(SAXParseException exception) {
hadError = true;
if(core!=null) core.error(exception);
}
public void fatalError(SAXParseException exception) {
hadError = true;
if(core!=null) core.fatalError(exception);
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.codemodel.internal.JPackage;
import javax.annotation.processing.Filer;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
/**
* Writes all the source files using the specified Filer.
*
* @author WS Development Team
*/
public class FilerCodeWriter extends WSCodeWriter {
/** The Filer used to create files. */
private final Filer filer;
private Writer w;
public FilerCodeWriter(File outDir, Options options) throws IOException {
super(outDir, options);
this.filer = options.filer;
}
public Writer openSource(JPackage pkg, String fileName) throws IOException {
String tmp = fileName.substring(0, fileName.length()-5);
if (pkg.name() != null && ! "".equals(pkg.name())) {
w = filer.createSourceFile(pkg.name() + "." + tmp).openWriter();
} else {
w = filer.createSourceFile(tmp).openWriter();
}
return w;
}
public void close() throws IOException {
super.close();
if (w != null)
w.close();
w = null;
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.istack.internal.tools.ParallelWorldClassLoader;
import com.sun.tools.internal.ws.resources.JavacompilerMessages;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URISyntaxException;
/**
* A helper class to invoke javac.
*
* @author WS Development Team
*/
class JavaCompilerHelper{
static File getJarFile(Class clazz) {
URL url = null;
try {
url = ParallelWorldClassLoader.toJarUrl(clazz.getResource('/'+clazz.getName().replace('.','/')+".class"));
return new File(url.toURI());
} catch (ClassNotFoundException e) {
// if we can't figure out where JAXB/JAX-WS API are, we couldn't have been executing this code.
throw new Error(e);
} catch (MalformedURLException e) {
// if we can't figure out where JAXB/JAX-WS API are, we couldn't have been executing this code.
throw new Error(e);
} catch (URISyntaxException e) {
// url.toURI() is picky and doesn't like ' ' in URL, so this is the fallback
return new File(url.getPath());
}
}
static boolean compile(String[] args, OutputStream out, ErrorReceiver receiver){
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
/* try to use the new compiler */
Class comSunToolsJavacMainClass =
cl.loadClass("com.sun.tools.javac.Main");
try {
Method compileMethod =
comSunToolsJavacMainClass.getMethod(
"compile",
compileMethodSignature);
Object result =
compileMethod.invoke(
null, args, new PrintWriter(out));
return result instanceof Integer && (Integer) result == 0;
} catch (NoSuchMethodException e2) {
receiver.error(JavacompilerMessages.JAVACOMPILER_NOSUCHMETHOD_ERROR("getMethod(\"compile\", Class[])"), e2);
} catch (IllegalAccessException e) {
receiver.error(e);
} catch (InvocationTargetException e) {
receiver.error(e);
}
} catch (ClassNotFoundException e) {
receiver.error(JavacompilerMessages.JAVACOMPILER_CLASSPATH_ERROR("com.sun.tools.javac.Main"), e);
} catch (SecurityException e) {
receiver.error(e);
}
return false;
}
private static final Class[] compileMethodSignature = {String[].class, PrintWriter.class};
}

View File

@@ -0,0 +1,491 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.ws.Invoker;
import javax.annotation.processing.Filer;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Provide common jaxws tool options.
*
* @author Vivek Pandey
*/
public class Options {
/**
* -verbose
*/
public boolean verbose;
/**
* - quite
*/
public boolean quiet;
/**
* -keep
*/
public boolean keep;
/**
* -d
*/
public File destDir = new File(".");
/**
* -s
*/
public File sourceDir;
/**
* The filer that can use used to write out the generated files
*/
public Filer filer;
/**
* -encoding
*/
public String encoding;
public String classpath = System.getProperty("java.class.path");
/**
* -javacOptions
*
* @since 2.2.9
*/
public List<String> javacOptions;
/**
* -Xnocompile
*/
public boolean nocompile;
/**
* If true XML security features when parsing XML documents will be disabled.
* The default value is false.
*
* Boolean
* @since 2.2.9
*/
public boolean disableXmlSecurity;
public enum Target {
V2_0, V2_1, V2_2;
/**
* Returns true if this version is equal or later than the given one.
*/
public boolean isLaterThan(Target t) {
return this.ordinal() >= t.ordinal();
}
/**
* Parses "2.0" and "2.1" into the {@link Target} object.
*
* @return null for parsing failure.
*/
public static Target parse(String token) {
if (token.equals("2.0"))
return Target.V2_0;
else if (token.equals("2.1"))
return Target.V2_1;
else if (token.equals("2.2"))
return Target.V2_2;
return null;
}
/**
* Gives the String representation of the {@link Target}
*/
public String getVersion(){
switch(this){
case V2_0:
return "2.0";
case V2_1:
return "2.1";
case V2_2:
return "2.2";
default:
return null;
}
}
public static Target getDefault() {
return V2_2;
}
public static Target getLoadedAPIVersion() {
return LOADED_API_VERSION;
}
private static final Target LOADED_API_VERSION;
static {
// check if we are indeed loading JAX-WS 2.2 API
if (Invoker.checkIfLoading22API()) {
LOADED_API_VERSION = Target.V2_2;
} // check if we are indeed loading JAX-WS 2.1 API
else if (Invoker.checkIfLoading21API()) {
LOADED_API_VERSION = Target.V2_1;
} else {
LOADED_API_VERSION = Target.V2_0;
}
}
}
public Target target = Target.V2_2;
/**
* strictly follow the compatibility rules specified in JAXWS spec
*/
public static final int STRICT = 1;
/**
* loosely follow the compatibility rules and allow the use of vendor
* binding extensions
*/
public static final int EXTENSION = 2;
/**
* this switch determines how carefully the compiler will follow
* the compatibility rules in the spec. Either <code>STRICT</code>
* or <code>EXTENSION</code>.
*/
public int compatibilityMode = STRICT;
public boolean isExtensionMode() {
return compatibilityMode == EXTENSION;
}
public boolean debug = false;
/**
* -Xdebug - gives complete stack trace
*/
public boolean debugMode = false;
private final List<File> generatedFiles = new ArrayList<File>();
private ClassLoader classLoader;
/**
* Remember info on generated source file generated so that it
* can be removed later, if appropriate.
*/
public void addGeneratedFile(File file) {
generatedFiles.add(file);
}
/**
* Remove generated files
*/
public void removeGeneratedFiles(){
for(File file : generatedFiles){
if (file.getName().endsWith(".java")) {
boolean deleted = file.delete();
if (verbose && !deleted) {
System.out.println(MessageFormat.format("{0} could not be deleted.", file));
}
}
}
generatedFiles.clear();
}
/**
* Return all the generated files and its types.
*/
public Iterable<File> getGeneratedFiles() {
return generatedFiles;
}
/**
* Delete all the generated source files made during the execution
* of this environment (those that have been registered with the
* "addGeneratedFile" method).
*/
public void deleteGeneratedFiles() {
synchronized (generatedFiles) {
for (File file : generatedFiles) {
if (file.getName().endsWith(".java")) {
boolean deleted = file.delete();
if (verbose && !deleted) {
System.out.println(MessageFormat.format("{0} could not be deleted.", file));
}
}
}
generatedFiles.clear();
}
}
/**
* Parses arguments and fill fields of this object.
*
* @exception BadCommandLineException
* thrown when there's a problem in the command-line arguments
*/
public void parseArguments( String[] args ) throws BadCommandLineException {
for (int i = 0; i < args.length; i++) {
if(args[i].length()==0)
throw new BadCommandLineException();
if (args[i].charAt(0) == '-') {
int j = parseArguments(args,i);
if(j==0)
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_INVALID_OPTION(args[i]));
i += (j-1);
} else {
addFile(args[i]);
}
}
if(destDir == null)
destDir = new File(".");
if(sourceDir == null)
sourceDir = destDir;
}
/**
* Adds a file from the argume
*
* @param arg a file, could be a wsdl or xsd or a Class
*/
protected void addFile(String arg) throws BadCommandLineException {}
/**
* Parses an option <code>args[i]</code> and return
* the number of tokens consumed.
*
* @return
* 0 if the argument is not understood. Returning 0
* will let the caller report an error.
* @exception BadCommandLineException
* If the callee wants to provide a custom message for an error.
*/
protected int parseArguments(String[] args, int i) throws BadCommandLineException {
if (args[i].equals("-g")) {
debug = true;
return 1;
} else if (args[i].equals("-Xdebug")) {
debugMode = true;
return 1;
} else if (args[i].equals("-Xendorsed")) {
// this option is processed much earlier, so just ignore.
return 1;
} else if (args[i].equals("-verbose")) {
verbose = true;
return 1;
} else if (args[i].equals("-quiet")) {
quiet = true;
return 1;
} else if (args[i].equals("-keep")) {
keep = true;
return 1;
} else if (args[i].equals("-target")) {
String token = requireArgument("-target", args, ++i);
target = Target.parse(token);
if(target == null)
throw new BadCommandLineException(WscompileMessages.WSIMPORT_ILLEGAL_TARGET_VERSION(token));
return 2;
} else if (args[i].equals("-classpath") || args[i].equals("-cp")) {
classpath = requireArgument("-classpath", args, ++i) + File.pathSeparator + System.getProperty("java.class.path");
return 2;
} else if (args[i].equals("-d")) {
destDir = new File(requireArgument("-d", args, ++i));
if (!destDir.exists())
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(destDir.getPath()));
return 2;
} else if (args[i].equals("-s")) {
sourceDir = new File(requireArgument("-s", args, ++i));
keep = true;
if (!sourceDir.exists()) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(sourceDir.getPath()));
}
return 2;
} else if (args[i].equals("-extension")) {
compatibilityMode = EXTENSION;
return 1;
} else if (args[i].startsWith("-help")) {
WeAreDone done = new WeAreDone();
done.initOptions(this);
throw done;
} else if (args[i].equals("-Xnocompile")) {
// -nocompile implies -keep. this is undocumented switch.
nocompile = true;
keep = true;
return 1;
} else if (args[i].equals("-encoding")) {
encoding = requireArgument("-encoding", args, ++i);
try {
if (!Charset.isSupported(encoding)) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
}
} catch (IllegalCharsetNameException icne) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
}
return 2;
} else if (args[i].equals("-disableXmlSecurity")) {
disableXmlSecurity();
return 1;
} else if (args[i].startsWith("-J")) {
if (javacOptions == null) {
javacOptions = new ArrayList<String>();
}
javacOptions.add(args[i].substring(2));
return 1;
}
return 0;
}
// protected method to allow overriding
protected void disableXmlSecurity() {
disableXmlSecurity= true;
}
/**
* Obtains an operand and reports an error if it's not there.
*/
public String requireArgument(String optionName, String[] args, int i) throws BadCommandLineException {
//if (i == args.length || args[i].startsWith("-")) {
if (args[i].startsWith("-")) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_MISSING_OPTION_ARGUMENT(optionName));
}
return args[i];
}
List<String> getJavacOptions(List<String> existingOptions, WsimportListener listener) {
List<String> result = new ArrayList<String>();
for (String o: javacOptions) {
if (o.contains("=") && !o.startsWith("A")) {
int i = o.indexOf('=');
String key = o.substring(0, i);
if (existingOptions.contains(key)) {
listener.message(WscompileMessages.WSCOMPILE_EXISTING_OPTION(key));
} else {
result.add(key);
result.add(o.substring(i + 1));
}
} else {
if (existingOptions.contains(o)) {
listener.message(WscompileMessages.WSCOMPILE_EXISTING_OPTION(o));
} else {
result.add(o);
}
}
}
return result;
}
/**
* Used to signal that we've finished processing.
*/
public static final class WeAreDone extends BadCommandLineException {}
/**
* Get a URLClassLoader from using the classpath
*/
public ClassLoader getClassLoader() {
if (classLoader == null) {
classLoader =
new URLClassLoader(pathToURLs(classpath),
this.getClass().getClassLoader());
}
return classLoader;
}
/**
* Utility method for converting a search path string to an array
* of directory and JAR file URLs.
*
* @param path the search path string
* @return the resulting array of directory and JAR file URLs
*/
public static URL[] pathToURLs(String path) {
StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
URL[] urls = new URL[st.countTokens()];
int count = 0;
while (st.hasMoreTokens()) {
URL url = fileToURL(new File(st.nextToken()));
if (url != null) {
urls[count++] = url;
}
}
if (urls.length != count) {
URL[] tmp = new URL[count];
System.arraycopy(urls, 0, tmp, 0, count);
urls = tmp;
}
return urls;
}
/**
* Returns the directory or JAR file URL corresponding to the specified
* local file name.
*
* @param file the File object
* @return the resulting directory or JAR file URL, or null if unknown
*/
public static URL fileToURL(File file) {
String name;
try {
name = file.getCanonicalPath();
} catch (IOException e) {
name = file.getAbsolutePath();
}
name = name.replace(File.separatorChar, '/');
if (!name.startsWith("/")) {
name = "/" + name;
}
// If the file does not exist, then assume that it's a directory
if (!file.isFile()) {
name = name + "/";
}
try {
return new URL("file", "", name);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("file");
}
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.tools.internal.ws.processor.model.Model;
import java.io.IOException;
import org.xml.sax.SAXException;
/**
* Add-on that works on the generated source code.
*
* <p> This add-on will be called after the default generation has finished.
*
* @author Lukas Jungmann
* @since 2.2.6
*/
public abstract class Plugin {
/**
* Gets the option name to turn on this add-on.
*
* <p> For example, if "abc" is returned, "-abc" will turn on this plugin. A
* plugin needs to be turned on explicitly, or else no other methods of {@link Plugin}
* will be invoked.
*
* <p> When an option matches the name returned from this method, WsImport
* will then invoke {@link #parseArgument(Options, String[], int)}, allowing
* plugins to handle arguments to this option.
*/
public abstract String getOptionName();
/**
* Gets the description of this add-on. Used to generate a usage screen.
*
* @return localized description message. should be terminated by \n.
*/
public abstract String getUsage();
/**
* Parses an option <code>args[i]</code> and augment the <code>opt</code> object
* appropriately, then return the number of tokens consumed.
*
* <p> The callee doesn't need to recognize the option that the
* getOptionName method returns.
*
* <p> Once a plugin is activated, this method is called for options that
* WsImport didn't recognize. This allows a plugin to define additional
* options to customize its behavior.
*
* <p> Since options can appear in no particular order, WsImport allows
* sub-options of a plugin to show up before the option that activates a
* plugin (one that's returned by {@link #getOptionName()}.)
*
* But nevertheless a {@link Plugin} needs to be activated to participate in
* further processing.
*
* @return 0 if the argument is not understood. Otherwise return the number
* of tokens that are consumed, including the option itself. (so if you have
* an option like "-foo 3", return 2.)
* @exception BadCommandLineException If the option was recognized but
* there's an error. This halts the argument parsing process and causes
* WsImport to abort, reporting an error.
*/
public int parseArgument(Options opt, String[] args, int i) throws BadCommandLineException, IOException {
return 0;
}
/**
* Notifies a plugin that it's activated.
*
* <p> This method is called when a plugin is activated through the command
* line option (as specified by {@link #getOptionName()}.
*
* <p> Noop by default.
*
*/
public void onActivated(Options opts) throws BadCommandLineException {
// noop
}
/**
* Run the add-on.
*
* <p> This method is invoked after WsImport has internally finished the
* code generation. Plugins can tweak some of the generated code (or add
* more code) by altering {@link JCodeModel} obtained from {@link WsimportOptions#getCodeModel()
* } according to the current
* {@link Model WSDL model} and {@link WsimportOptions}.
*
* <p> Note that this method is invoked only when a {@link Plugin} is
* activated.
*
* @param wsdlModel This object allows access to the WSDL model used for
* code generation.
*
* @param options This object allows access to various options used for code
* generation as well as access to the generated code.
*
* @param errorReceiver Errors should be reported to this handler.
*
* @return If the add-on executes successfully, return true. If it detects
* some errors but those are reported and recovered gracefully, return
* false.
*
* @throws SAXException After an error is reported to {@link ErrorReceiver},
* the same exception can be thrown to indicate a fatal irrecoverable error. {@link ErrorReceiver}
* itself may throw it, if it chooses not to recover from the error.
*/
public abstract boolean run(
Model wsdlModel, WsimportOptions options, ErrorReceiver errorReceiver) throws SAXException;
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.codemodel.internal.JPackage;
import com.sun.codemodel.internal.writer.FileCodeWriter;
import java.io.File;
import java.io.IOException;
/**
* {@link FileCodeWriter} implementation that notifies
* JAX-WS about newly created files.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class WSCodeWriter extends FileCodeWriter {
private final Options options;
public WSCodeWriter( File outDir, Options options) throws IOException {
super(outDir, options.encoding);
this.options = options;
}
protected File getFile(JPackage pkg, String fileName ) throws IOException {
File f = super.getFile(pkg, fileName);
options.addGeneratedFile(f);
// we can't really tell the file type, for we don't know
// what this file is used for. Fortunately,
// FILE_TYPE doesn't seem to be used, so it doesn't really
// matter what we set.
return f;
}
}

View File

@@ -0,0 +1,296 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.tools.internal.ws.api.WsgenExtension;
import com.sun.tools.internal.ws.api.WsgenProtocol;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.xml.internal.ws.api.BindingID;
import com.sun.xml.internal.ws.binding.SOAPBindingImpl;
import com.sun.xml.internal.ws.util.ServiceFinder;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Vivek Pandey
*/
public class WsgenOptions extends Options {
/**
* -servicename
*/
public QName serviceName;
/**
* -portname
*/
public QName portName;
/**
* -r
*/
public File nonclassDestDir;
/**
* -wsdl
*/
public boolean genWsdl;
/**
* -inlineSchemas
*/
public boolean inlineSchemas;
/**
* protocol value
*/
public String protocol = "soap1.1";
public Set<String> protocols = new LinkedHashSet<String>();
public Map<String, String> nonstdProtocols = new LinkedHashMap<String, String>();
/**
* -XwsgenReport
*/
public File wsgenReport;
/**
* -Xdonotoverwrite
*/
public boolean doNotOverWrite;
/**
* Tells if user specified a specific protocol
*/
public boolean protocolSet = false;
/**
* <code>-x file1 -x file2 ...<code/><br />
* Files to be parsed to get classes' metadata in addition/instead of using annotations and reflection API
*/
public List<String> externalMetadataFiles = new ArrayList<String>();
private static final String SERVICENAME_OPTION = "-servicename";
private static final String PORTNAME_OPTION = "-portname";
private static final String HTTP = "http";
private static final String SOAP11 = "soap1.1";
public static final String X_SOAP12 = "Xsoap1.2";
public WsgenOptions() {
protocols.add(SOAP11);
protocols.add(X_SOAP12);
nonstdProtocols.put(X_SOAP12, SOAPBindingImpl.X_SOAP12HTTP_BINDING);
ServiceFinder<WsgenExtension> extn = ServiceFinder.find(WsgenExtension.class);
for(WsgenExtension ext : extn) {
Class clazz = ext.getClass();
WsgenProtocol pro = (WsgenProtocol)clazz.getAnnotation(WsgenProtocol.class);
protocols.add(pro.token());
nonstdProtocols.put(pro.token(), pro.lexical());
}
}
@Override
protected int parseArguments(String[] args, int i) throws BadCommandLineException {
int j = super.parseArguments(args, i);
if (args[i].equals(SERVICENAME_OPTION)) {
serviceName = QName.valueOf(requireArgument(SERVICENAME_OPTION, args, ++i));
if (serviceName.getNamespaceURI() == null || serviceName.getNamespaceURI().length() == 0) {
throw new BadCommandLineException(WscompileMessages.WSGEN_SERVICENAME_MISSING_NAMESPACE(args[i]));
}
if (serviceName.getLocalPart() == null || serviceName.getLocalPart().length() == 0) {
throw new BadCommandLineException(WscompileMessages.WSGEN_SERVICENAME_MISSING_LOCALNAME(args[i]));
}
return 2;
} else if (args[i].equals(PORTNAME_OPTION)) {
portName = QName.valueOf(requireArgument(PORTNAME_OPTION, args, ++i));
if (portName.getNamespaceURI() == null || portName.getNamespaceURI().length() == 0) {
throw new BadCommandLineException(WscompileMessages.WSGEN_PORTNAME_MISSING_NAMESPACE(args[i]));
}
if (portName.getLocalPart() == null || portName.getLocalPart().length() == 0) {
throw new BadCommandLineException(WscompileMessages.WSGEN_PORTNAME_MISSING_LOCALNAME(args[i]));
}
return 2;
} else if (args[i].equals("-r")) {
nonclassDestDir = new File(requireArgument("-r", args, ++i));
if (!nonclassDestDir.exists()) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(nonclassDestDir.getPath()));
}
return 2;
} else if (args[i].startsWith("-wsdl")) {
genWsdl = true;
//String value = requireArgument("-wsdl", args, ++i).substring(5);
String value = args[i].substring(5);
int index = value.indexOf(':');
if (index == 0) {
value = value.substring(1);
index = value.indexOf('/');
if (index == -1) {
protocol = value;
} else {
protocol = value.substring(0, index);
}
protocolSet = true;
}
return 1;
} else if (args[i].equals("-XwsgenReport")) {
// undocumented switch for the test harness
wsgenReport = new File(requireArgument("-XwsgenReport", args, ++i));
return 2;
} else if (args[i].equals("-Xdonotoverwrite")) {
doNotOverWrite = true;
return 1;
} else if (args[i].equals("-inlineSchemas")) {
inlineSchemas = true;
return 1;
} else if ("-x".equals(args[i])) {
externalMetadataFiles.add(requireArgument("-x", args, ++i));
return 1;
}
return j;
}
@Override
protected void addFile(String arg) {
endpoints.add(arg);
}
List<String> endpoints = new ArrayList<String>();
public Class endpoint;
private boolean isImplClass;
public void validate() throws BadCommandLineException {
if(nonclassDestDir == null)
nonclassDestDir = destDir;
if (!protocols.contains(protocol)) {
throw new BadCommandLineException(WscompileMessages.WSGEN_INVALID_PROTOCOL(protocol, protocols));
}
if (endpoints.isEmpty()) {
throw new BadCommandLineException(WscompileMessages.WSGEN_MISSING_FILE());
}
if (protocol == null || protocol.equalsIgnoreCase(X_SOAP12) && !isExtensionMode()) {
throw new BadCommandLineException(WscompileMessages.WSGEN_SOAP_12_WITHOUT_EXTENSION());
}
if (nonstdProtocols.containsKey(protocol) && !isExtensionMode()) {
throw new BadCommandLineException(WscompileMessages.WSGEN_PROTOCOL_WITHOUT_EXTENSION(protocol));
}
if (inlineSchemas && !genWsdl) {
throw new BadCommandLineException(WscompileMessages.WSGEN_INLINE_SCHEMAS_ONLY_WITH_WSDL());
}
validateEndpointClass();
validateArguments();
}
/**
* Get an implementation class annotated with @WebService annotation.
*/
private void validateEndpointClass() throws BadCommandLineException {
Class clazz = null;
for(String cls : endpoints){
clazz = getClass(cls);
if (clazz == null)
continue;
if (clazz.isEnum() || clazz.isInterface() ||
clazz.isPrimitive()) {
continue;
}
isImplClass = true;
WebService webService = (WebService) clazz.getAnnotation(WebService.class);
if(webService == null)
continue;
break;
}
if(clazz == null){
throw new BadCommandLineException(WscompileMessages.WSGEN_CLASS_NOT_FOUND(endpoints.get(0)));
}
if(!isImplClass){
throw new BadCommandLineException(WscompileMessages.WSGEN_CLASS_MUST_BE_IMPLEMENTATION_CLASS(clazz.getName()));
}
endpoint = clazz;
validateBinding();
}
private void validateBinding() throws BadCommandLineException {
if (genWsdl) {
BindingID binding = BindingID.parse(endpoint);
if ((binding.equals(BindingID.SOAP12_HTTP) ||
binding.equals(BindingID.SOAP12_HTTP_MTOM)) &&
!(protocol.equals(X_SOAP12) && isExtensionMode())) {
throw new BadCommandLineException(WscompileMessages.WSGEN_CANNOT_GEN_WSDL_FOR_SOAP_12_BINDING(binding.toString(), endpoint.getName()));
}
if (binding.equals(BindingID.XML_HTTP)) {
throw new BadCommandLineException(WscompileMessages.WSGEN_CANNOT_GEN_WSDL_FOR_NON_SOAP_BINDING(binding.toString(), endpoint.getName()));
}
}
}
private void validateArguments() throws BadCommandLineException {
if (!genWsdl) {
if (serviceName != null) {
throw new BadCommandLineException(WscompileMessages.WSGEN_WSDL_ARG_NO_GENWSDL(SERVICENAME_OPTION));
}
if (portName != null) {
throw new BadCommandLineException(WscompileMessages.WSGEN_WSDL_ARG_NO_GENWSDL(PORTNAME_OPTION));
}
}
}
BindingID getBindingID(String protocol) {
if (protocol.equals(SOAP11))
return BindingID.SOAP11_HTTP;
if (protocol.equals(X_SOAP12))
return BindingID.SOAP12_HTTP;
String lexical = nonstdProtocols.get(protocol);
return (lexical != null) ? BindingID.parse(lexical) : null;
}
private Class getClass(String className) {
try {
return getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
return null;
}
}
}

View File

@@ -0,0 +1,448 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.oracle.webservices.internal.api.databinding.WSDLResolver;
import com.sun.istack.internal.tools.ParallelWorldClassLoader;
import com.sun.tools.internal.ws.ToolVersion;
import com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAp;
import com.sun.tools.internal.ws.processor.modeler.wsdl.ConsoleErrorReporter;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.xjc.util.NullStream;
import com.sun.xml.internal.txw2.TXW;
import com.sun.xml.internal.txw2.TypedXmlWriter;
import com.sun.xml.internal.txw2.annotation.XmlAttribute;
import com.sun.xml.internal.txw2.annotation.XmlElement;
import com.sun.xml.internal.txw2.output.StreamSerializer;
import com.sun.xml.internal.ws.api.BindingID;
import com.sun.xml.internal.ws.api.databinding.DatabindingConfig;
import com.sun.xml.internal.ws.api.databinding.DatabindingFactory;
import com.sun.xml.internal.ws.api.databinding.WSDLGenInfo;
import com.sun.xml.internal.ws.api.server.Container;
import com.sun.xml.internal.ws.api.wsdl.writer.WSDLGeneratorExtension;
import com.sun.xml.internal.ws.binding.WebServiceFeatureList;
import com.sun.xml.internal.ws.model.ExternalMetadataReader;
import com.sun.xml.internal.ws.model.AbstractSEIModelImpl;
import com.sun.xml.internal.ws.util.ServiceFinder;
import org.xml.sax.SAXParseException;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.Holder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Vivek Pandey
*/
/*
* All annotation types are supported.
*/
public class WsgenTool {
private final PrintStream out;
private final WsgenOptions options = new WsgenOptions();
public WsgenTool(OutputStream out, Container container) {
this.out = (out instanceof PrintStream) ? (PrintStream) out : new PrintStream(out);
this.container = container;
}
public WsgenTool(OutputStream out) {
this(out, null);
}
public boolean run(String[] args) {
final Listener listener = new Listener();
for (String arg : args) {
if (arg.equals("-version")) {
listener.message(
WscompileMessages.WSGEN_VERSION(ToolVersion.VERSION.MAJOR_VERSION));
return true;
}
if (arg.equals("-fullversion")) {
listener.message(
WscompileMessages.WSGEN_FULLVERSION(ToolVersion.VERSION.toString()));
return true;
}
}
try {
options.parseArguments(args);
options.validate();
if (!buildModel(options.endpoint.getName(), listener)) {
return false;
}
} catch (Options.WeAreDone done) {
usage(done.getOptions());
} catch (BadCommandLineException e) {
if (e.getMessage() != null) {
System.out.println(e.getMessage());
System.out.println();
}
usage(e.getOptions());
return false;
} catch (AbortException e) {
//error might have been reported
} finally {
if (!options.keep) {
options.removeGeneratedFiles();
}
}
return true;
}
private final Container container;
/*
* To take care of JDK6-JDK6u3, where 2.1 API classes are not there
*/
private static boolean useBootClasspath(Class clazz) {
try {
ParallelWorldClassLoader.toJarUrl(clazz.getResource('/' + clazz.getName().replace('.', '/') + ".class"));
return true;
} catch (Exception e) {
return false;
}
}
/**
*
* @param endpoint
* @param listener
* @return
* @throws BadCommandLineException
*/
public boolean buildModel(String endpoint, Listener listener) throws BadCommandLineException {
final ErrorReceiverFilter errReceiver = new ErrorReceiverFilter(listener);
boolean bootCP = useBootClasspath(EndpointReference.class) || useBootClasspath(XmlSeeAlso.class);
List<String> args = new ArrayList<String>(6 + (bootCP ? 1 : 0) + (options.nocompile ? 1 : 0)
+ (options.encoding != null ? 2 : 0));
args.add("-d");
args.add(options.destDir.getAbsolutePath());
args.add("-classpath");
args.add(options.classpath);
args.add("-s");
args.add(options.sourceDir.getAbsolutePath());
if (options.nocompile) {
args.add("-proc:only");
}
if (options.encoding != null) {
args.add("-encoding");
args.add(options.encoding);
}
if (bootCP) {
args.add(new StringBuilder()
.append("-Xbootclasspath/p:")
.append(JavaCompilerHelper.getJarFile(EndpointReference.class))
.append(File.pathSeparator)
.append(JavaCompilerHelper.getJarFile(XmlSeeAlso.class)).toString());
}
if (options.javacOptions != null) {
args.addAll(options.getJavacOptions(args, listener));
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();// compiler = JavacTool.create();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
JavaCompiler.CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
args,
Collections.singleton(endpoint.replaceAll("\\$", ".")),
null);
task.setProcessors(Collections.singleton(new WebServiceAp(options, out)));
boolean result = task.call();
if (!result) {
out.println(WscompileMessages.WSCOMPILE_ERROR(WscompileMessages.WSCOMPILE_COMPILATION_FAILED()));
return false;
}
if (options.genWsdl) {
DatabindingConfig config = new DatabindingConfig();
List<String> externalMetadataFileNames = options.externalMetadataFiles;
boolean disableXmlSecurity = options.disableXmlSecurity;
if (externalMetadataFileNames != null && externalMetadataFileNames.size() > 0) {
config.setMetadataReader(new ExternalMetadataReader(getExternalFiles(externalMetadataFileNames), null, null, true, disableXmlSecurity));
}
String tmpPath = options.destDir.getAbsolutePath() + File.pathSeparator + options.classpath;
ClassLoader classLoader = new URLClassLoader(Options.pathToURLs(tmpPath),
this.getClass().getClassLoader());
Class<?> endpointClass;
try {
endpointClass = classLoader.loadClass(endpoint);
} catch (ClassNotFoundException e) {
throw new BadCommandLineException(WscompileMessages.WSGEN_CLASS_NOT_FOUND(endpoint));
}
BindingID bindingID = options.getBindingID(options.protocol);
if (!options.protocolSet) {
bindingID = BindingID.parse(endpointClass);
}
WebServiceFeatureList wsfeatures = new WebServiceFeatureList(endpointClass);
// RuntimeModeler rtModeler = new RuntimeModeler(endpointClass, options.serviceName, bindingID, wsfeatures.toArray());
// rtModeler.setClassLoader(classLoader);
if (options.portName != null)
config.getMappingInfo().setPortName(options.portName);//rtModeler.setPortName(options.portName);
// AbstractSEIModelImpl rtModel = rtModeler.buildRuntimeModel();
DatabindingFactory fac = DatabindingFactory.newInstance();
config.setEndpointClass(endpointClass);
config.getMappingInfo().setServiceName(options.serviceName);
config.setFeatures(wsfeatures.toArray());
config.setClassLoader(classLoader);
config.getMappingInfo().setBindingID(bindingID);
com.sun.xml.internal.ws.db.DatabindingImpl rt = (com.sun.xml.internal.ws.db.DatabindingImpl) fac.createRuntime(config);
final File[] wsdlFileName = new File[1]; // used to capture the generated WSDL file.
final Map<String, File> schemaFiles = new HashMap<String, File>();
WSDLGenInfo wsdlGenInfo = new WSDLGenInfo();
wsdlGenInfo.setSecureXmlProcessingDisabled(disableXmlSecurity);
wsdlGenInfo.setWsdlResolver(
new WSDLResolver() {
private File toFile(String suggestedFilename) {
return new File(options.nonclassDestDir, suggestedFilename);
}
private Result toResult(File file) {
Result result;
try {
result = new StreamResult(new FileOutputStream(file));
result.setSystemId(file.getPath().replace('\\', '/'));
} catch (FileNotFoundException e) {
errReceiver.error(e);
return null;
}
return result;
}
@Override
public Result getWSDL(String suggestedFilename) {
File f = toFile(suggestedFilename);
wsdlFileName[0] = f;
return toResult(f);
}
public Result getSchemaOutput(String namespace, String suggestedFilename) {
if (namespace == null)
return null;
File f = toFile(suggestedFilename);
schemaFiles.put(namespace, f);
return toResult(f);
}
@Override
public Result getAbstractWSDL(Holder<String> filename) {
return toResult(toFile(filename.value));
}
@Override
public Result getSchemaOutput(String namespace, Holder<String> filename) {
return getSchemaOutput(namespace, filename.value);
}
// TODO pass correct impl's class name
});
wsdlGenInfo.setContainer(container);
wsdlGenInfo.setExtensions(ServiceFinder.find(WSDLGeneratorExtension.class).toArray());
wsdlGenInfo.setInlineSchemas(options.inlineSchemas);
rt.generateWSDL(wsdlGenInfo);
if (options.wsgenReport != null)
generateWsgenReport(endpointClass, (AbstractSEIModelImpl) rt.getModel(), wsdlFileName[0], schemaFiles);
}
return true;
}
private List<File> getExternalFiles(List<String> exts) {
List<File> files = new ArrayList<File>();
for (String ext : exts) {
// first try absolute path ...
File file = new File(ext);
if (!file.exists()) {
// then relative path ...
file = new File(options.sourceDir.getAbsolutePath() + File.separator + ext);
}
files.add(file);
}
return files;
}
/**
* Generates a small XML file that captures the key activity of wsgen,
* so that test harness can pick up artifacts.
*/
private void generateWsgenReport(Class<?> endpointClass, AbstractSEIModelImpl rtModel, File wsdlFile, Map<String, File> schemaFiles) {
try {
ReportOutput.Report report = TXW.create(ReportOutput.Report.class,
new StreamSerializer(new BufferedOutputStream(new FileOutputStream(options.wsgenReport))));
report.wsdl(wsdlFile.getAbsolutePath());
ReportOutput.writeQName(rtModel.getServiceQName(), report.service());
ReportOutput.writeQName(rtModel.getPortName(), report.port());
ReportOutput.writeQName(rtModel.getPortTypeName(), report.portType());
report.implClass(endpointClass.getName());
for (Map.Entry<String, File> e : schemaFiles.entrySet()) {
ReportOutput.Schema s = report.schema();
s.ns(e.getKey());
s.location(e.getValue().getAbsolutePath());
}
report.commit();
} catch (IOException e) {
// this is code for the test, so we can be lousy in the error handling
throw new Error(e);
}
}
/**
* "Namespace" for code needed to generate the report file.
*/
static class ReportOutput {
@XmlElement("report")
interface Report extends TypedXmlWriter {
@XmlElement
void wsdl(String file); // location of WSDL
@XmlElement
QualifiedName portType();
@XmlElement
QualifiedName service();
@XmlElement
QualifiedName port();
/**
* Name of the class that has {@link javax.jws.WebService}.
*/
@XmlElement
void implClass(String name);
@XmlElement
Schema schema();
}
interface QualifiedName extends TypedXmlWriter {
@XmlAttribute
void uri(String ns);
@XmlAttribute
void localName(String localName);
}
interface Schema extends TypedXmlWriter {
@XmlAttribute
void ns(String ns);
@XmlAttribute
void location(String filePath);
}
private static void writeQName(QName n, QualifiedName w) {
w.uri(n.getNamespaceURI());
w.localName(n.getLocalPart());
}
}
protected void usage(Options options) {
// Just don't see any point in passing WsgenOptions
// BadCommandLineException also shouldn't have options
if (options == null)
options = this.options;
if (options instanceof WsgenOptions) {
System.out.println(WscompileMessages.WSGEN_HELP("WSGEN",
((WsgenOptions)options).protocols,
((WsgenOptions)options).nonstdProtocols.keySet()));
System.out.println(WscompileMessages.WSGEN_USAGE_EXTENSIONS());
System.out.println(WscompileMessages.WSGEN_USAGE_EXAMPLES());
}
}
class Listener extends WsimportListener {
ConsoleErrorReporter cer = new ConsoleErrorReporter(out == null ? new PrintStream(new NullStream()) : out);
@Override
public void generatedFile(String fileName) {
message(fileName);
}
@Override
public void message(String msg) {
out.println(msg);
}
@Override
public void error(SAXParseException exception) {
cer.error(exception);
}
@Override
public void fatalError(SAXParseException exception) {
cer.fatalError(exception);
}
@Override
public void warning(SAXParseException exception) {
cer.warning(exception);
}
@Override
public void info(SAXParseException exception) {
cer.info(exception);
}
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.tools.internal.xjc.api.ErrorListener;
import org.xml.sax.SAXParseException;
/**
* @author Vivek Pandey
*/
public class WsimportListener implements ErrorListener {
/**
* Called for each file generated by wsimport or wsgen.
*
* <p>
* The file name includes the path portions that correspond with the package name.
*
* <p>
* When generating files into a directory, file names will be relative to the
* output directory.
*
* @param fileName
* file names like "org/acme/foo/Foo.java"
*
*/
public void generatedFile(String fileName) {}
/**
* Other miscellenous messages that do not have structures
* will be reported through this method.
*
* This method is used like {@link java.io.PrintStream#println(String)}.
* The callee is expected to add '\n'.
*/
public void message(String msg) {}
public void error(SAXParseException exception) {
}
public void fatalError(SAXParseException exception) {
}
public void warning(SAXParseException exception) {
}
public void info(SAXParseException exception) {
}
public void debug(SAXParseException exception){}
/**
* wsimport will periodically invoke this method to see if it should cancel a compilation.
*
* @return
* true if the {@link com.sun.tools.internal.ws.wscompile.WsimportListener} wants to abort the processing.
* @since 2.1
*/
public boolean isCanceled() {
return false;
}
}

View File

@@ -0,0 +1,783 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.tools.internal.ws.processor.generator.GeneratorExtension;
import com.sun.tools.internal.ws.resources.ConfigurationMessages;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.ws.util.ForkEntityResolver;
import com.sun.tools.internal.ws.wsdl.document.jaxws.JAXWSBindingsConstants;
import com.sun.tools.internal.ws.wsdl.document.schema.SchemaConstants;
import com.sun.tools.internal.xjc.api.SchemaCompiler;
import com.sun.tools.internal.xjc.api.SpecVersion;
import com.sun.tools.internal.xjc.api.XJC;
import com.sun.tools.internal.xjc.reader.Util;
import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil;
import com.sun.xml.internal.ws.util.ServiceFinder;
import com.sun.xml.internal.ws.util.JAXWSUtils;
import com.sun.xml.internal.ws.util.xml.XmlUtil;
import org.w3c.dom.Element;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.LocatorImpl;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Vivek Pandey
*/
public class WsimportOptions extends Options {
/**
* -wsdlLocation
*/
public String wsdlLocation;
/**
* Actually stores {@link com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver}, but the field
* type is made to {@link org.xml.sax.EntityResolver} so that XJC can be
* used even if resolver.jar is not available in the classpath.
*/
public EntityResolver entityResolver = null;
/**
* The -p option that should control the default Java package that
* will contain the generated code. Null if unspecified.
*/
public String defaultPackage = null;
/**
* The -clientjar option to package client artifacts as jar
*/
public String clientjar = null;
/**
* -XadditionalHeaders
*/
public boolean additionalHeaders;
/**
* The option indicates the dir where the jwsImpl will be generated.
*/
public File implDestDir = null;
/**
* optional, generated impl file only for the ordered serviceName
* Note: It is a QName string, formatted as: "{" + Namespace URI + "}" + local part
*/
public String implServiceName = null;
/**
* optional, generated impl file only for the ordered portName
* Note: It is a QName string, formatted as: "{" + Namespace URI + "}" + local part
*/
public String implPortName = null;
/**
* optional, if true JWS file is generated
*/
public boolean isGenerateJWS = false;
/**
* Setting disableSSLHostVerification to true disables the SSL Hostname verification while fetching the wsdls.
* -XdisableSSLHostVerification
*/
public boolean disableSSLHostnameVerification;
/**
* Setting useBaseResourceAndURLToLoadWSDL to true causes generated Service classes to load the WSDL file from
* a URL generated from the base resource.
* -XuseBaseResourceAndURLToLoadWSDL
*/
public boolean useBaseResourceAndURLToLoadWSDL = false;
/**
* JAXB's {@link SchemaCompiler} to be used for handling the schema portion.
* This object is also configured through options.
*/
private SchemaCompiler schemaCompiler = XJC.createSchemaCompiler();
/**
* Authentication file
*/
public File authFile = null;
//can user.home value be null?
public static final String defaultAuthfile
= System.getProperty("user.home") + System.getProperty("file.separator")
+ ".metro" + System.getProperty("file.separator") + "auth";
/**
* Setting disableAuthenticator to true disables the DefaultAuthenticator.
* -XdisableAuthenticator
*/
public boolean disableAuthenticator;
public String proxyAuth = null;
private String proxyHost = null;
private String proxyPort = null;
/**
* Additional arguments
*/
public HashMap<String, String> extensionOptions = new HashMap<String, String>();
/**
* All discovered {@link Plugin}s.
* This is lazily parsed, so that we can take '-cp' option into account.
*
* @see #getAllPlugins()
*/
private List<Plugin> allPlugins;
/**
* {@link Plugin}s that are enabled in this compilation.
*/
public final List<Plugin> activePlugins = new ArrayList<Plugin>();
public JCodeModel getCodeModel() {
if(codeModel == null)
codeModel = new JCodeModel();
return codeModel;
}
public SchemaCompiler getSchemaCompiler() {
schemaCompiler.setTargetVersion(SpecVersion.parse(target.getVersion()));
if(entityResolver != null) {
//set if its not null so as not to override catalog option specified via xjc args
schemaCompiler.setEntityResolver(entityResolver);
}
return schemaCompiler;
}
public void setCodeModel(JCodeModel codeModel) {
this.codeModel = codeModel;
}
private JCodeModel codeModel;
/**
* This captures jars passed on the commandline and passes them to XJC and puts them in the classpath for compilation
*/
public List<String> cmdlineJars = new ArrayList<String>();
/**
* Gets all the {@link Plugin}s discovered so far.
*
* <p>
* A plugins are enumerated when this method is called for the first time,
* by taking {@link #classpath} into account. That means
* "-cp plugin.jar" has to come before you specify options to enable it.
*/
public List<Plugin> getAllPlugins() {
if(allPlugins==null) {
allPlugins = new ArrayList<Plugin>();
allPlugins.addAll(Arrays.asList(findServices(Plugin.class, getClassLoader())));
}
return allPlugins;
}
/**
* Parses arguments and fill fields of this object.
*
* @exception BadCommandLineException
* thrown when there's a problem in the command-line arguments
*/
@Override
public final void parseArguments( String[] args ) throws BadCommandLineException {
for (int i = 0; i < args.length; i++) {
if(args[i].length()==0)
throw new BadCommandLineException();
if (args[i].charAt(0) == '-') {
int j = parseArguments(args,i);
if(j==0)
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_INVALID_OPTION(args[i]));
i += (j-1);
} else {
if(args[i].endsWith(".jar")) {
try {
cmdlineJars.add(args[i]);
schemaCompiler.getOptions().scanEpisodeFile(new File(args[i]));
} catch (com.sun.tools.internal.xjc.BadCommandLineException e) {
//Driver.usage(jaxbOptions,false);
throw new BadCommandLineException(e.getMessage(), e);
}
} else{
addFile(args[i]);
}
}
}
if (encoding != null && schemaCompiler.getOptions().encoding == null) {
try {
schemaCompiler.getOptions().parseArgument(
new String[] {"-encoding", encoding}, 0);
} catch (com.sun.tools.internal.xjc.BadCommandLineException ex) {
Logger.getLogger(WsimportOptions.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(destDir == null)
destDir = new File(".");
if(sourceDir == null)
sourceDir = destDir;
}
/** -Xno-addressing-databinding option to disable addressing namespace data binding. This is
* experimental switch and will be working as a temporary workaround till
* jaxb can provide a better way to selelctively disable compiling of an
* schema component.
* **/
public boolean noAddressingBbinding;
@Override
public int parseArguments(String[] args, int i) throws BadCommandLineException {
int j = super.parseArguments(args ,i);
if(j>0) return j; // understood by the super class
if (args[i].equals("-b")) {
addBindings(requireArgument("-b", args, ++i));
return 2;
} else if (args[i].equals("-wsdllocation")) {
wsdlLocation = requireArgument("-wsdllocation", args, ++i);
return 2;
} else if (args[i].equals("-XadditionalHeaders")) {
additionalHeaders = true;
return 1;
} else if (args[i].equals("-XdisableSSLHostnameVerification")) {
disableSSLHostnameVerification = true;
return 1;
} else if (args[i].equals("-p")) {
defaultPackage = requireArgument("-p", args, ++i);
return 2;
} else if (args[i].equals("-catalog")) {
String catalog = requireArgument("-catalog", args, ++i);
try {
if (entityResolver == null) {
if (catalog != null && catalog.length() > 0)
entityResolver = XmlUtil.createEntityResolver(JAXWSUtils.getFileOrURL(JAXWSUtils.absolutize(Util.escapeSpace(catalog))));
} else if (catalog != null && catalog.length() > 0) {
EntityResolver er = XmlUtil.createEntityResolver(JAXWSUtils.getFileOrURL(JAXWSUtils.absolutize(Util.escapeSpace(catalog))));
entityResolver = new ForkEntityResolver(er, entityResolver);
}
} catch (IOException e) {
throw new BadCommandLineException(WscompileMessages.WSIMPORT_FAILED_TO_PARSE(catalog, e.getMessage()));
}
return 2;
} else if (args[i].startsWith("-httpproxy:")) {
String value = args[i].substring(11);
if (value.length() == 0) {
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_INVALID_OPTION(args[i]));
}
parseProxy(value);
if (proxyHost != null || proxyPort != null) {
System.setProperty("proxySet", "true");
}
if (proxyHost != null) {
System.setProperty("proxyHost", proxyHost);
}
if (proxyPort != null) {
System.setProperty("proxyPort", proxyPort);
}
return 1;
} else if (args[i].equals("-Xno-addressing-databinding")) {
noAddressingBbinding = true;
return 1;
} else if (args[i].startsWith("-B")) {
// JAXB option pass through.
String[] subCmd = new String[args.length-i];
System.arraycopy(args,i,subCmd,0,subCmd.length);
subCmd[0] = subCmd[0].substring(2); // trim off the first "-B"
com.sun.tools.internal.xjc.Options jaxbOptions = schemaCompiler.getOptions();
try {
int r = jaxbOptions.parseArgument(subCmd, 0);
if(r==0) {
//Driver.usage(jaxbOptions,false);
throw new BadCommandLineException(WscompileMessages.WSIMPORT_NO_SUCH_JAXB_OPTION(subCmd[0]));
}
return r;
} catch (com.sun.tools.internal.xjc.BadCommandLineException e) {
//Driver.usage(jaxbOptions,false);
throw new BadCommandLineException(e.getMessage(),e);
}
} else if (args[i].equals("-Xauthfile")) {
String authfile = requireArgument("-Xauthfile", args, ++i);
authFile = new File(authfile);
return 2;
} else if (args[i].equals("-clientjar")) {
clientjar = requireArgument("-clientjar", args, ++i);
return 2;
} else if (args[i].equals("-implDestDir")) {
implDestDir = new File(requireArgument("-implDestDir", args, ++i));
if (!implDestDir.exists())
throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(implDestDir.getPath()));
return 2;
} else if (args[i].equals("-implServiceName")) {
implServiceName = requireArgument("-implServiceName", args, ++i);
return 2;
} else if (args[i].equals("-implPortName")) {
implPortName = requireArgument("-implPortName", args, ++i);
return 2;
} else if (args[i].equals("-generateJWS")) {
isGenerateJWS = true;
return 1;
} else if (args[i].equals("-XuseBaseResourceAndURLToLoadWSDL")) {
useBaseResourceAndURLToLoadWSDL = true;
return 1;
} else if (args[i].equals("-XdisableAuthenticator")) {
disableAuthenticator = true;
return 1;
}
// handle additional options
for (GeneratorExtension f:ServiceFinder.find(GeneratorExtension.class)) {
if (f.validateOption(args[i])) {
extensionOptions.put(args[i], requireArgument(args[i], args, ++i));
return 2;
}
}
// see if this is one of the extensions
for( Plugin plugin : getAllPlugins() ) {
try {
if(('-' + plugin.getOptionName()).equals(args[i])) {
activePlugins.add(plugin);
plugin.onActivated(this);
return 1;
}
int r = plugin.parseArgument(this, args, i);
if (r != 0) {
return r;
}
} catch (IOException e) {
throw new BadCommandLineException(e.getMessage(),e);
}
}
return 0; // what's this option?
}
public void validate() throws BadCommandLineException {
if (wsdls.isEmpty()) {
throw new BadCommandLineException(WscompileMessages.WSIMPORT_MISSING_FILE());
}
if(wsdlLocation !=null && clientjar != null) {
throw new BadCommandLineException(WscompileMessages.WSIMPORT_WSDLLOCATION_CLIENTJAR());
}
if(wsdlLocation == null){
wsdlLocation = wsdls.get(0).getSystemId();
}
}
@Override
protected void addFile(String arg) throws BadCommandLineException {
addFile(arg, wsdls, ".wsdl");
}
private final List<InputSource> wsdls = new ArrayList<InputSource>();
private final List<InputSource> schemas = new ArrayList<InputSource>();
private final List<InputSource> bindingFiles = new ArrayList<InputSource>();
private final List<InputSource> jaxwsCustomBindings = new ArrayList<InputSource>();
private final List<InputSource> jaxbCustomBindings = new ArrayList<InputSource>();
private final List<Element> handlerConfigs = new ArrayList<Element>();
/**
* There is supposed to be one handler chain per generated SEI.
* TODO: There is possible bug, how to associate a @HandlerChain
* with each port on the generated SEI. For now lets preserve the JAXWS 2.0 FCS
* behaviour and generate only one @HandlerChain on the SEI
*/
public Element getHandlerChainConfiguration(){
if(handlerConfigs.size() > 0)
return handlerConfigs.get(0);
return null;
}
public void addHandlerChainConfiguration(Element config){
handlerConfigs.add(config);
}
public InputSource[] getWSDLs() {
return wsdls.toArray(new InputSource[wsdls.size()]);
}
public InputSource[] getSchemas() {
return schemas.toArray(new InputSource[schemas.size()]);
}
public InputSource[] getWSDLBindings() {
return jaxwsCustomBindings.toArray(new InputSource[jaxwsCustomBindings.size()]);
}
public InputSource[] getSchemaBindings() {
return jaxbCustomBindings.toArray(new InputSource[jaxbCustomBindings.size()]);
}
public void addWSDL(File source) {
addWSDL(fileToInputSource(source));
}
public void addWSDL(InputSource is) {
wsdls.add(absolutize(is));
}
public void addSchema(File source) {
addSchema(fileToInputSource(source));
}
public void addSchema(InputSource is) {
schemas.add(is);
}
private InputSource fileToInputSource(File source) {
try {
String url = source.toURL().toExternalForm();
return new InputSource(Util.escapeSpace(url));
} catch (MalformedURLException e) {
return new InputSource(source.getPath());
}
}
/**
* Recursively scan directories and add all XSD files in it.
*/
public void addGrammarRecursive(File dir) {
addRecursive(dir, ".wsdl", wsdls);
addRecursive(dir, ".xsd", schemas);
}
/**
* Adds a new input schema.
*/
public void addWSDLBindFile(InputSource is) {
jaxwsCustomBindings.add(new RereadInputSource(absolutize(is)));
}
public void addSchemmaBindFile(InputSource is) {
jaxbCustomBindings.add(new RereadInputSource(absolutize(is)));
}
private void addRecursive(File dir, String suffix, List<InputSource> result) {
File[] files = dir.listFiles();
if (files == null) return; // work defensively
for (File f : files) {
if (f.isDirectory())
addRecursive(f, suffix, result);
else if (f.getPath().endsWith(suffix))
result.add(absolutize(fileToInputSource(f)));
}
}
private InputSource absolutize(InputSource is) {
// absolutize all the system IDs in the input,
// so that we can map system IDs to DOM trees.
try {
URL baseURL = new File(".").getCanonicalFile().toURL();
is.setSystemId(new URL(baseURL, is.getSystemId()).toExternalForm());
} catch (IOException e) {
// ignore
}
return is;
}
public void addBindings(String name) throws BadCommandLineException {
addFile(name, bindingFiles, null);
}
/**
* Parses a token to a file (or a set of files)
* and add them as {@link InputSource} to the specified list.
*
* @param suffix If the given token is a directory name, we do a recusive search
* and find all files that have the given suffix.
*/
private void addFile(String name, List<InputSource> target, String suffix) throws BadCommandLineException {
Object src;
try {
src = Util.getFileOrURL(name);
} catch (IOException e) {
throw new BadCommandLineException(WscompileMessages.WSIMPORT_NOT_A_FILE_NOR_URL(name));
}
if (src instanceof URL) {
target.add(absolutize(new InputSource(Util.escapeSpace(((URL) src).toExternalForm()))));
} else {
File fsrc = (File) src;
if (fsrc.isDirectory()) {
addRecursive(fsrc, suffix, target);
} else {
target.add(absolutize(fileToInputSource(fsrc)));
}
}
}
/**
* Exposing it as a public method to allow external tools such as NB to read from wsdl model and work on it.
* TODO: WSDL model needs to be exposed - basically at tool time we need to use the runtimw wsdl model
*
* Binding files could be jaxws or jaxb. This method identifies jaxws and jaxb binding files and keeps them separately. jaxb binding files are given separately
* to JAXB in {@link com.sun.tools.internal.ws.processor.modeler.wsdl.JAXBModelBuilder}
*
* @param receiver {@link ErrorReceiver}
*/
public final void parseBindings(ErrorReceiver receiver){
for (InputSource is : bindingFiles) {
XMLStreamReader reader =
XMLStreamReaderFactory.create(is,true);
XMLStreamReaderUtil.nextElementContent(reader);
if (reader.getName().equals(JAXWSBindingsConstants.JAXWS_BINDINGS)) {
jaxwsCustomBindings.add(new RereadInputSource(is));
} else if (reader.getName().equals(JAXWSBindingsConstants.JAXB_BINDINGS) ||
reader.getName().equals(new QName(SchemaConstants.NS_XSD, "schema"))) {
jaxbCustomBindings.add(new RereadInputSource(is));
} else {
LocatorImpl locator = new LocatorImpl();
locator.setSystemId(reader.getLocation().getSystemId());
locator.setPublicId(reader.getLocation().getPublicId());
locator.setLineNumber(reader.getLocation().getLineNumber());
locator.setColumnNumber(reader.getLocation().getColumnNumber());
receiver.warning(locator, ConfigurationMessages.CONFIGURATION_NOT_BINDING_FILE(is.getSystemId()));
}
}
}
/**
* Get extension argument
*/
public String getExtensionOption(String argument) {
return extensionOptions.get(argument);
}
private void parseProxy(String text) throws BadCommandLineException {
int i = text.lastIndexOf('@');
int j = text.lastIndexOf(':');
if (i > 0) {
proxyAuth = text.substring(0, i);
if (j > i) {
proxyHost = text.substring(i + 1, j);
proxyPort = text.substring(j + 1);
} else {
proxyHost = text.substring(i + 1);
proxyPort = "8080";
}
} else {
//no auth info
if (j < 0) {
//no port
proxyHost = text;
proxyPort = "8080";
} else {
proxyHost = text.substring(0, j);
proxyPort = text.substring(j + 1);
}
}
try {
Integer.valueOf(proxyPort);
} catch (NumberFormatException e) {
throw new BadCommandLineException(WscompileMessages.WSIMPORT_ILLEGAL_PROXY(text));
}
}
/**
* Looks for all "META-INF/services/[className]" files and
* create one instance for each class name found inside this file.
*/
private static <T> T[] findServices(Class<T> clazz, ClassLoader classLoader) {
ServiceFinder<T> serviceFinder = ServiceFinder.find(clazz, classLoader);
List<T> r = new ArrayList<T>();
for (T t : serviceFinder) {
r.add(t);
}
return r.toArray((T[]) Array.newInstance(clazz, r.size()));
}
private static final class ByteStream extends ByteArrayOutputStream {
byte[] getBuffer() {
return buf;
}
}
private static final class RereadInputStream extends InputStream {
private InputStream is;
private ByteStream bs;
RereadInputStream(InputStream is) {
this.is = is;
this.bs = new ByteStream();
}
@Override
public int available() throws IOException {
return is.available();
}
@Override
public void close() throws IOException {
if (bs != null) {
InputStream i = new ByteArrayInputStream(bs.getBuffer());
bs = null;
is.close();
is = i;
}
}
@Override
public synchronized void mark(int readlimit) {
is.mark(readlimit);
}
@Override
public boolean markSupported() {
return is.markSupported();
}
@Override
public int read() throws IOException {
int r = is.read();
if (bs != null)
bs.write(r);
return r;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int r = is.read(b, off, len);
if (r > 0 && bs != null)
bs.write(b, off, r);
return r;
}
@Override
public int read(byte[] b) throws IOException {
int r = is.read(b);
if (r > 0 && bs != null)
bs.write(b, 0, r);
return r;
}
@Override
public synchronized void reset() throws IOException {
is.reset();
}
}
private static final class RereadInputSource extends InputSource {
private InputSource is;
RereadInputSource(InputSource is) {
this.is = is;
}
@Override
public InputStream getByteStream() {
InputStream i = is.getByteStream();
if (i != null && !(i instanceof RereadInputStream)) {
i = new RereadInputStream(i);
is.setByteStream(i);
}
return i;
}
@Override
public Reader getCharacterStream() {
// TODO Auto-generated method stub
return is.getCharacterStream();
}
@Override
public String getEncoding() {
return is.getEncoding();
}
@Override
public String getPublicId() {
return is.getPublicId();
}
@Override
public String getSystemId() {
return is.getSystemId();
}
@Override
public void setByteStream(InputStream byteStream) {
is.setByteStream(byteStream);
}
@Override
public void setCharacterStream(Reader characterStream) {
is.setCharacterStream(characterStream);
}
@Override
public void setEncoding(String encoding) {
is.setEncoding(encoding);
}
@Override
public void setPublicId(String publicId) {
is.setPublicId(publicId);
}
@Override
public void setSystemId(String systemId) {
is.setSystemId(systemId);
}
}
@Override
protected void disableXmlSecurity() {
super.disableXmlSecurity();
schemaCompiler.getOptions().disableXmlSecurity = true;
}
}

View File

@@ -0,0 +1,586 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile;
import com.sun.codemodel.internal.CodeWriter;
import com.sun.codemodel.internal.writer.ProgressCodeWriter;
import com.sun.istack.internal.tools.DefaultAuthenticator;
import com.sun.tools.internal.ws.ToolVersion;
import com.sun.tools.internal.ws.api.TJavaGeneratorExtension;
import com.sun.tools.internal.ws.processor.generator.CustomExceptionGenerator;
import com.sun.tools.internal.ws.processor.generator.GeneratorBase;
import com.sun.tools.internal.ws.processor.generator.SeiGenerator;
import com.sun.tools.internal.ws.processor.generator.ServiceGenerator;
import com.sun.tools.internal.ws.processor.generator.JwsImplGenerator;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.processor.modeler.wsdl.ConsoleErrorReporter;
import com.sun.tools.internal.ws.processor.modeler.wsdl.WSDLModeler;
import com.sun.tools.internal.ws.processor.util.DirectoryUtil;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.ws.resources.WsdlMessages;
import com.sun.tools.internal.ws.util.WSDLFetcher;
import com.sun.tools.internal.ws.wsdl.parser.MetadataFinder;
import com.sun.tools.internal.ws.wsdl.parser.WSDLInternalizationLogic;
import com.sun.tools.internal.xjc.util.NullStream;
import com.sun.xml.internal.ws.api.server.Container;
import com.sun.xml.internal.ws.util.ServiceFinder;
import com.sun.istack.internal.tools.ParallelWorldClassLoader;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXParseException;
import javax.xml.bind.JAXBPermission;
import javax.xml.stream.*;
import javax.xml.ws.EndpointContext;
import java.io.*;
import java.util.*;
import java.text.MessageFormat;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
/**
* @author Vivek Pandey
*/
public class WsimportTool {
private static final String WSIMPORT = "wsimport";
private final PrintStream out;
private final Container container;
/**
* Wsimport specific options
*/
protected WsimportOptions options = new WsimportOptions();
public WsimportTool(OutputStream out) {
this(out, null);
}
public WsimportTool(OutputStream logStream, Container container) {
this.out = (logStream instanceof PrintStream)?(PrintStream)logStream:new PrintStream(logStream);
this.container = container;
}
protected class Listener extends WsimportListener {
ConsoleErrorReporter cer = new ConsoleErrorReporter(out == null ? new PrintStream(new NullStream()) : out);
@Override
public void generatedFile(String fileName) {
message(fileName);
}
@Override
public void message(String msg) {
out.println(msg);
}
@Override
public void error(SAXParseException exception) {
cer.error(exception);
}
@Override
public void fatalError(SAXParseException exception) {
cer.fatalError(exception);
}
@Override
public void warning(SAXParseException exception) {
cer.warning(exception);
}
@Override
public void debug(SAXParseException exception) {
cer.debug(exception);
}
@Override
public void info(SAXParseException exception) {
cer.info(exception);
}
public void enableDebugging(){
cer.enableDebugging();
}
}
protected class Receiver extends ErrorReceiverFilter {
private Listener listener;
public Receiver(Listener listener) {
super(listener);
this.listener = listener;
}
@Override
public void info(SAXParseException exception) {
if (options.verbose)
super.info(exception);
}
@Override
public void warning(SAXParseException exception) {
if (!options.quiet)
super.warning(exception);
}
@Override
public void pollAbort() throws AbortException {
if (listener.isCanceled())
throw new AbortException();
}
@Override
public void debug(SAXParseException exception){
if(options.debugMode){
listener.debug(exception);
}
}
}
public boolean run(String[] args) {
Listener listener = new Listener();
Receiver receiver = new Receiver(listener);
return run(args, listener, receiver);
}
protected boolean run(String[] args, Listener listener,
Receiver receiver) {
for (String arg : args) {
if (arg.equals("-version")) {
listener.message(
WscompileMessages.WSIMPORT_VERSION(ToolVersion.VERSION.MAJOR_VERSION));
return true;
}
if (arg.equals("-fullversion")) {
listener.message(
WscompileMessages.WSIMPORT_FULLVERSION(ToolVersion.VERSION.toString()));
return true;
}
}
try {
parseArguments(args, listener, receiver);
try {
Model wsdlModel = buildWsdlModel(listener, receiver);
if (wsdlModel == null)
return false;
if (!generateCode(listener, receiver, wsdlModel, true))
return false;
/* Not so fast!
} catch(AbortException e){
//error might have been reported
*
*/
}catch (IOException e) {
receiver.error(e);
return false;
}catch (XMLStreamException e) {
receiver.error(e);
return false;
}
if (!options.nocompile){
if(!compileGeneratedClasses(receiver, listener)){
listener.message(WscompileMessages.WSCOMPILE_COMPILATION_FAILED());
return false;
}
}
try {
if (options.clientjar != null) {
//add all the generated class files to the list of generated files
addClassesToGeneratedFiles();
jarArtifacts(listener);
}
} catch (IOException e) {
receiver.error(e);
return false;
}
} catch (Options.WeAreDone done) {
usage(done.getOptions());
} catch (BadCommandLineException e) {
if (e.getMessage() != null) {
System.out.println(e.getMessage());
System.out.println();
}
usage(e.getOptions());
return false;
} finally{
deleteGeneratedFiles();
if (!options.disableAuthenticator) {
DefaultAuthenticator.reset();
}
}
if(receiver.hadError()) {
return false;
}
return true;
}
private void deleteGeneratedFiles() {
Set<File> trackedRootPackages = new HashSet<File>();
if (options.clientjar != null) {
//remove all non-java artifacts as they will packaged in jar.
Iterable<File> generatedFiles = options.getGeneratedFiles();
synchronized (generatedFiles) {
for (File file : generatedFiles) {
if (!file.getName().endsWith(".java")) {
boolean deleted = file.delete();
if (options.verbose && !deleted) {
System.out.println(MessageFormat.format("{0} could not be deleted.", file));
}
trackedRootPackages.add(file.getParentFile());
}
}
}
//remove empty package dirs
for(File pkg:trackedRootPackages) {
while(pkg.list() != null && pkg.list().length ==0 && !pkg.equals(options.destDir)) {
File parentPkg = pkg.getParentFile();
boolean deleted = pkg.delete();
if (options.verbose && !deleted) {
System.out.println(MessageFormat.format("{0} could not be deleted.", pkg));
}
pkg = parentPkg;
}
}
}
if(!options.keep) {
options.removeGeneratedFiles();
}
}
private void addClassesToGeneratedFiles() throws IOException {
Iterable<File> generatedFiles = options.getGeneratedFiles();
final List<File> trackedClassFiles = new ArrayList<File>();
for(File f: generatedFiles) {
if(f.getName().endsWith(".java")) {
String relativeDir = DirectoryUtil.getRelativePathfromCommonBase(f.getParentFile(),options.sourceDir);
final String className = f.getName().substring(0,f.getName().indexOf(".java"));
File classDir = new File(options.destDir,relativeDir);
if(classDir.exists()) {
classDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.equals(className+".class") || (name.startsWith(className+"$") && name.endsWith(".class"))) {
trackedClassFiles.add(new File(dir,name));
return true;
}
return false;
}
});
}
}
}
for(File f: trackedClassFiles) {
options.addGeneratedFile(f);
}
}
private void jarArtifacts(WsimportListener listener) throws IOException {
File zipFile = new File(options.clientjar);
if(!zipFile.isAbsolute()) {
zipFile = new File(options.destDir, options.clientjar);
}
FileOutputStream fos;
if (!options.quiet) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVING_ARTIFACTS(zipFile));
}
BufferedInputStream bis = null;
FileInputStream fi = null;
fos = new FileOutputStream(zipFile);
JarOutputStream jos = new JarOutputStream(fos);
try {
String base = options.destDir.getCanonicalPath();
for(File f: options.getGeneratedFiles()) {
//exclude packaging the java files in the jar
if(f.getName().endsWith(".java")) {
continue;
}
if(options.verbose) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVE_ARTIFACT(f, options.clientjar));
}
String entry = f.getCanonicalPath().substring(base.length()+1).replace(File.separatorChar, '/');
fi = new FileInputStream(f);
bis = new BufferedInputStream(fi);
JarEntry jarEntry = new JarEntry(entry);
jos.putNextEntry(jarEntry);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = bis.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
}
} finally {
try {
if (bis != null) {
bis.close();
}
} finally {
if (jos != null) {
jos.close();
}
if (fi != null) {
fi.close();
}
}
}
}
protected void parseArguments(String[] args, Listener listener,
Receiver receiver) throws BadCommandLineException {
options.parseArguments(args);
options.validate();
if (options.debugMode)
listener.enableDebugging();
options.parseBindings(receiver);
}
protected Model buildWsdlModel(Listener listener, final Receiver receiver)
throws BadCommandLineException, XMLStreamException, IOException {
//set auth info
//if(options.authFile != null)
if (!options.disableAuthenticator) {
class AuthListener implements DefaultAuthenticator.Receiver {
private final boolean isFatal;
AuthListener(boolean isFatal) {
this.isFatal = isFatal;
}
@Override
public void onParsingError(String text, Locator loc) {
error(new SAXParseException(WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(text), loc));
}
@Override
public void onError(Exception e, Locator loc) {
if (e instanceof FileNotFoundException) {
error(new SAXParseException(WscompileMessages.WSIMPORT_AUTH_FILE_NOT_FOUND(
loc.getSystemId(), WsimportOptions.defaultAuthfile), null));
} else {
error(new SAXParseException(WscompileMessages.WSIMPORT_FAILED_TO_PARSE(loc.getSystemId(),e.getMessage()), loc));
}
}
private void error(SAXParseException e) {
if (isFatal) {
receiver.error(e);
} else {
receiver.debug(e);
}
}
}
DefaultAuthenticator da = DefaultAuthenticator.getAuthenticator();
if (options.proxyAuth != null) {
da.setProxyAuth(options.proxyAuth);
}
if (options.authFile != null) {
da.setAuth(options.authFile, new AuthListener(true));
} else {
da.setAuth(new File(WsimportOptions.defaultAuthfile), new AuthListener(false));
}
}
if (!options.quiet) {
listener.message(WscompileMessages.WSIMPORT_PARSING_WSDL());
}
MetadataFinder forest = new MetadataFinder(new WSDLInternalizationLogic(), options, receiver);
forest.parseWSDL();
if (forest.isMexMetadata)
receiver.reset();
WSDLModeler wsdlModeler = new WSDLModeler(options, receiver,forest);
Model wsdlModel = wsdlModeler.buildModel();
if (wsdlModel == null) {
listener.message(WsdlMessages.PARSING_PARSE_FAILED());
}
if(options.clientjar != null) {
if( !options.quiet )
listener.message(WscompileMessages.WSIMPORT_FETCHING_METADATA());
options.wsdlLocation = new WSDLFetcher(options,listener).fetchWsdls(forest);
}
return wsdlModel;
}
protected boolean generateCode(Listener listener, Receiver receiver,
Model wsdlModel, boolean generateService)
throws IOException {
//generated code
if( !options.quiet )
listener.message(WscompileMessages.WSIMPORT_GENERATING_CODE());
TJavaGeneratorExtension[] genExtn = ServiceFinder.find(TJavaGeneratorExtension.class).toArray();
CustomExceptionGenerator.generate(wsdlModel, options, receiver);
SeiGenerator.generate(wsdlModel, options, receiver, genExtn);
if(receiver.hadError()){
throw new AbortException();
}
if (generateService)
{
ServiceGenerator.generate(wsdlModel, options, receiver);
}
for (GeneratorBase g : ServiceFinder.find(GeneratorBase.class)) {
g.init(wsdlModel, options, receiver);
g.doGeneration();
}
List<String> implFiles = null;
if (options.isGenerateJWS) {
implFiles = JwsImplGenerator.generate(wsdlModel, options, receiver);
}
for (Plugin plugin: options.activePlugins) {
try {
plugin.run(wsdlModel, options, receiver);
} catch (SAXException sex) {
// fatal error. error should have been reported
return false;
}
}
CodeWriter cw;
if (options.filer != null) {
cw = new FilerCodeWriter(options.sourceDir, options);
} else {
cw = new WSCodeWriter(options.sourceDir, options);
}
if (options.verbose)
cw = new ProgressCodeWriter(cw, out);
options.getCodeModel().build(cw);
if (options.isGenerateJWS) {
//move Impl files to implDestDir
return JwsImplGenerator.moveToImplDestDir(implFiles, options, receiver);
}
return true;
}
public void setEntityResolver(EntityResolver resolver){
this.options.entityResolver = resolver;
}
/*
* To take care of JDK6-JDK6u3, where 2.1 API classes are not there
*/
private static boolean useBootClasspath(Class clazz) {
try {
ParallelWorldClassLoader.toJarUrl(clazz.getResource('/'+clazz.getName().replace('.','/')+".class"));
return true;
} catch(Exception e) {
return false;
}
}
protected boolean compileGeneratedClasses(ErrorReceiver receiver, WsimportListener listener){
List<String> sourceFiles = new ArrayList<String>();
for (File f : options.getGeneratedFiles()) {
if (f.exists() && f.getName().endsWith(".java")) {
sourceFiles.add(f.getAbsolutePath());
}
}
if (sourceFiles.size() > 0) {
String classDir = options.destDir.getAbsolutePath();
String classpathString = createClasspathString();
boolean bootCP = useBootClasspath(EndpointContext.class) || useBootClasspath(JAXBPermission.class);
List<String> args = new ArrayList<String>();
args.add("-d");
args.add(classDir);
args.add("-classpath");
args.add(classpathString);
//javac is not working in osgi as the url starts with a bundle
if (bootCP) {
args.add("-Xbootclasspath/p:"
+ JavaCompilerHelper.getJarFile(EndpointContext.class)
+ File.pathSeparator
+ JavaCompilerHelper.getJarFile(JAXBPermission.class));
}
if (options.debug) {
args.add("-g");
}
if (options.encoding != null) {
args.add("-encoding");
args.add(options.encoding);
}
if (options.javacOptions != null) {
args.addAll(options.getJavacOptions(args, listener));
}
for (int i = 0; i < sourceFiles.size(); ++i) {
args.add(sourceFiles.get(i));
}
listener.message(WscompileMessages.WSIMPORT_COMPILING_CODE());
if(options.verbose){
StringBuilder argstr = new StringBuilder();
for(String arg:args){
argstr.append(arg).append(" ");
}
listener.message("javac "+ argstr.toString());
}
return JavaCompilerHelper.compile(args.toArray(new String[args.size()]), out, receiver);
}
//there are no files to compile, so return true?
return true;
}
private String createClasspathString() {
StringBuilder classpathStr = new StringBuilder(System.getProperty("java.class.path"));
for(String s: options.cmdlineJars) {
classpathStr.append(File.pathSeparator);
classpathStr.append(new File(s).toString());
}
return classpathStr.toString();
}
protected void usage(Options options) {
System.out.println(WscompileMessages.WSIMPORT_HELP(WSIMPORT));
System.out.println(WscompileMessages.WSIMPORT_USAGE_EXTENSIONS());
System.out.println(WscompileMessages.WSIMPORT_USAGE_EXAMPLES());
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wscompile.plugin.at_generated;
import com.sun.codemodel.internal.*;
import com.sun.tools.internal.ws.ToolVersion;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.Plugin;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wscompile.WsimportTool;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.xml.sax.SAXException;
/**
* {@link Plugin} that marks the generated code by using JSR-250's '@Generated'.
* It is based on a similar plugin in JAXB RI.
*
* @author Lukas Jungmann
* @since 2.2.6
*/
public final class PluginImpl extends Plugin {
private JClass annotation;
// cache the timestamp so that all the @Generated annotations match
private String date = null;
@Override
public String getOptionName() {
return "mark-generated";
}
@Override
public String getUsage() {
return " -mark-generated : mark the generated code as @javax.annotation.Generated";
}
@Override
public boolean run(Model model, WsimportOptions wo, ErrorReceiver er) throws SAXException {
JCodeModel cm = wo.getCodeModel();
// we want this to work without requiring JSR-250 jar.
annotation = cm.ref("javax.annotation.Generated");
for (Iterator<JPackage> i = cm.packages(); i.hasNext();) {
for (Iterator<JDefinedClass> j = i.next().classes(); j.hasNext();) {
annotate(j.next());
}
}
return true;
}
private void annotate(JAnnotatable m) {
m.annotate(annotation)
.param("value", WsimportTool.class.getName())
.param("date", getISO8601Date())
.param("comments", ToolVersion.VERSION.BUILD_VERSION);
}
/**
* calculate the date value in ISO8601 format for the @Generated annotation
* @return the date value
*/
private String getISO8601Date() {
if(date==null) {
StringBuilder tstamp = new StringBuilder();
tstamp.append((new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ")).format(new Date()));
// hack to get ISO 8601 style timezone - is there a better way that doesn't require
// a bunch of timezone offset calculations?
tstamp.insert(tstamp.length()-2, ':');
date = tstamp.toString();
}
return date;
}
}