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,55 @@
/*
* 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.processor;
import com.sun.xml.internal.ws.util.exception.JAXWSExceptionBase;
/**
* ProcessorException represents an exception that occurred while processing
* a web service.
*
* @see JAXWSExceptionBase
*
* @author WS Development Team
*/
public class ProcessorException extends JAXWSExceptionBase {
public ProcessorException(String key, Object... args) {
super(key, args);
}
public ProcessorException(String msg){
super(msg);
}
public ProcessorException(Throwable throwable) {
super(throwable);
}
public String getDefaultResourceBundleName() {
return "com.sun.tools.internal.ws.resources.processor";
}
}

View File

@@ -0,0 +1,160 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.ClassType;
import com.sun.codemodel.internal.JAnnotationUse;
import com.sun.codemodel.internal.JBlock;
import com.sun.codemodel.internal.JClass;
import com.sun.codemodel.internal.JClassAlreadyExistsException;
import com.sun.codemodel.internal.JDefinedClass;
import com.sun.codemodel.internal.JDocComment;
import com.sun.codemodel.internal.JExpr;
import com.sun.codemodel.internal.JFieldRef;
import com.sun.codemodel.internal.JFieldVar;
import com.sun.codemodel.internal.JMethod;
import com.sun.codemodel.internal.JMod;
import com.sun.codemodel.internal.JType;
import com.sun.codemodel.internal.JVar;
import com.sun.tools.internal.ws.processor.model.Fault;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import javax.xml.ws.WebFault;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author WS Development Team
*/
public class CustomExceptionGenerator extends GeneratorBase {
private Map<String, JClass> faults = new HashMap<String, JClass>();
public static void generate(Model model,
WsimportOptions options,
ErrorReceiver receiver){
CustomExceptionGenerator exceptionGen = new CustomExceptionGenerator();
exceptionGen.init(model, options, receiver);
exceptionGen.doGeneration();
}
public GeneratorBase getGenerator(Model model, WsimportOptions options, ErrorReceiver receiver) {
GeneratorBase g = new CustomExceptionGenerator();
g.init(model, options, receiver);
return g;
}
@Override
public void visit(Fault fault) throws Exception {
if (isRegistered(fault))
return;
registerFault(fault);
}
private boolean isRegistered(Fault fault) {
if(faults.keySet().contains(fault.getJavaException().getName())){
fault.setExceptionClass(faults.get(fault.getJavaException().getName()));
return true;
}
return false;
}
private void registerFault(Fault fault) {
try {
write(fault);
faults.put(fault.getJavaException().getName(), fault.getExceptionClass());
} catch (JClassAlreadyExistsException e) {
throw new GeneratorException("generator.nestedGeneratorError",e);
}
}
private void write(Fault fault) throws JClassAlreadyExistsException {
String className = Names.customExceptionClassName(fault);
JDefinedClass cls = cm._class(className, ClassType.CLASS);
JDocComment comment = cls.javadoc();
if(fault.getJavaDoc() != null){
comment.add(fault.getJavaDoc());
comment.add("\n\n");
}
for (String doc : getJAXWSClassComment()) {
comment.add(doc);
}
cls._extends(java.lang.Exception.class);
//@WebFault
JAnnotationUse faultAnn = cls.annotate(WebFault.class);
faultAnn.param("name", fault.getBlock().getName().getLocalPart());
faultAnn.param("targetNamespace", fault.getBlock().getName().getNamespaceURI());
JType faultBean = fault.getBlock().getType().getJavaType().getType().getType();
//faultInfo filed
JFieldVar fi = cls.field(JMod.PRIVATE, faultBean, "faultInfo");
//add jaxb annotations
fault.getBlock().getType().getJavaType().getType().annotate(fi);
fi.javadoc().add("Java type that goes as soapenv:Fault detail element.");
JFieldRef fr = JExpr.ref(JExpr._this(), fi);
//Constructor
JMethod constrc1 = cls.constructor(JMod.PUBLIC);
JVar var1 = constrc1.param(String.class, "message");
JVar var2 = constrc1.param(faultBean, "faultInfo");
constrc1.javadoc().addParam(var1);
constrc1.javadoc().addParam(var2);
JBlock cb1 = constrc1.body();
cb1.invoke("super").arg(var1);
cb1.assign(fr, var2);
//constructor with Throwable
JMethod constrc2 = cls.constructor(JMod.PUBLIC);
var1 = constrc2.param(String.class, "message");
var2 = constrc2.param(faultBean, "faultInfo");
JVar var3 = constrc2.param(Throwable.class, "cause");
constrc2.javadoc().addParam(var1);
constrc2.javadoc().addParam(var2);
constrc2.javadoc().addParam(var3);
JBlock cb2 = constrc2.body();
cb2.invoke("super").arg(var1).arg(var3);
cb2.assign(fr, var2);
//getFaultInfo() method
JMethod fim = cls.method(JMod.PUBLIC, faultBean, "getFaultInfo");
fim.javadoc().addReturn().add("returns fault bean: "+faultBean.fullName());
JBlock fib = fim.body();
fib._return(fi);
fault.setExceptionClass(cls);
}
}

View File

@@ -0,0 +1,244 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.ClassType;
import com.sun.codemodel.internal.JAnnotationUse;
import com.sun.codemodel.internal.JClassAlreadyExistsException;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.codemodel.internal.JDefinedClass;
import com.sun.tools.internal.ws.ToolVersion;
import com.sun.tools.internal.ws.processor.model.Block;
import com.sun.tools.internal.ws.processor.model.Fault;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.processor.model.ModelVisitor;
import com.sun.tools.internal.ws.processor.model.Operation;
import com.sun.tools.internal.ws.processor.model.Parameter;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.processor.model.Request;
import com.sun.tools.internal.ws.processor.model.Response;
import com.sun.tools.internal.ws.processor.model.Service;
import com.sun.tools.internal.ws.processor.util.DirectoryUtil;
import com.sun.tools.internal.ws.processor.util.IndentingWriter;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.xml.internal.ws.util.xml.XmlUtil;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.jws.HandlerChain;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.processing.Filer;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
public abstract class GeneratorBase implements ModelVisitor {
private File destDir;
private String targetVersion;
protected boolean donotOverride;
protected JCodeModel cm;
protected Model model;
protected String wsdlLocation;
protected ErrorReceiver receiver;
protected WsimportOptions options;
protected GeneratorBase() {
}
public void init(Model model, WsimportOptions options, ErrorReceiver receiver){
this.model = model;
this.options = options;
this.destDir = options.destDir;
this.receiver = receiver;
this.wsdlLocation = options.wsdlLocation;
this.targetVersion = options.target.getVersion();
this.cm = options.getCodeModel();
}
public void doGeneration() {
try {
model.accept(this);
} catch (Exception e) {
receiver.error(e);
}
}
@Override
public void visit(Model model) throws Exception {
for (Service service : model.getServices()) {
service.accept(this);
}
}
@Override
public void visit(Service service) throws Exception {
for (Port port : service.getPorts()) {
port.accept(this);
}
}
@Override
public void visit(Port port) throws Exception {
for (Operation operation : port.getOperations()) {
operation.accept(this);
}
}
@Override
public void visit(Operation operation) throws Exception {
operation.getRequest().accept(this);
if (operation.getResponse() != null) {
operation.getResponse().accept(this);
}
Iterator faults = operation.getFaultsSet().iterator();
if (faults != null) {
Fault fault;
while (faults.hasNext()) {
fault = (Fault) faults.next();
fault.accept(this);
}
}
}
@Override
public void visit(Parameter param) throws Exception {}
@Override
public void visit(Block block) throws Exception {}
@Override
public void visit(Response response) throws Exception {}
@Override
public void visit(Request request) throws Exception {}
@Override
public void visit(Fault fault) throws Exception {}
public List<String> getJAXWSClassComment(){
return getJAXWSClassComment(targetVersion);
}
public static List<String> getJAXWSClassComment(String targetVersion) {
List<String> comments = new ArrayList<String>();
comments.add("This class was generated by the JAX-WS RI.\n");
comments.add(ToolVersion.VERSION.BUILD_VERSION+"\n");
comments.add("Generated source version: " + targetVersion);
return comments;
}
protected JDefinedClass getClass(String className, ClassType type) throws JClassAlreadyExistsException {
JDefinedClass cls;
try {
cls = cm._class(className, type);
} catch (JClassAlreadyExistsException e){
cls = cm._getClass(className);
if (cls == null) {
throw e;
}
}
return cls;
}
protected void log(String msg) {
if (options.verbose) {
System.out.println(
"["
+ Names.stripQualifier(this.getClass().getName())
+ ": "
+ msg
+ "]");
}
}
protected void writeHandlerConfig(String className, JDefinedClass cls, WsimportOptions options) {
Element e = options.getHandlerChainConfiguration();
if (e == null) {
return;
}
JAnnotationUse handlerChainAnn = cls.annotate(cm.ref(HandlerChain.class));
NodeList nl = e.getElementsByTagNameNS(
"http://java.sun.com/xml/ns/javaee", "handler-chain");
if(nl.getLength() > 0){
String fName = getHandlerConfigFileName(className);
handlerChainAnn.param("file", fName);
generateHandlerChainFile(e, className);
}
}
private String getHandlerConfigFileName(String fullName){
String name = Names.stripQualifier(fullName);
return name+"_handler.xml";
}
private void generateHandlerChainFile(Element hChains, String name) {
Filer filer = options.filer;
try {
IndentingWriter p;
FileObject jfo;
if (filer != null) {
jfo = filer.createResource(StandardLocation.SOURCE_OUTPUT,
Names.getPackageName(name), getHandlerConfigFileName(name));
options.addGeneratedFile(new File(jfo.toUri()));
p = new IndentingWriter(new OutputStreamWriter(jfo.openOutputStream()));
} else { // leave for backw. compatibility now
String hcName = getHandlerConfigFileName(name);
File packageDir = DirectoryUtil.getOutputDirectoryFor(name, destDir);
File hcFile = new File(packageDir, hcName);
options.addGeneratedFile(hcFile);
p = new IndentingWriter(new OutputStreamWriter(new FileOutputStream(hcFile)));
}
Transformer it = XmlUtil.newTransformer();
it.setOutputProperty(OutputKeys.METHOD, "xml");
it.setOutputProperty(OutputKeys.INDENT, "yes");
it.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount",
"2");
it.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
it.transform( new DOMSource(hChains), new StreamResult(p) );
p.close();
} catch (Exception e) {
throw new GeneratorException(
"generator.nestedGeneratorError",
e);
}
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.processor.generator;
/**
* @author WS Development Team
*/
public enum GeneratorConstants {
DOTC("."),
SIG_INNERCLASS("$"),
JAVA_SRC_SUFFIX(".java"),
QNAME_SUFFIX("_QNAME"),
GET("get"),
IS("is"),
RESPONSE("Response"),
FAULT_CLASS_MEMBER_NAME("faultInfo");
private String value;
private GeneratorConstants(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,47 @@
/*
* 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.processor.generator;
import com.sun.tools.internal.ws.processor.ProcessorException;
/**
*
* @author WS Development Team
*/
public class GeneratorException extends ProcessorException {
public GeneratorException(String key, Object... args) {
super(key, args);
}
public GeneratorException(Throwable throwable) {
super(throwable);
}
public String getDefaultResourceBundleName() {
return "com.sun.tools.internal.ws.resources.generator";
}
}

View File

@@ -0,0 +1,80 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.codemodel.internal.JDefinedClass;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.xml.internal.ws.api.SOAPVersion;
/**
* Service Generator Extension for Custom Binding and Transport
*
* @since 2.2.6
* @see JwsImplGenerator
*/
public abstract class GeneratorExtension {
/**
* Derive Binding ID based on transport and SOAP version
* @param transport
* @param soapVersion
* @return BindingID
*/
public String getBindingValue(String transport, SOAPVersion soapVersion) {
return null;
}
/**
* Create annotations in service JWS generated
* @param model
* @param cm
* @param cls
* @param port
*/
public void writeWebServiceAnnotation(Model model, JCodeModel cm, JDefinedClass cls, Port port) {
}
/**
* Allow additional wsimport options
* @param name for instance, "-neoption"
* @return whether the name specifies an option recognized by the extension
*/
public boolean validateOption(String name) {
return false;
}
/**
* Create annotations in service client generated
* @param options
* @param cm
* @param cls
*/
public void writeWebServiceClientAnnotation(WsimportOptions options, JCodeModel cm, JDefinedClass cls) {
}
}

View File

@@ -0,0 +1,67 @@
/*
* 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.processor.generator;
import com.sun.tools.internal.ws.wscompile.Options;
/**
*
* @author WS Development Team
*/
public class GeneratorUtil {
public static boolean classExists(
Options options,
String className) {
try {
// Takes care of inner classes.
getLoadableClassName(className, options.getClassLoader());
return true;
} catch(ClassNotFoundException ce) {
return false;
}
}
private static String getLoadableClassName(
String className,
ClassLoader classLoader)
throws ClassNotFoundException {
try {
Class.forName(className, true, classLoader);
} catch (ClassNotFoundException e) {
int idx = className.lastIndexOf(GeneratorConstants.DOTC.getValue());
if (idx > -1) {
String tmp = className.substring(0, idx) + GeneratorConstants.SIG_INNERCLASS.getValue();
tmp += className.substring(idx + 1);
return getLoadableClassName(tmp, classLoader);
}
throw e;
}
return className;
}
}

View File

@@ -0,0 +1,48 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.JMethod;
import com.sun.tools.internal.ws.api.TJavaGeneratorExtension;
import com.sun.tools.internal.ws.api.wsdl.TWSDLOperation;
/**
* @author Arun Gupta
*/
public final class JavaGeneratorExtensionFacade extends TJavaGeneratorExtension {
private final TJavaGeneratorExtension[] extensions;
JavaGeneratorExtensionFacade(TJavaGeneratorExtension... extensions) {
assert extensions != null;
this.extensions = extensions;
}
public void writeMethodAnnotations(TWSDLOperation wsdlOperation, JMethod jMethod) {
for (TJavaGeneratorExtension e : extensions) {
e.writeMethodAnnotations(wsdlOperation, jMethod);
}
}
}

View File

@@ -0,0 +1,582 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.*;
import com.sun.tools.internal.ws.processor.model.*;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.processor.model.java.JavaMethod;
import com.sun.tools.internal.ws.processor.model.java.JavaParameter;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
import com.sun.tools.internal.ws.wsdl.document.Definitions;
import com.sun.tools.internal.ws.wsdl.document.Binding;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAP12Binding;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPBinding;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPConstants;
import com.sun.tools.internal.ws.api.wsdl.TWSDLExtension;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.processor.model.ModelProperties;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.codemodel.internal.JClassAlreadyExistsException;
import com.sun.xml.internal.ws.api.SOAPVersion;
import com.sun.xml.internal.ws.util.ServiceFinder;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
/**
* Generator for placeholder JWS implementations
*
* @since 2.2.6
*/
public final class JwsImplGenerator extends GeneratorBase {
private static final Map<String, String> TRANSLATION_MAP = new HashMap<String, String>(
1);
static
{
TRANSLATION_MAP.put(SOAPConstants.URI_SOAP_TRANSPORT_HTTP,
javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING);
}
// save the generated impl files' info
private final List<String> implFiles = new ArrayList<String>();
public static List<String> generate(Model model, WsimportOptions options,
ErrorReceiver receiver) {
// options check
// Generate it according the implDestDir option
if (options.implDestDir == null)
return null;
JwsImplGenerator jwsImplGenerator = new JwsImplGenerator();
jwsImplGenerator.init(model, options, receiver);
jwsImplGenerator.doGeneration();
// print a warning message while implFiles.size() is zero
if (jwsImplGenerator.implFiles.isEmpty()) {
StringBuilder msg = new StringBuilder();
if (options.implServiceName != null)
msg.append("serviceName=[").append(options.implServiceName).append("] ");
if (options.implPortName != null)
msg.append("portName=[").append(options.implPortName).append("] ");
if (msg.length() > 0)
msg.append(", Not found in wsdl file.\n");
msg.append("No impl files generated!");
receiver.warning(null, msg.toString());
}
return jwsImplGenerator.implFiles;
}
/**
* Move impl files to implDestDir
*/
public static boolean moveToImplDestDir(List<String> gImplFiles,
WsimportOptions options, ErrorReceiver receiver) {
if (options.implDestDir == null || gImplFiles == null
|| gImplFiles.isEmpty())
return true;
List<ImplFile> generatedImplFiles = ImplFile.toImplFiles(gImplFiles);
try {
File implDestDir = makePackageDir(options);
File movedF;
File f;
for (ImplFile implF : generatedImplFiles) {
movedF = findFile(options, implF.qualifiedName);
if (movedF == null) {
// should never happen
receiver.warning(null, "Class " + implF.qualifiedName
+ " is not generated. Not moving.");
return false;
}
f = new File(implDestDir, implF.name);
if (!movedF.equals(f)) { //bug 10102169
if (f.exists())
{
if (!f.delete()){
receiver.error("Class " + implF.qualifiedName
+ " has existed in destImplDir, and it "
+ "can not be written!", null);
}
}
if(!movedF.renameTo(f))
{
throw new Exception();
}
}
}
} catch (Exception e) {
receiver.error("Moving WebService Impl files failed!", e);
return false;
}
return true;
}
private JwsImplGenerator() {
donotOverride = true;
}
@Override
public void visit(Service service) {
QName serviceName = service.getName();
// process the ordered service only if it is defined
if (options.implServiceName != null
&& !equalsNSOptional(options.implServiceName, serviceName))
return;
for (Port port : service.getPorts()) {
if (port.isProvider()) {
continue; // Not generating for Provider based endpoint
}
// Generate the impl class name according to
// Xpath(/definitions/service/port[@name]);
QName portName = port.getName();
// process the ordered port only if it is defined
if (options.implPortName != null
&& !equalsNSOptional(options.implPortName, portName))
continue;
String simpleClassName = serviceName.getLocalPart() + "_"
+ portName.getLocalPart() + "Impl";
String className = makePackageQualified(simpleClassName);
implFiles.add(className);
if (donotOverride && GeneratorUtil.classExists(options, className)) {
log("Class " + className + " exists. Not overriding.");
return;
}
JDefinedClass cls = null;
try {
cls = getClass(className, ClassType.CLASS);
} catch (JClassAlreadyExistsException e) {
log("Class " + className
+ " generates failed. JClassAlreadyExistsException[" + className
+ "].");
return;
}
// Each serviceImpl will implements one port interface
JavaInterface portIntf = port.getJavaInterface();
String portClassName = Names.customJavaTypeClassName(portIntf);
JDefinedClass portCls = null;
try {
portCls = getClass(portClassName, ClassType.INTERFACE);
} catch (JClassAlreadyExistsException e) {
log("Class " + className
+ " generates failed. JClassAlreadyExistsException["
+ portClassName + "].");
return;
}
cls._implements(portCls);
// create a default constructor
cls.constructor(JMod.PUBLIC);
// write class comment - JAXWS warning
JDocComment comment = cls.javadoc();
if (service.getJavaDoc() != null) {
comment.add(service.getJavaDoc());
comment.add("\n\n");
}
for (String doc : getJAXWSClassComment()) {
comment.add(doc);
}
// @WebService
JAnnotationUse webServiceAnn = cls.annotate(cm.ref(WebService.class));
writeWebServiceAnnotation(service, port, webServiceAnn);
// @BindingType
JAnnotationUse bindingTypeAnn = cls.annotate(cm.ref(BindingType.class));
writeBindingTypeAnnotation(port, bindingTypeAnn);
// extra annotation
for( GeneratorExtension f : ServiceFinder.find(GeneratorExtension.class) ) {
f.writeWebServiceAnnotation(model, cm, cls, port);
}
// WebMethods
for (Operation operation : port.getOperations()) {
JavaMethod method = operation.getJavaMethod();
// @WebMethod
JMethod m;
JDocComment methodDoc;
String methodJavaDoc = operation.getJavaDoc();
if (method.getReturnType().getName().equals("void")) {
m = cls.method(JMod.PUBLIC, void.class, method.getName());
methodDoc = m.javadoc();
} else {
JAXBTypeAndAnnotation retType = method.getReturnType().getType();
m = cls.method(JMod.PUBLIC, retType.getType(), method.getName());
retType.annotate(m);
methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns " + retType.getName());
}
if (methodJavaDoc != null)
methodDoc.add(methodJavaDoc);
JClass holder = cm.ref(Holder.class);
for (JavaParameter parameter : method.getParametersList()) {
JVar var;
JAXBTypeAndAnnotation paramType = parameter.getType().getType();
if (parameter.isHolder()) {
var = m.param(holder.narrow(paramType.getType().boxify()),
parameter.getName());
} else {
var = m.param(paramType.getType(), parameter.getName());
}
methodDoc.addParam(var);
}
com.sun.tools.internal.ws.wsdl.document.Operation wsdlOp = operation
.getWSDLPortTypeOperation();
for (Fault fault : operation.getFaultsSet()) {
m._throws(fault.getExceptionClass());
methodDoc.addThrows(fault.getExceptionClass());
wsdlOp.putFault(fault.getWsdlFaultName(), fault.getExceptionClass());
}
m.body().block().directStatement("//replace with your impl here");
m.body().block().directStatement(
getReturnString(method.getReturnType().getName()));
}
}
}
/**
* Generate return statement according to return type.
*
* @param type
* The method's return type
* @return The whole return statement
*/
private String getReturnString(String type) {
final String nullReturnStr = "return null;";
// complex type or array
if (type.indexOf('.') > -1 || type.indexOf('[') > -1) {
return nullReturnStr;
}
// primitive type
if (type.equals("void")) {
return "return;";
}
if (type.equals("boolean")) {
return "return false;";
}
if (type.equals("int") || type.equals("byte") || type.equals("short")
|| type.equals("long") || type.equals("double") || type.equals("float")) {
return "return 0;";
}
if (type.equals("char")) {
return "return '0';";
}
return nullReturnStr;
}
/**
*
* @param service
* @param port
* @param webServiceAnn
* @param options
*/
private void writeWebServiceAnnotation(Service service, Port port,
JAnnotationUse webServiceAnn) {
webServiceAnn.param("portName", port.getName().getLocalPart());
webServiceAnn.param("serviceName", service.getName().getLocalPart());
webServiceAnn.param("targetNamespace", service.getName().getNamespaceURI());
webServiceAnn.param("wsdlLocation", wsdlLocation);
webServiceAnn.param("endpointInterface", port.getJavaInterface().getName());
}
//CR373098 To transform the java class name as validate.
private String transToValidJavaIdentifier(String s) {
if (s == null) {
return null;
}
final int len = s.length();
StringBuilder retSB = new StringBuilder();
if (len == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
retSB.append("J"); //update to a default start char
} else {
retSB.append(s.charAt(0));
}
for (int i = 1; i < len; i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i)))
; //delete it if it is illegal //TODO: It might conflict "a-b" vs. "ab"
else {
retSB.append(s.charAt(i));
}
}
return retSB.toString();
}
private String makePackageQualified(String s) {
s = transToValidJavaIdentifier(s);
if (options.defaultPackage != null && !options.defaultPackage.equals("")) {
return options.defaultPackage + "." + s;
} else {
return s;
}
}
/**
* TODO
*
* @param port
* @param bindingTypeAnn
*/
private void writeBindingTypeAnnotation(Port port,
JAnnotationUse bindingTypeAnn) {
QName bName = (QName) port
.getProperty(ModelProperties.PROPERTY_WSDL_BINDING_NAME);
if (bName == null)
return;
String v = getBindingType(bName);
// TODO: How to decide if it is a mtom?
if (v != null) {
// transport = translate(transport);
bindingTypeAnn.param("value", v);
}
}
private String resolveBindingValue(TWSDLExtension wsdlext) {
if (wsdlext.getClass().equals(SOAPBinding.class)) {
SOAPBinding sb = (SOAPBinding) wsdlext;
if(javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_MTOM_BINDING.equals(sb.getTransport()))
return javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_MTOM_BINDING;
else {
for(GeneratorExtension f : ServiceFinder.find(GeneratorExtension.class) ) {
String bindingValue = f.getBindingValue(sb.getTransport(), SOAPVersion.SOAP_11);
if(bindingValue!=null) {
return bindingValue;
}
}
return javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING;
}
}
if (wsdlext.getClass().equals(SOAP12Binding.class)) {
SOAP12Binding sb = (SOAP12Binding) wsdlext;
if(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING.equals(sb.getTransport()))
return javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING;
else {
for(GeneratorExtension f : ServiceFinder.find(GeneratorExtension.class) ) {
String bindingValue = f.getBindingValue(sb.getTransport(), SOAPVersion.SOAP_12);
if(bindingValue!=null) {
return bindingValue;
}
}
return javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING;
}
}
return null;
}
private String getBindingType(QName bName) {
String value = null;
// process the bindings in definitions of model.entity
if (model.getEntity() instanceof Definitions) {
Definitions definitions = (Definitions) model.getEntity();
if (definitions != null) {
Iterator bindings = definitions.bindings();
if (bindings != null) {
while (bindings.hasNext()) {
Binding binding = (Binding) bindings.next();
if (bName.getLocalPart().equals(binding.getName())
&& bName.getNamespaceURI().equals(binding.getNamespaceURI())) {
List<TWSDLExtension> bindextends = (List<TWSDLExtension>) binding
.extensions();
for (TWSDLExtension wsdlext : bindextends) {
value = resolveBindingValue(wsdlext);
if (value != null)
break;
}
break;
}
}
}
}
}
// process the bindings in whole document
if (value == null) {
if (model.getEntity() instanceof Definitions) {
Definitions definitions = (Definitions) model.getEntity();
Binding b = (Binding) definitions.resolveBindings().get(bName);
if (b != null) {
List<TWSDLExtension> bindextends = (List<TWSDLExtension>) b
.extensions();
for (TWSDLExtension wsdlext : bindextends) {
value = resolveBindingValue(wsdlext);
if (value != null)
break;
}
}
}
}
return value;
}
/**
* Since the SOAP 1.1 binding transport URI defined in WSDL 1.1 specification
* is different with the SOAPBinding URI defined by JAX-WS 2.0 specification.
* We must translate the wsdl version into JAX-WS version. If the given
* transport URI is NOT one of the predefined transport URIs, it is returned
* as is.
*
* @param transportURI
* retrieved from WSDL
* @return Standard BindingType URI defined by JAX-WS 2.0 specification.
*/
// private String translate(String transportURI)
// {
// String translatedBindingId = TRANSLATION_MAP.get(transportURI);
// if (translatedBindingId == null)
// translatedBindingId = transportURI;
//
// return translatedBindingId;
// }
/*****************************************************************************
* Inner classes definition
*/
static final class ImplFile {
public String qualifiedName; // package+"."+simpleClassName + ".java"
public String name; // simpleClassName + ".java"
private ImplFile(String qualifiedClassName) {
this.qualifiedName = qualifiedClassName + ".java";
String simpleClassName = qualifiedClassName;
int i = qualifiedClassName.lastIndexOf(".");
if (i != -1)
simpleClassName = qualifiedClassName.substring(i + 1);
this.name = simpleClassName + ".java";
}
public static List<ImplFile> toImplFiles(List<String> qualifiedClassNames) {
List<ImplFile> ret = new ArrayList<ImplFile>();
for (String qualifiedClassName : qualifiedClassNames)
ret.add(new ImplFile(qualifiedClassName));
return ret;
}
}
/*****************************************************************************
* Other utility methods
*/
private static File makePackageDir(WsimportOptions options) {
File ret = null;
if (options.defaultPackage != null && !options.defaultPackage.equals("")) {
String subDir = options.defaultPackage.replace('.', '/');
ret = new File(options.implDestDir, subDir);
} else {
ret = options.implDestDir;
}
boolean created = ret.mkdirs();
if (options.verbose && !created) {
System.out.println(MessageFormat.format("Directory not created: {0}", ret));
}
return ret;
}
private static String getQualifiedFileName(String canonicalBaseDir, File f)
throws java.io.IOException {
String fp = f.getCanonicalPath();
if (fp == null)
return null;
fp = fp.replace(canonicalBaseDir, "");
fp = fp.replace('\\', '.');
fp = fp.replace('/', '.');
if (fp.startsWith("."))
fp = fp.substring(1);
return fp;
}
private static File findFile(WsimportOptions options, String qualifiedFileName)
throws java.io.IOException {
String baseDir = options.sourceDir.getCanonicalPath();
String fp = null;
for (File f : options.getGeneratedFiles()) {
fp = getQualifiedFileName(baseDir, f);
if (qualifiedFileName.equals(fp))
return f;
}
return null;
}
private static boolean equalsNSOptional(String strQName, QName checkQN) {
if (strQName == null)
return false;
strQName = strQName.trim();
QName reqQN = QName.valueOf(strQName);
if (reqQN.getNamespaceURI() == null || reqQN.getNamespaceURI().equals(""))
return reqQN.getLocalPart().equals(checkQN.getLocalPart());
return reqQN.equals(checkQN);
}
}

View File

@@ -0,0 +1,180 @@
/*
* 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.processor.generator;
import com.sun.istack.internal.NotNull;
import com.sun.tools.internal.ws.processor.model.Fault;
import com.sun.tools.internal.ws.processor.model.ModelProperties;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.processor.model.java.JavaStructureMember;
import com.sun.tools.internal.ws.processor.modeler.ModelerConstants;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import com.sun.xml.internal.ws.util.StringUtils;
import javax.xml.namespace.QName;
import java.util.HashMap;
import java.util.Map;
/**
* Names provides utility methods used by other wscompile classes
* for dealing with identifiers.
*
* @author WS Development Team
*/
public final class Names {
private Names() {
}
public static String getPortName(Port port) {
String javaPortName =
(String) port.getProperty(ModelProperties.PROPERTY_JAVA_PORT_NAME);
if (javaPortName != null) {
return javaPortName;
} else {
QName portName =
(QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_PORT_NAME);
if (portName != null) {
return portName.getLocalPart();
} else {
String name = stripQualifier(port.getJavaInterface().getName());
return ClassNameInfo.replaceInnerClassSym(name);
}
}
}
public static String stripQualifier(String name) {
return ClassNameInfo.getName(name);
}
public static String getPackageName(String className) {
String packageName = ClassNameInfo.getQualifier(className);
return packageName != null ? packageName : "";
}
public static String customJavaTypeClassName(JavaInterface intf) {
return intf.getName();
}
public static String customExceptionClassName(Fault fault) {
return fault.getJavaException().getName();
}
public static String getExceptionClassMemberName(){
return GeneratorConstants.FAULT_CLASS_MEMBER_NAME.getValue();
}
public static boolean isJavaReservedWord(String name) {
return RESERVED_WORDS.get(name) != null;
}
/**
* See if its a java keyword name, if so then mangle the name
*/
public static @NotNull String getJavaReserverVarialbeName(@NotNull String name){
return (RESERVED_WORDS.get(name) == null) ? name : RESERVED_WORDS.get(name);
}
/* here we check on wether return values datatype is
boolean. If its boolean, instead of a get method
its set a is<MethodName> to comply with JavaBeans
Pattern spec */
public static String getJavaMemberReadMethod(JavaStructureMember member) {
String return_value;
if (member.getType().getRealName().equals(ModelerConstants.BOOLEAN_CLASSNAME.getValue())) {
return_value = GeneratorConstants.IS.getValue() + StringUtils.capitalize(member.getName());
} else {
return_value = GeneratorConstants.GET.getValue() + StringUtils.capitalize(member.getName());
}
return (return_value);
}
public static String getResponseName(String messageName) {
return messageName + GeneratorConstants.RESPONSE.getValue();
}
private static final Map<String, String> RESERVED_WORDS = new HashMap<String, String>(53);
static {
RESERVED_WORDS.put("abstract", "_abstract");
RESERVED_WORDS.put("assert", "_assert");
RESERVED_WORDS.put("boolean", "_boolean");
RESERVED_WORDS.put("break", "_break");
RESERVED_WORDS.put("byte", "_byte");
RESERVED_WORDS.put("case", "_case");
RESERVED_WORDS.put("catch", "_catch");
RESERVED_WORDS.put("char", "_char");
RESERVED_WORDS.put("class", "_class");
RESERVED_WORDS.put("const", "_const");
RESERVED_WORDS.put("continue", "_continue");
RESERVED_WORDS.put("default", "_default");
RESERVED_WORDS.put("do", "_do");
RESERVED_WORDS.put("double", "_double");
RESERVED_WORDS.put("else", "_else");
RESERVED_WORDS.put("extends", "_extends");
RESERVED_WORDS.put("false", "_false");
RESERVED_WORDS.put("final", "_final");
RESERVED_WORDS.put("finally", "_finally");
RESERVED_WORDS.put("float", "_float");
RESERVED_WORDS.put("for", "_for");
RESERVED_WORDS.put("goto", "_goto");
RESERVED_WORDS.put("if", "_if");
RESERVED_WORDS.put("implements", "_implements");
RESERVED_WORDS.put("import", "_import");
RESERVED_WORDS.put("instanceof", "_instanceof");
RESERVED_WORDS.put("int", "_int");
RESERVED_WORDS.put("interface", "_interface");
RESERVED_WORDS.put("long", "_long");
RESERVED_WORDS.put("native", "_native");
RESERVED_WORDS.put("new", "_new");
RESERVED_WORDS.put("null", "_null");
RESERVED_WORDS.put("package", "_package");
RESERVED_WORDS.put("private", "_private");
RESERVED_WORDS.put("protected", "_protected");
RESERVED_WORDS.put("public", "_public");
RESERVED_WORDS.put("return", "_return");
RESERVED_WORDS.put("short", "_short");
RESERVED_WORDS.put("static", "_static");
RESERVED_WORDS.put("strictfp", "_strictfp");
RESERVED_WORDS.put("super", "_super");
RESERVED_WORDS.put("switch", "_switch");
RESERVED_WORDS.put("synchronized", "_synchronized");
RESERVED_WORDS.put("this", "_this");
RESERVED_WORDS.put("throw", "_throw");
RESERVED_WORDS.put("throws", "_throws");
RESERVED_WORDS.put("transient", "_transient");
RESERVED_WORDS.put("true", "_true");
RESERVED_WORDS.put("try", "_try");
RESERVED_WORDS.put("void", "_void");
RESERVED_WORDS.put("volatile", "_volatile");
RESERVED_WORDS.put("while", "_while");
RESERVED_WORDS.put("enum", "_enum");
}
}

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.processor.generator;
import com.sun.codemodel.internal.*;
import com.sun.tools.internal.ws.api.TJavaGeneratorExtension;
import com.sun.tools.internal.ws.processor.model.*;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.processor.model.java.JavaMethod;
import com.sun.tools.internal.ws.processor.model.java.JavaParameter;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBType;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.Options;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
import com.sun.tools.internal.ws.wsdl.document.PortType;
import com.sun.tools.internal.ws.resources.GeneratorMessages;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Locator;
public class SeiGenerator extends GeneratorBase {
private TJavaGeneratorExtension extension;
private List<TJavaGeneratorExtension> extensionHandlers;
public static void generate(Model model, WsimportOptions options, ErrorReceiver receiver, TJavaGeneratorExtension... extensions){
SeiGenerator seiGenerator = new SeiGenerator();
seiGenerator.init(model, options, receiver, extensions);
seiGenerator.doGeneration();
}
public void init(Model model, WsimportOptions options, ErrorReceiver receiver, TJavaGeneratorExtension... extensions) {
init(model, options, receiver);
extensionHandlers = new ArrayList<TJavaGeneratorExtension>();
// register handlers for default extensions
// 2.2 Spec requires generation of @Action when wsam:Action is explicitly stated in wsdl
if (options.target.isLaterThan(Options.Target.V2_2)) {
register(new W3CAddressingJavaGeneratorExtension());
}
for (TJavaGeneratorExtension j : extensions) {
register(j);
}
this.extension = new JavaGeneratorExtensionFacade(extensionHandlers.toArray(new TJavaGeneratorExtension[extensionHandlers.size()]));
}
private void write(Port port) {
JavaInterface intf = port.getJavaInterface();
String className = Names.customJavaTypeClassName(intf);
if (donotOverride && GeneratorUtil.classExists(options, className)) {
log("Class " + className + " exists. Not overriding.");
return;
}
JDefinedClass cls;
try {
cls = getClass(className, ClassType.INTERFACE);
} catch (JClassAlreadyExistsException e) {
QName portTypeName =
(QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
Locator loc = null;
if(portTypeName != null){
PortType pt = port.portTypes.get(portTypeName);
if (pt!=null) {
loc = pt.getLocator();
}
}
receiver.error(loc, GeneratorMessages.GENERATOR_SEI_CLASS_ALREADY_EXIST(intf.getName(), portTypeName));
return;
}
// If the class has methods it has already been defined
// so skip it.
if (!cls.methods().isEmpty()) {
return;
}
//write class comment - JAXWS warning
JDocComment comment = cls.javadoc();
String ptDoc = intf.getJavaDoc();
if(ptDoc != null){
comment.add(ptDoc);
comment.add("\n\n");
}
for(String doc:getJAXWSClassComment()){
comment.add(doc);
}
//@WebService
JAnnotationUse webServiceAnn = cls.annotate(cm.ref(WebService.class));
writeWebServiceAnnotation(port, webServiceAnn);
//@HandlerChain
writeHandlerConfig(Names.customJavaTypeClassName(port.getJavaInterface()), cls, options);
//@SOAPBinding
writeSOAPBinding(port, cls);
//@XmlSeeAlso
if (options.target.isLaterThan(Options.Target.V2_1)) {
writeXmlSeeAlso(cls);
}
for (Operation operation: port.getOperations()) {
JavaMethod method = operation.getJavaMethod();
//@WebMethod
JMethod m;
JDocComment methodDoc;
String methodJavaDoc = operation.getJavaDoc();
if(method.getReturnType().getName().equals("void")){
m = cls.method(JMod.PUBLIC, void.class, method.getName());
methodDoc = m.javadoc();
}else {
JAXBTypeAndAnnotation retType = method.getReturnType().getType();
m = cls.method(JMod.PUBLIC, retType.getType(), method.getName());
retType.annotate(m);
methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+retType.getName());
}
if (methodJavaDoc != null) {
methodDoc.add(methodJavaDoc);
}
writeWebMethod(operation, m);
JClass holder = cm.ref(Holder.class);
for (JavaParameter parameter: method.getParametersList()) {
JVar var;
JAXBTypeAndAnnotation paramType = parameter.getType().getType();
if (parameter.isHolder()) {
var = m.param(holder.narrow(paramType.getType().boxify()), parameter.getName());
}else{
var = m.param(paramType.getType(), parameter.getName());
}
//annotate parameter with JAXB annotations
paramType.annotate(var);
methodDoc.addParam(var);
JAnnotationUse paramAnn = var.annotate(cm.ref(WebParam.class));
writeWebParam(operation, parameter, paramAnn);
}
com.sun.tools.internal.ws.wsdl.document.Operation wsdlOp = operation.getWSDLPortTypeOperation();
for(Fault fault:operation.getFaultsSet()){
m._throws(fault.getExceptionClass());
methodDoc.addThrows(fault.getExceptionClass());
wsdlOp.putFault(fault.getWsdlFaultName(), fault.getExceptionClass());
}
//It should be the last thing to invoke after JMethod is built completely
extension.writeMethodAnnotations(wsdlOp, m);
}
}
private void writeXmlSeeAlso(JDefinedClass cls) {
if (model.getJAXBModel().getS2JJAXBModel() != null) {
List<JClass> objectFactories = model.getJAXBModel().getS2JJAXBModel().getAllObjectFactories();
//if there are no object facotires, dont generate @XmlSeeAlso
if (objectFactories.isEmpty()) {
return;
}
JAnnotationUse xmlSeeAlso = cls.annotate(cm.ref(XmlSeeAlso.class));
JAnnotationArrayMember paramArray = xmlSeeAlso.paramArray("value");
for (JClass of : objectFactories) {
paramArray = paramArray.param(of);
}
}
}
private void writeWebMethod(Operation operation, JMethod m) {
Response response = operation.getResponse();
JAnnotationUse webMethodAnn = m.annotate(cm.ref(WebMethod.class));
String operationName = (operation instanceof AsyncOperation)?
((AsyncOperation)operation).getNormalOperation().getName().getLocalPart():
operation.getName().getLocalPart();
if(!m.name().equals(operationName)){
webMethodAnn.param("operationName", operationName);
}
if (operation.getSOAPAction() != null && operation.getSOAPAction().length() > 0){
webMethodAnn.param("action", operation.getSOAPAction());
}
if (operation.getResponse() == null){
m.annotate(javax.jws.Oneway.class);
}else if (!operation.getJavaMethod().getReturnType().getName().equals("void") &&
operation.getResponse().getParametersList().size() > 0){
Block block;
String resultName = null;
String nsURI = null;
if (operation.getResponse().getBodyBlocks().hasNext()) {
block = operation.getResponse().getBodyBlocks().next();
resultName = block.getName().getLocalPart();
if(isDocStyle || block.getLocation() == Block.HEADER){
nsURI = block.getName().getNamespaceURI();
}
}
for (Parameter parameter : operation.getResponse().getParametersList()) {
if (parameter.getParameterIndex() == -1) {
if(operation.isWrapped()||!isDocStyle){
if(parameter.getBlock().getLocation() == Block.HEADER){
resultName = parameter.getBlock().getName().getLocalPart();
}else{
resultName = parameter.getName();
}
if (isDocStyle || (parameter.getBlock().getLocation() == Block.HEADER)) {
nsURI = parameter.getType().getName().getNamespaceURI();
}
}else if(isDocStyle){
JAXBType t = (JAXBType)parameter.getType();
resultName = t.getName().getLocalPart();
nsURI = t.getName().getNamespaceURI();
}
if(!(operation instanceof AsyncOperation)){
JAnnotationUse wr = null;
if(!resultName.equals("return")){
wr = m.annotate(javax.jws.WebResult.class);
wr.param("name", resultName);
}
if (nsURI != null || (isDocStyle && operation.isWrapped())) {
if(wr == null) {
wr = m.annotate(javax.jws.WebResult.class);
}
wr.param("targetNamespace", nsURI);
}
//doclit wrapped could have additional headers
if(!(isDocStyle && operation.isWrapped()) ||
(parameter.getBlock().getLocation() == Block.HEADER)){
if (wr == null) {
wr = m.annotate(javax.jws.WebResult.class);
}
wr.param("partName", parameter.getName());
}
if(parameter.getBlock().getLocation() == Block.HEADER){
if (wr == null) {
wr = m.annotate(javax.jws.WebResult.class);
}
wr.param("header",true);
}
}
}
}
}
//DOC/BARE
if (!sameParamStyle) {
if(!operation.isWrapped()) {
JAnnotationUse sb = m.annotate(SOAPBinding.class);
sb.param("parameterStyle", SOAPBinding.ParameterStyle.BARE);
}
}
if (operation.isWrapped() && operation.getStyle().equals(SOAPStyle.DOCUMENT)) {
Block reqBlock = operation.getRequest().getBodyBlocks().next();
JAnnotationUse reqW = m.annotate(javax.xml.ws.RequestWrapper.class);
reqW.param("localName", reqBlock.getName().getLocalPart());
reqW.param("targetNamespace", reqBlock.getName().getNamespaceURI());
reqW.param("className", reqBlock.getType().getJavaType().getName());
if (response != null) {
JAnnotationUse resW = m.annotate(javax.xml.ws.ResponseWrapper.class);
Block resBlock = response.getBodyBlocks().next();
resW.param("localName", resBlock.getName().getLocalPart());
resW.param("targetNamespace", resBlock.getName().getNamespaceURI());
resW.param("className", resBlock.getType().getJavaType().getName());
}
}
}
private boolean isMessageParam(Parameter param, Message message) {
Block block = param.getBlock();
return (message.getBodyBlockCount() > 0 && block.equals(message.getBodyBlocks().next())) ||
(message.getHeaderBlockCount() > 0 &&
block.equals(message.getHeaderBlocks().next()));
}
private boolean isHeaderParam(Parameter param, Message message) {
if (message.getHeaderBlockCount() == 0) {
return false;
}
for (Block headerBlock : message.getHeaderBlocksMap().values()) {
if (param.getBlock().equals(headerBlock)) {
return true;
}
}
return false;
}
private boolean isAttachmentParam(Parameter param, Message message){
if (message.getAttachmentBlockCount() == 0) {
return false;
}
for (Block attBlock : message.getAttachmentBlocksMap().values()) {
if (param.getBlock().equals(attBlock)) {
return true;
}
}
return false;
}
private boolean isUnboundParam(Parameter param, Message message){
if (message.getUnboundBlocksCount() == 0) {
return false;
}
for (Block unboundBlock : message.getUnboundBlocksMap().values()) {
if (param.getBlock().equals(unboundBlock)) {
return true;
}
}
return false;
}
private void writeWebParam(Operation operation, JavaParameter javaParameter, JAnnotationUse paramAnno) {
Parameter param = javaParameter.getParameter();
Request req = operation.getRequest();
Response res = operation.getResponse();
boolean header = isHeaderParam(param, req) ||
(res != null && isHeaderParam(param, res));
String name;
boolean isWrapped = operation.isWrapped();
if ((param.getBlock().getLocation() == Block.HEADER) || (isDocStyle && !isWrapped)) {
name = param.getBlock().getName().getLocalPart();
} else {
name = param.getName();
}
paramAnno.param("name", name);
String ns= null;
if (isDocStyle) {
ns = param.getBlock().getName().getNamespaceURI(); // its bare nsuri
if(isWrapped){
ns = param.getType().getName().getNamespaceURI();
}
}else if(header){
ns = param.getBlock().getName().getNamespaceURI();
}
if (ns != null || (isDocStyle && isWrapped)) {
paramAnno.param("targetNamespace", ns);
}
if (header) {
paramAnno.param("header", true);
}
if (param.isINOUT()){
paramAnno.param("mode", javax.jws.WebParam.Mode.INOUT);
}else if ((res != null) && (isMessageParam(param, res) || isHeaderParam(param, res) || isAttachmentParam(param, res) ||
isUnboundParam(param,res) || param.isOUT())){
paramAnno.param("mode", javax.jws.WebParam.Mode.OUT);
}
//doclit wrapped could have additional headers
if (!(isDocStyle && isWrapped) || header) {
paramAnno.param("partName", javaParameter.getParameter().getName());
}
}
private boolean isDocStyle = true;
private boolean sameParamStyle = true;
private void writeSOAPBinding(Port port, JDefinedClass cls) {
JAnnotationUse soapBindingAnn = null;
isDocStyle = port.getStyle() == null || port.getStyle().equals(SOAPStyle.DOCUMENT);
if(!isDocStyle){
soapBindingAnn = cls.annotate(SOAPBinding.class);
soapBindingAnn.param("style", SOAPBinding.Style.RPC);
port.setWrapped(true);
}
if(isDocStyle){
boolean first = true;
boolean isWrapper = true;
for(Operation operation:port.getOperations()){
if(first){
isWrapper = operation.isWrapped();
first = false;
continue;
}
sameParamStyle = (isWrapper == operation.isWrapped());
if (!sameParamStyle) {
break;
}
}
if (sameParamStyle) {
port.setWrapped(isWrapper);
}
}
if(sameParamStyle && !port.isWrapped()){
if (soapBindingAnn == null) {
soapBindingAnn = cls.annotate(SOAPBinding.class);
}
soapBindingAnn.param("parameterStyle", SOAPBinding.ParameterStyle.BARE);
}
}
private void writeWebServiceAnnotation(Port port, JAnnotationUse wsa) {
QName name = (QName) port.getProperty(ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
wsa.param("name", name.getLocalPart());
wsa.param("targetNamespace", name.getNamespaceURI());
}
@Override
public void visit(Model model) throws Exception {
for(Service s:model.getServices()){
s.accept(this);
}
}
@Override
public void visit(Service service) throws Exception {
String jd = model.getJavaDoc();
if(jd != null){
JPackage pkg = cm._package(options.defaultPackage);
pkg.javadoc().add(jd);
}
for(Port p:service.getPorts()){
visitPort(service, p);
}
}
private void visitPort(Service service, Port port) {
if (port.isProvider()) {
return; // Not generating for Provider based endpoint
}
write(port);
}
private void register(TJavaGeneratorExtension h) {
extensionHandlers.add(h);
}
}

View File

@@ -0,0 +1,422 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.ClassType;
import com.sun.codemodel.internal.JAnnotationUse;
import com.sun.codemodel.internal.JBlock;
import com.sun.codemodel.internal.JCatchBlock;
import com.sun.codemodel.internal.JClass;
import com.sun.codemodel.internal.JClassAlreadyExistsException;
import com.sun.codemodel.internal.JCommentPart;
import com.sun.codemodel.internal.JConditional;
import com.sun.codemodel.internal.JDefinedClass;
import com.sun.codemodel.internal.JDocComment;
import com.sun.codemodel.internal.JExpr;
import com.sun.codemodel.internal.JFieldVar;
import com.sun.codemodel.internal.JInvocation;
import com.sun.codemodel.internal.JMethod;
import com.sun.codemodel.internal.JMod;
import com.sun.codemodel.internal.JTryBlock;
import com.sun.codemodel.internal.JType;
import com.sun.codemodel.internal.JVar;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.processor.model.ModelProperties;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.processor.model.Service;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.resources.GeneratorMessages;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.Options;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wsdl.document.PortType;
import com.sun.xml.internal.ws.spi.db.BindingHelper;
import org.xml.sax.Locator;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.WebServiceException;
import java.net.MalformedURLException;
import java.net.URL;
import com.sun.xml.internal.ws.util.ServiceFinder;
import java.util.Locale;
/**
* @author WS Development Team
* @author Jitendra Kotamraju
*/
public class ServiceGenerator extends GeneratorBase {
public static void generate(Model model, WsimportOptions options, ErrorReceiver receiver) {
ServiceGenerator serviceGenerator = new ServiceGenerator(model, options, receiver);
serviceGenerator.doGeneration();
}
private ServiceGenerator(Model model, WsimportOptions options, ErrorReceiver receiver) {
init(model, options, receiver);
}
@Override
public void visit(Service service) {
JavaInterface intf = service.getJavaInterface();
String className = Names.customJavaTypeClassName(intf);
if (donotOverride && GeneratorUtil.classExists(options, className)) {
log("Class " + className + " exists. Not overriding.");
return;
}
JDefinedClass cls;
try {
cls = getClass(className, ClassType.CLASS);
} catch (JClassAlreadyExistsException e) {
receiver.error(service.getLocator(), GeneratorMessages.GENERATOR_SERVICE_CLASS_ALREADY_EXIST(className, service.getName()));
return;
}
cls._extends(javax.xml.ws.Service.class);
String serviceFieldName = BindingHelper.mangleNameToClassName(service.getName().getLocalPart()).toUpperCase(Locale.ENGLISH);
String wsdlLocationName = serviceFieldName + "_WSDL_LOCATION";
JFieldVar urlField = cls.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, URL.class, wsdlLocationName);
JFieldVar exField = cls.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, WebServiceException.class, serviceFieldName+"_EXCEPTION");
String serviceName = serviceFieldName + "_QNAME";
cls.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, QName.class, serviceName,
JExpr._new(cm.ref(QName.class)).arg(service.getName().getNamespaceURI()).arg(service.getName().getLocalPart()));
JClass qNameCls = cm.ref(QName.class);
JInvocation inv;
inv = JExpr._new(qNameCls);
inv.arg("namespace");
inv.arg("localpart");
if (options.useBaseResourceAndURLToLoadWSDL) {
writeClassLoaderBaseResourceWSDLLocation(className, cls, urlField, exField);
} else if (wsdlLocation.startsWith("http://") || wsdlLocation.startsWith("https://") || wsdlLocation.startsWith("file:/")) {
writeAbsWSDLLocation(cls, urlField, exField);
} else if (wsdlLocation.startsWith("META-INF/")) {
writeClassLoaderResourceWSDLLocation(className, cls, urlField, exField);
} else {
writeResourceWSDLLocation(className, cls, urlField, exField);
}
//write class comment - JAXWS warning
JDocComment comment = cls.javadoc();
if (service.getJavaDoc() != null) {
comment.add(service.getJavaDoc());
comment.add("\n\n");
}
for (String doc : getJAXWSClassComment()) {
comment.add(doc);
}
// Generating constructor
// for e.g: public ExampleService()
JMethod constructor1 = cls.constructor(JMod.PUBLIC);
String constructor1Str = String.format("super(__getWsdlLocation(), %s);", serviceName);
constructor1.body().directStatement(constructor1Str);
// Generating constructor
// for e.g: public ExampleService(WebServiceFeature ... features)
if (options.target.isLaterThan(Options.Target.V2_2)) {
JMethod constructor2 = cls.constructor(JMod.PUBLIC);
constructor2.varParam(WebServiceFeature.class, "features");
String constructor2Str = String.format("super(__getWsdlLocation(), %s, features);", serviceName);
constructor2.body().directStatement(constructor2Str);
}
// Generating constructor
// for e.g: public ExampleService(URL wsdlLocation)
if (options.target.isLaterThan(Options.Target.V2_2)) {
JMethod constructor3 = cls.constructor(JMod.PUBLIC);
constructor3.param(URL.class, "wsdlLocation");
String constructor3Str = String.format("super(wsdlLocation, %s);", serviceName);
constructor3.body().directStatement(constructor3Str);
}
// Generating constructor
// for e.g: public ExampleService(URL wsdlLocation, WebServiceFeature ... features)
if (options.target.isLaterThan(Options.Target.V2_2)) {
JMethod constructor4 = cls.constructor(JMod.PUBLIC);
constructor4.param(URL.class, "wsdlLocation");
constructor4.varParam(WebServiceFeature.class, "features");
String constructor4Str = String.format("super(wsdlLocation, %s, features);", serviceName);
constructor4.body().directStatement(constructor4Str);
}
// Generating constructor
// for e.g: public ExampleService(URL wsdlLocation, QName serviceName)
JMethod constructor5 = cls.constructor(JMod.PUBLIC);
constructor5.param(URL.class, "wsdlLocation");
constructor5.param(QName.class, "serviceName");
constructor5.body().directStatement("super(wsdlLocation, serviceName);");
// Generating constructor
// for e.g: public ExampleService(URL, QName, WebServiceFeature ...)
if (options.target.isLaterThan(Options.Target.V2_2)) {
JMethod constructor6 = cls.constructor(JMod.PUBLIC);
constructor6.param(URL.class, "wsdlLocation");
constructor6.param(QName.class, "serviceName");
constructor6.varParam(WebServiceFeature.class, "features");
constructor6.body().directStatement("super(wsdlLocation, serviceName, features);");
}
//@WebService
JAnnotationUse webServiceClientAnn = cls.annotate(cm.ref(WebServiceClient.class));
writeWebServiceClientAnnotation(service, webServiceClientAnn);
// additional annotations
for (GeneratorExtension f:ServiceFinder.find(GeneratorExtension.class)) {
f.writeWebServiceClientAnnotation(options, cm, cls);
}
//@HandlerChain
writeHandlerConfig(Names.customJavaTypeClassName(service.getJavaInterface()), cls, options);
for (Port port : service.getPorts()) {
if (port.isProvider()) {
continue; // No getXYZPort() for porvider based endpoint
}
//Get the SEI class
JType retType;
try {
retType = getClass(port.getJavaInterface().getName(), ClassType.INTERFACE);
} catch (JClassAlreadyExistsException e) {
QName portTypeName =
(QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
Locator loc = null;
if (portTypeName != null) {
PortType pt = port.portTypes.get(portTypeName);
if (pt != null) {
loc = pt.getLocator();
}
}
receiver.error(loc, GeneratorMessages.GENERATOR_SEI_CLASS_ALREADY_EXIST(port.getJavaInterface().getName(), portTypeName));
return;
}
//write getXyzPort()
writeDefaultGetPort(port, retType, cls);
//write getXyzPort(WebServicesFeature...)
if (options.target.isLaterThan(Options.Target.V2_1)) {
writeGetPort(port, retType, cls);
}
}
writeGetWsdlLocation(cm.ref(URL.class), cls, urlField, exField);
}
private void writeGetPort(Port port, JType retType, JDefinedClass cls) {
JMethod m = cls.method(JMod.PUBLIC, retType, port.getPortGetter());
JDocComment methodDoc = m.javadoc();
if (port.getJavaDoc() != null) {
methodDoc.add(port.getJavaDoc());
}
JCommentPart ret = methodDoc.addReturn();
JCommentPart paramDoc = methodDoc.addParam("features");
paramDoc.append("A list of ");
paramDoc.append("{@link " + WebServiceFeature.class.getName() + "}");
paramDoc.append("to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.");
ret.add("returns " + retType.name());
m.varParam(WebServiceFeature.class, "features");
JBlock body = m.body();
StringBuilder statement = new StringBuilder("return ");
statement.append("super.getPort(new QName(\"").append(port.getName().getNamespaceURI()).append("\", \"").append(port.getName().getLocalPart()).append("\"), ");
statement.append(retType.name());
statement.append(".class, features);");
body.directStatement(statement.toString());
writeWebEndpoint(port, m);
}
/*
Generates the code to create URL for absolute WSDL location
for e.g.:
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://ExampleService.wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
EXAMPLESERVICE_WSDL_LOCATION = url;
EXAMPLESERVICE_EXCEPTION = e;
}
*/
private void writeAbsWSDLLocation(JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JTryBlock tryBlock = staticBlock._try();
tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(wsdlLocation));
JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
catchBlock.param("ex");
catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(JExpr.ref("ex")));
staticBlock.assign(urlField, urlVar);
staticBlock.assign(exField, exVar);
}
/*
Generates the code to create URL for WSDL location as resource
for e.g.:
static {
EXAMPLESERVICE_WSDL_LOCATION = ExampleService.class.getResource(...);
Exception e = null;
if (EXAMPLESERVICE_WSDL_LOCATION == null) {
e = new WebServiceException("...");
}
EXAMPLESERVICE_EXCEPTION = e;
}
*/
private void writeResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
staticBlock.assign(urlField, JExpr.dotclass(cm.ref(className)).invoke("getResource").arg(wsdlLocation));
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JConditional ifBlock = staticBlock._if(urlField.eq(JExpr._null()));
ifBlock._then().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(
"Cannot find "+JExpr.quotify('\'', wsdlLocation)+" wsdl. Place the resource correctly in the classpath."));
staticBlock.assign(exField, exVar);
}
/*
Generates the code to create URL for WSDL location as classloader resource
for e.g.:
static {
EXAMPLESERVICE_WSDL_LOCATION = ExampleService.class.getClassLoader().getResource(...);
Exception e = null;
if (EXAMPLESERVICE_WSDL_LOCATION == null) {
e = new WebServiceException("...");
}
EXAMPLESERVICE_EXCEPTION = e;
}
*/
private void writeClassLoaderResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
staticBlock.assign(urlField, JExpr.dotclass(cm.ref(className)).invoke("getClassLoader").invoke("getResource").arg(wsdlLocation));
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JConditional ifBlock = staticBlock._if(urlField.eq(JExpr._null()));
ifBlock._then().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(
"Cannot find "+JExpr.quotify('\'', wsdlLocation)+" wsdl. Place the resource correctly in the classpath."));
staticBlock.assign(exField, exVar);
}
/*
Generates the code to create URL for WSDL location from classloader base resource
for e.g.:
static {
Exception e = null;
URL url = null;
try {
url = new URL(ExampleService.class.getClassLoader().getResource("."), ...);
} catch (MalformedURLException murl) {
e = new WebServiceException(murl);
}
EXAMPLESERVICE_WSDL_LOCATION = url;
EXAMPLESERVICE_EXCEPTION = e;
}
*/
private void writeClassLoaderBaseResourceWSDLLocation(String className, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JBlock staticBlock = cls.init();
JVar exVar = staticBlock.decl(cm.ref(WebServiceException.class), "e", JExpr._null());
JVar urlVar = staticBlock.decl(cm.ref(URL.class), "url", JExpr._null());
JTryBlock tryBlock = staticBlock._try();
tryBlock.body().assign(urlVar, JExpr._new(cm.ref(URL.class)).arg(JExpr.dotclass(cm.ref(className)).invoke("getResource").arg(".")).arg(wsdlLocation));
JCatchBlock catchBlock = tryBlock._catch(cm.ref(MalformedURLException.class));
JVar murlVar = catchBlock.param("murl");
catchBlock.body().assign(exVar, JExpr._new(cm.ref(WebServiceException.class)).arg(murlVar));
staticBlock.assign(urlField, urlVar);
staticBlock.assign(exField, exVar);
}
/*
Generates code that gives wsdl URL. If there is an exception in
creating the URL, it throws an exception.
for example:
private URL __getWsdlLocation() {
if (EXAMPLESERVICE_EXCEPTION != null) {
throw EXAMPLESERVICE_EXCEPTION;
}
return EXAMPLESERVICE_WSDL_LOCATION;
}
*/
private void writeGetWsdlLocation(JType retType, JDefinedClass cls, JFieldVar urlField, JFieldVar exField) {
JMethod m = cls.method(JMod.PRIVATE|JMod.STATIC , retType, "__getWsdlLocation");
JConditional ifBlock = m.body()._if(exField.ne(JExpr._null()));
ifBlock._then()._throw(exField);
m.body()._return(urlField);
}
private void writeDefaultGetPort(Port port, JType retType, JDefinedClass cls) {
String portGetter = port.getPortGetter();
JMethod m = cls.method(JMod.PUBLIC, retType, portGetter);
JDocComment methodDoc = m.javadoc();
if (port.getJavaDoc() != null) {
methodDoc.add(port.getJavaDoc());
}
JCommentPart ret = methodDoc.addReturn();
ret.add("returns " + retType.name());
JBlock body = m.body();
StringBuilder statement = new StringBuilder("return ");
statement.append("super.getPort(new QName(\"").append(port.getName().getNamespaceURI()).append("\", \"").append(port.getName().getLocalPart()).append("\"), ");
statement.append(retType.name());
statement.append(".class);");
body.directStatement(statement.toString());
writeWebEndpoint(port, m);
}
private void writeWebServiceClientAnnotation(Service service, JAnnotationUse wsa) {
String serviceName = service.getName().getLocalPart();
String serviceNS = service.getName().getNamespaceURI();
wsa.param("name", serviceName);
wsa.param("targetNamespace", serviceNS);
wsa.param("wsdlLocation", wsdlLocation);
}
private void writeWebEndpoint(Port port, JMethod m) {
JAnnotationUse webEndpointAnn = m.annotate(cm.ref(WebEndpoint.class));
webEndpointAnn.param("name", port.getName().getLocalPart());
}
}

View File

@@ -0,0 +1,97 @@
/*
* 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.processor.generator;
import com.sun.codemodel.internal.JAnnotationArrayMember;
import com.sun.codemodel.internal.JAnnotationUse;
import com.sun.codemodel.internal.JClass;
import com.sun.codemodel.internal.JMethod;
import com.sun.tools.internal.ws.api.TJavaGeneratorExtension;
import com.sun.tools.internal.ws.api.wsdl.TWSDLOperation;
import com.sun.tools.internal.ws.wsdl.document.Fault;
import com.sun.tools.internal.ws.wsdl.document.Operation;
import javax.xml.ws.Action;
import javax.xml.ws.FaultAction;
import java.util.Map;
/**
* This Java Generator extension generates @Action annotation on web methods if an explicit wsam:Action value is specified
* in the wsdl definitions.
*
* @author Arun Gupta
*/
public class W3CAddressingJavaGeneratorExtension extends TJavaGeneratorExtension {
@Override
public void writeMethodAnnotations(TWSDLOperation two, JMethod jMethod) {
JAnnotationUse actionAnn = null;
if (!(two instanceof Operation))
return;
Operation o = ((Operation)two);
// explicit input action
if (o.getInput().getAction() != null && !o.getInput().getAction().equals("")) {
// explicitly specified
actionAnn = jMethod.annotate(Action.class);
actionAnn.param("input", o.getInput().getAction());
}
// explicit output action
if (o.getOutput() != null && o.getOutput().getAction() != null && !o.getOutput().getAction().equals("")) {
// explicitly specified
if (actionAnn == null)
actionAnn = jMethod.annotate(Action.class);
actionAnn.param("output", o.getOutput().getAction());
}
// explicit fault action
if (o.getFaults() != null && o.getFaults().size() > 0) {
Map<String, JClass> map = o.getFaults();
JAnnotationArrayMember jam = null;
for (Fault f : o.faults()) {
if (f.getAction() == null)
continue;
if (f.getAction().equals(""))
continue;
if (actionAnn == null) {
actionAnn = jMethod.annotate(Action.class);
}
if (jam == null) {
jam = actionAnn.paramArray("fault");
}
final JAnnotationUse faAnn = jam.annotate(FaultAction.class);
faAnn.param("className", map.get(f.getName()));
faAnn.param("value", f.getAction());
}
}
}
}

View File

@@ -0,0 +1,145 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.processor.model.java.JavaType;
import javax.xml.namespace.QName;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author WS Development Team
*/
public abstract class AbstractType {
protected AbstractType() {}
protected AbstractType(QName name) {
this(name, null, null);
}
protected AbstractType(QName name, String version) {
this(name, null, version);
}
protected AbstractType(QName name, JavaType javaType) {
this(name, javaType, null);
}
protected AbstractType(QName name, JavaType javaType, String version) {
this.name = name;
this.javaType = javaType;
this.version = version;
}
public QName getName() {
return name;
}
public void setName(QName name) {
this.name = name;
}
public JavaType getJavaType() {
return javaType;
}
public void setJavaType(JavaType javaType) {
this.javaType = javaType;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isNillable() {
return false;
}
public boolean isSOAPType() {
return false;
}
public boolean isLiteralType() {
return false;
}
public Object getProperty(String key) {
if (properties == null) {
return null;
}
return properties.get(key);
}
public void setProperty(String key, Object value) {
if (value == null) {
removeProperty(key);
return;
}
if (properties == null) {
properties = new HashMap();
}
properties.put(key, value);
}
public void removeProperty(String key) {
if (properties != null) {
properties.remove(key);
}
}
public Iterator getProperties() {
if (properties == null) {
return Collections.emptyList().iterator();
} else {
return properties.keySet().iterator();
}
}
/* serialization */
public Map getPropertiesMap() {
return properties;
}
/* serialization */
public void setPropertiesMap(Map m) {
properties = m;
}
private QName name;
private JavaType javaType;
private String version = null;
private Map properties;
}

View File

@@ -0,0 +1,133 @@
/*
* 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.processor.model;
import com.sun.codemodel.internal.JClass;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.tools.internal.ws.processor.model.java.JavaSimpleType;
import com.sun.tools.internal.ws.processor.model.java.JavaType;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
/**
* @author Vivek Pandey
*
*
*/
public class AsyncOperation extends Operation {
/**
*
*/
public AsyncOperation(Entity entity) {
super(entity);
// TODO Auto-generated constructor stub
}
/**
* @param operation
*/
public AsyncOperation(Operation operation, Entity entity) {
super(operation, entity);
this.operation = operation;
}
/**
* @param name
*/
public AsyncOperation(QName name, Entity entity) {
super(name, entity);
// TODO Auto-generated constructor stub
}
/**
* @return Returns the async.
*/
public boolean isAsync() {
return _async;
}
public void setAsyncType(AsyncOperationType type) {
this._asyncOpType = type;
_async = true;
}
public AsyncOperationType getAsyncType(){
return _asyncOpType;
}
public void setResponseBean(AbstractType type){
_responseBean = type;
}
public AbstractType getResponseBeanType(){
return _responseBean;
}
public JavaType getResponseBeanJavaType(){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JClass future = cm.ref(java.util.concurrent.Future.class).narrow(cm.ref(Object.class).wildcard());
return new JavaSimpleType(new JAXBTypeAndAnnotation(future));
}else if(_asyncOpType.equals(AsyncOperationType.POLLING)){
JClass polling = cm.ref(javax.xml.ws.Response.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(polling));
}
return null;
}
public JavaType getCallBackType(){
if(_asyncOpType.equals(AsyncOperationType.CALLBACK)){
JCodeModel cm = _responseBean.getJavaType().getType().getType().owner();
JClass cb = cm.ref(javax.xml.ws.AsyncHandler.class).narrow(_responseBean.getJavaType().getType().getType().boxify());
return new JavaSimpleType(new JAXBTypeAndAnnotation(cb));
}
return null;
}
public Operation getNormalOperation(){
return operation;
}
public void setNormalOperation(Operation operation){
this.operation = operation;
}
@Override public String getJavaMethodName() {
return super.getJavaMethodName() + "Async";
}
//Normal operation
private Operation operation;
private boolean _async;
private AsyncOperationType _asyncOpType;
private AbstractType _responseBean;
}

View File

@@ -0,0 +1,43 @@
/*
* 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.processor.model;
/**
* @author Vivek Pandey
*
* Async WSDLOperation type
*/
public final class AsyncOperationType {
public static final AsyncOperationType POLLING = new AsyncOperationType();
public static final AsyncOperationType CALLBACK = new AsyncOperationType();
private AsyncOperationType() {
}
}

View File

@@ -0,0 +1,78 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wsdl.document.*;
import javax.xml.namespace.QName;
/**
*
* @author WS Development Team
*/
public class Block extends ModelObject {
public static final int UNBOUND = 0;
public static final int BODY = 1;
public static final int HEADER = 2;
public static final int ATTACHMENT = 3;
public Block(QName name, AbstractType type, Entity entity) {
super(entity);
this.name = name;
this.type = type;
}
public QName getName() {
return name;
}
public AbstractType getType() {
return type;
}
public void setType(AbstractType type) {
this.type = type;
}
public int getLocation() {
return location;
}
public void setLocation(int i) {
location = i;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
private final QName name;
private AbstractType type;
private int location;
}

View File

@@ -0,0 +1,138 @@
/*
* 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.processor.model;
import java.util.Iterator;
/**
*
* A model visitor incorporating all the logic required to walk through the model.
*
* @author WS Development Team
*/
public class ExtendedModelVisitor {
public ExtendedModelVisitor() {}
public void visit(Model model) throws Exception {
preVisit(model);
for (Service service : model.getServices()) {
preVisit(service);
for (Port port : service.getPorts()) {
preVisit(port);
if (shouldVisit(port)) {
for (Operation operation : port.getOperations()) {
preVisit(operation);
Request request = operation.getRequest();
if (request != null) {
preVisit(request);
for (Iterator iter4 = request.getHeaderBlocks();
iter4.hasNext();) {
Block block = (Block) iter4.next();
visitHeaderBlock(block);
}
for (Iterator iter4 = request.getBodyBlocks();
iter4.hasNext();) {
Block block = (Block) iter4.next();
visitBodyBlock(block);
}
for (Iterator iter4 = request.getParameters();
iter4.hasNext();) {
Parameter parameter = (Parameter) iter4.next();
visit(parameter);
}
postVisit(request);
}
Response response = operation.getResponse();
if (response != null) {
preVisit(response);
for (Iterator iter4 = response.getHeaderBlocks();
iter4.hasNext();) {
Block block = (Block) iter4.next();
visitHeaderBlock(block);
}
for (Iterator iter4 = response.getBodyBlocks();
iter4.hasNext();) {
Block block = (Block) iter4.next();
visitBodyBlock(block);
}
for (Iterator iter4 = response.getParameters();
iter4.hasNext();) {
Parameter parameter = (Parameter) iter4.next();
visit(parameter);
}
postVisit(response);
}
for (Iterator iter4 = operation.getFaults();
iter4.hasNext();) {
Fault fault = (Fault) iter4.next();
preVisit(fault);
visitFaultBlock(fault.getBlock());
postVisit(fault);
}
postVisit(operation);
}
}
postVisit(port);
}
postVisit(service);
}
postVisit(model);
}
protected boolean shouldVisit(Port port) {
return true;
}
// these methods are intended for subclasses
protected void preVisit(Model model) throws Exception {}
protected void postVisit(Model model) throws Exception {}
protected void preVisit(Service service) throws Exception {}
protected void postVisit(Service service) throws Exception {}
protected void preVisit(Port port) throws Exception {}
protected void postVisit(Port port) throws Exception {}
protected void preVisit(Operation operation) throws Exception {}
protected void postVisit(Operation operation) throws Exception {}
protected void preVisit(Request request) throws Exception {}
protected void postVisit(Request request) throws Exception {}
protected void preVisit(Response response) throws Exception {}
protected void postVisit(Response response) throws Exception {}
protected void preVisit(Fault fault) throws Exception {}
protected void postVisit(Fault fault) throws Exception {}
protected void visitBodyBlock(Block block) throws Exception {}
protected void visitHeaderBlock(Block block) throws Exception {}
protected void visitFaultBlock(Block block) throws Exception {}
protected void visit(Parameter parameter) throws Exception {}
}

View File

@@ -0,0 +1,170 @@
/*
* 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.processor.model;
import com.sun.codemodel.internal.JClass;
import com.sun.tools.internal.ws.processor.model.java.JavaException;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author WS Development Team
*/
public class Fault extends ModelObject {
public Fault(Entity entity) {
super(entity);
}
public Fault(String name, Entity entity) {
super(entity);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Block getBlock() {
return block;
}
public void setBlock(Block b) {
block = b;
}
public JavaException getJavaException() {
return javaException;
}
public void setJavaException(JavaException e) {
javaException = e;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
public Iterator getSubfaults() {
if (subfaults.isEmpty()) {
return null;
}
return subfaults.iterator();
}
/* serialization */
public Set getSubfaultsSet() {
return subfaults;
}
/* serialization */
public void setSubfaultsSet(Set s) {
subfaults = s;
}
public Iterator getAllFaults() {
Set allFaults = getAllFaultsSet();
if (allFaults.isEmpty()) {
return null;
}
return allFaults.iterator();
}
public Set getAllFaultsSet() {
Set transSet = new HashSet();
Iterator iter = subfaults.iterator();
while (iter.hasNext()) {
transSet.addAll(((Fault)iter.next()).getAllFaultsSet());
}
transSet.addAll(subfaults);
return transSet;
}
public QName getElementName() {
return elementName;
}
public void setElementName(QName elementName) {
this.elementName = elementName;
}
public String getJavaMemberName() {
return javaMemberName;
}
public void setJavaMemberName(String javaMemberName) {
this.javaMemberName = javaMemberName;
}
/**
* @return Returns the wsdlFault.
*/
public boolean isWsdlException() {
return wsdlException;
}
/**
* @param wsdlFault The wsdlFault to set.
*/
public void setWsdlException(boolean wsdlFault) {
this.wsdlException = wsdlFault;
}
public void setExceptionClass(JClass ex){
exceptionClass = ex;
}
public JClass getExceptionClass(){
return exceptionClass;
}
private boolean wsdlException = true;
private String name;
private Block block;
private JavaException javaException;
private Set subfaults = new HashSet();
private QName elementName = null;
private String javaMemberName = null;
private JClass exceptionClass;
public String getWsdlFaultName() {
return wsdlFaultName;
}
public void setWsdlFaultName(String wsdlFaultName) {
this.wsdlFaultName = wsdlFaultName;
}
private String wsdlFaultName;
}

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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
public class HeaderFault extends Fault {
public HeaderFault(Entity entity) {
super(entity);
}
public HeaderFault(String name, Entity entity) {
super(name, entity);
}
public QName getMessage() {
return _message;
}
public void setMessage(QName message) {
_message = message;
}
public String getPart() {
return _part;
}
public void setPart(String part) {
_part = part;
}
private QName _message;
private String _part;
}

View File

@@ -0,0 +1,234 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.AbortException;
import com.sun.tools.internal.ws.resources.ModelMessages;
import javax.xml.namespace.QName;
import java.util.*;
/**
*
* @author WS Development Team
*/
public abstract class Message extends ModelObject {
protected Message(com.sun.tools.internal.ws.wsdl.document.Message entity, ErrorReceiver receiver) {
super(entity);
setErrorReceiver(receiver);
}
public void addBodyBlock(Block b) {
if (_bodyBlocks.containsKey(b.getName())) {
errorReceiver.error(getEntity().getLocator(), ModelMessages.MODEL_PART_NOT_UNIQUE(((com.sun.tools.internal.ws.wsdl.document.Message)getEntity()).getName(), b.getName()));
throw new AbortException();
}
_bodyBlocks.put(b.getName(), b);
b.setLocation(Block.BODY);
}
public Iterator<Block> getBodyBlocks() {
return _bodyBlocks.values().iterator();
}
public int getBodyBlockCount() {
return _bodyBlocks.size();
}
/* serialization */
public Map<QName, Block> getBodyBlocksMap() {
return _bodyBlocks;
}
/* serialization */
public void setBodyBlocksMap(Map<QName, Block> m) {
_bodyBlocks = m;
}
public boolean isBodyEmpty() {
return getBodyBlocks().hasNext();
}
public boolean isBodyEncoded() {
boolean isEncoded = false;
for (Iterator iter = getBodyBlocks(); iter.hasNext();) {
Block bodyBlock = (Block) iter.next();
if (bodyBlock.getType().isSOAPType()) {
isEncoded = true;
}
}
return isEncoded;
}
public void addHeaderBlock(Block b) {
if (_headerBlocks.containsKey(b.getName())) {
errorReceiver.error(getEntity().getLocator(), ModelMessages.MODEL_PART_NOT_UNIQUE(((com.sun.tools.internal.ws.wsdl.document.Message)getEntity()).getName(), b.getName()));
throw new AbortException();
}
_headerBlocks.put(b.getName(), b);
b.setLocation(Block.HEADER);
}
public Iterator<Block> getHeaderBlocks() {
return _headerBlocks.values().iterator();
}
public Collection<Block> getHeaderBlockCollection() {
return _headerBlocks.values();
}
public int getHeaderBlockCount() {
return _headerBlocks.size();
}
/* serialization */
public Map<QName, Block> getHeaderBlocksMap() {
return _headerBlocks;
}
/* serialization */
public void setHeaderBlocksMap(Map<QName, Block> m) {
_headerBlocks = m;
}
/** attachment block */
public void addAttachmentBlock(Block b) {
if (_attachmentBlocks.containsKey(b.getName())) {
errorReceiver.error(getEntity().getLocator(), ModelMessages.MODEL_PART_NOT_UNIQUE(((com.sun.tools.internal.ws.wsdl.document.Message)getEntity()).getName(), b.getName()));
throw new AbortException();
}
_attachmentBlocks.put(b.getName(), b);
b.setLocation(Block.ATTACHMENT);
}
public void addUnboundBlock(Block b) {
if (_unboundBlocks.containsKey(b.getName())) {
return;
}
_unboundBlocks.put(b.getName(), b);
b.setLocation(Block.UNBOUND);
}
public Iterator<Block> getUnboundBlocks() {
return _unboundBlocks.values().iterator();
}
/* serialization */
public Map<QName, Block> getUnboundBlocksMap() {
return _unboundBlocks;
}
public int getUnboundBlocksCount() {
return _unboundBlocks.size();
}
/* serialization */
public void setUnboundBlocksMap(Map<QName, Block> m) {
_unboundBlocks = m;
}
public Iterator<Block> getAttachmentBlocks() {
return _attachmentBlocks.values().iterator();
}
public int getAttachmentBlockCount () {
return _attachmentBlocks.size();
}
/* serialization */
public Map<QName, Block> getAttachmentBlocksMap() {
return _attachmentBlocks;
}
/* serialization */
public void setAttachmentBlocksMap(Map<QName, Block> m) {
_attachmentBlocks = m;
}
public void addParameter(Parameter p) {
if (_parametersByName.containsKey(p.getName())) {
errorReceiver.error(getEntity().getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE(p.getName(), p.getName()));
throw new AbortException();
}
_parameters.add(p);
String name = p.getCustomName() != null ? p.getCustomName() : p.getName();
_parametersByName.put(name, p);
}
public Parameter getParameterByName(String name) {
if (_parametersByName.size() != _parameters.size()) {
initializeParametersByName();
}
return _parametersByName.get(name);
}
public Iterator<Parameter> getParameters() {
return _parameters.iterator();
}
/* serialization */
public List<Parameter> getParametersList() {
return _parameters;
}
/* serialization */
public void setParametersList(List<Parameter> l) {
_parameters = l;
}
private void initializeParametersByName() {
_parametersByName = new HashMap();
if (_parameters != null) {
for (Iterator iter = _parameters.iterator(); iter.hasNext();) {
Parameter param = (Parameter) iter.next();
if (param.getName() != null &&
_parametersByName.containsKey(param.getName())) {
errorReceiver.error(getEntity().getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE(param.getName(), param.getName()));
throw new AbortException();
}
_parametersByName.put(param.getName(), param);
}
}
}
public Set<Block> getAllBlocks(){
Set<Block> blocks = new HashSet<Block>();
blocks.addAll(_bodyBlocks.values());
blocks.addAll(_headerBlocks.values());
blocks.addAll(_attachmentBlocks.values());
return blocks;
}
private Map<QName, Block> _attachmentBlocks = new HashMap<QName, Block>();
private Map<QName, Block> _bodyBlocks = new HashMap<QName, Block>();
private Map<QName, Block> _headerBlocks = new HashMap<QName, Block>();
private Map<QName, Block> _unboundBlocks = new HashMap<QName, Block>();
private List<Parameter> _parameters = new ArrayList<Parameter>();
private Map<String, Parameter> _parametersByName = new HashMap<String, Parameter>();
}

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.processor.model;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBModel;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
import java.util.*;
/**
* The model is used to represent the entire Web Service. The JAX-WS ProcessorActions can process
* this Model to generate Java artifacts such as the service interface.
*
* @author WS Development Team
*/
public class Model extends ModelObject {
public Model(Entity entity) {
super(entity);
}
public Model(QName name, Entity entity) {
super(entity);
this.name = name;
}
public QName getName() {
return name;
}
public void setName(QName n) {
name = n;
}
public String getTargetNamespaceURI() {
return targetNamespace;
}
public void setTargetNamespaceURI(String s) {
targetNamespace = s;
}
public void addService(Service service) {
if (servicesByName.containsKey(service.getName())) {
throw new ModelException("model.uniqueness");
}
services.add(service);
servicesByName.put(service.getName(), service);
}
public Service getServiceByName(QName name) {
if (servicesByName.size() != services.size()) {
initializeServicesByName();
}
return (Service)servicesByName.get(name);
}
/* serialization */
public List<Service> getServices() {
return services;
}
/* serialization */
public void setServices(List<Service> l) {
services = l;
}
private void initializeServicesByName() {
servicesByName = new HashMap();
if (services != null) {
for (Service service : services) {
if (service.getName() != null &&
servicesByName.containsKey(service.getName())) {
throw new ModelException("model.uniqueness");
}
servicesByName.put(service.getName(), service);
}
}
}
public void addExtraType(AbstractType type) {
extraTypes.add(type);
}
public Iterator getExtraTypes() {
return extraTypes.iterator();
}
/* serialization */
public Set<AbstractType> getExtraTypesSet() {
return extraTypes;
}
/* serialization */
public void setExtraTypesSet(Set<AbstractType> s) {
extraTypes = s;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
/**
* @return the source version
*/
public String getSource() {
return source;
}
/**
* @param string
*/
public void setSource(String string) {
source = string;
}
public void setJAXBModel(JAXBModel jaxBModel) {
this.jaxBModel = jaxBModel;
}
public JAXBModel getJAXBModel() {
return jaxBModel;
}
private QName name;
private String targetNamespace;
private List<Service> services = new ArrayList<Service>();
private Map<QName, Service> servicesByName = new HashMap<QName, Service>();
private Set<AbstractType> extraTypes = new HashSet<AbstractType>();
private String source;
private JAXBModel jaxBModel = null;
}

View File

@@ -0,0 +1,56 @@
/*
* 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.processor.model;
import com.sun.istack.internal.localization.Localizable;
import com.sun.tools.internal.ws.processor.ProcessorException;
/**
* ModelException represents an exception that occurred while
* visiting service model.
*
* @see ProcessorException
*
* @author WS Development Team
*/
public class ModelException extends ProcessorException {
public ModelException(String key, Object... args) {
super(key, args);
}
public ModelException(Throwable throwable) {
super(throwable);
}
public ModelException(Localizable arg) {
super("model.nestedModelError", arg);
}
public String getDefaultResourceBundleName() {
return "com.sun.tools.internal.ws.resources.model";
}
}

View File

@@ -0,0 +1,115 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.xml.sax.Locator;
/**
*
* @author WS Development Team
*/
public abstract class ModelObject {
public abstract void accept(ModelVisitor visitor) throws Exception;
private final Entity entity;
protected ErrorReceiver errorReceiver;
protected ModelObject(Entity entity) {
this.entity = entity;
}
public void setErrorReceiver(ErrorReceiver errorReceiver) {
this.errorReceiver = errorReceiver;
}
public Entity getEntity() {
return entity;
}
public Object getProperty(String key) {
if (_properties == null) {
return null;
}
return _properties.get(key);
}
public void setProperty(String key, Object value) {
if (value == null) {
removeProperty(key);
return;
}
if (_properties == null) {
_properties = new HashMap();
}
_properties.put(key, value);
}
public void removeProperty(String key) {
if (_properties != null) {
_properties.remove(key);
}
}
public Iterator getProperties() {
if (_properties == null) {
return Collections.emptyList().iterator();
} else {
return _properties.keySet().iterator();
}
}
public Locator getLocator(){
return entity.getLocator();
}
public Map getPropertiesMap() {
return _properties;
}
public void setPropertiesMap(Map m) {
_properties = m;
}
public String getJavaDoc() {
return javaDoc;
}
public void setJavaDoc(String javaDoc) {
this.javaDoc = javaDoc;
}
private String javaDoc;
private Map _properties;
}

View File

@@ -0,0 +1,76 @@
/*
* 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.processor.model;
/**
*
* @author WS Development Team
*/
public interface ModelProperties {
//to set WSDL_MODELER_NAME from inside WSDLModeler
public static final String WSDL_MODELER_NAME =
"com.sun.xml.internal.ws.processor.modeler.wsdl.WSDLModeler";
public static final String PROPERTY_PARAM_MESSAGE_PART_NAME =
"com.sun.xml.internal.ws.processor.model.ParamMessagePartName";
public static final String PROPERTY_ANONYMOUS_TYPE_NAME =
"com.sun.xml.internal.ws.processor.model.AnonymousTypeName";
public static final String PROPERTY_ANONYMOUS_ARRAY_TYPE_NAME =
"com.sun.xml.internal.ws.processor.model.AnonymousArrayTypeName";
public static final String PROPERTY_ANONYMOUS_ARRAY_JAVA_TYPE =
"com.sun.xml.internal.ws.processor.model.AnonymousArrayJavaType";
public static final String PROPERTY_PTIE_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.PtieClassName";
public static final String PROPERTY_EPTFF_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.EPTFFClassName";
public static final String PROPERTY_SED_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.SEDClassName";
public static final String PROPERTY_WSDL_PORT_NAME =
"com.sun.xml.internal.ws.processor.model.WSDLPortName";
public static final String PROPERTY_WSDL_PORT_TYPE_NAME =
"com.sun.xml.internal.ws.processor.model.WSDLPortTypeName";
public static final String PROPERTY_WSDL_BINDING_NAME =
"com.sun.xml.internal.ws.processor.model.WSDLBindingName";
public static final String PROPERTY_WSDL_MESSAGE_NAME =
"com.sun.xml.internal.ws.processor.model.WSDLMessageName";
public static final String PROPERTY_MODELER_NAME =
"com.sun.xml.internal.ws.processor.model.ModelerName";
public static final String PROPERTY_STUB_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.StubClassName";
public static final String PROPERTY_STUB_OLD_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.StubOldClassName";
public static final String PROPERTY_DELEGATE_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.DelegateClassName";
public static final String PROPERTY_CLIENT_ENCODER_DECODER_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.ClientEncoderClassName";
public static final String PROPERTY_CLIENT_CONTACTINFOLIST_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.ClientContactInfoListClassName";
public static final String PROPERTY_TIE_CLASS_NAME =
"com.sun.xml.internal.ws.processor.model.TieClassName";
public static final String PROPERTY_JAVA_PORT_NAME =
"com.sun.xml.internal.ws.processor.model.JavaPortName";
}

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.processor.model;
/**
*
* @author WS Development Team
*/
public interface ModelVisitor {
public void visit(Model model) throws Exception;
public void visit(Service service) throws Exception;
public void visit(Port port) throws Exception;
public void visit(Operation operation) throws Exception;
public void visit(Request request) throws Exception;
public void visit(Response response) throws Exception;
public void visit(Fault fault) throws Exception;
public void visit(Block block) throws Exception;
public void visit(Parameter parameter) throws Exception;
}

View File

@@ -0,0 +1,257 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.processor.model.java.JavaMethod;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPUse;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.xml.internal.ws.spi.db.BindingHelper;
import javax.xml.namespace.QName;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author WS Development Team
*/
public class Operation extends ModelObject {
public Operation(Entity entity) {
super(entity);
}
public Operation(Operation operation, Entity entity){
this(operation._name, entity);
this._style = operation._style;
this._use = operation._use;
this.customizedName = operation.customizedName;
}
public Operation(QName name, Entity entity) {
super(entity);
_name = name;
_uniqueName = name.getLocalPart();
_faultNames = new HashSet<String>();
_faults = new HashSet<Fault>();
}
public QName getName() {
return _name;
}
public void setName(QName n) {
_name = n;
}
public String getUniqueName() {
return _uniqueName;
}
public void setUniqueName(String s) {
_uniqueName = s;
}
public Request getRequest() {
return _request;
}
public void setRequest(Request r) {
_request = r;
}
public Response getResponse() {
return _response;
}
public void setResponse(Response r) {
_response = r;
}
public boolean isOverloaded() {
return !_name.getLocalPart().equals(_uniqueName);
}
public void addFault(Fault f) {
if (_faultNames.contains(f.getName())) {
throw new ModelException("model.uniqueness");
}
_faultNames.add(f.getName());
_faults.add(f);
}
public Iterator<Fault> getFaults() {
return _faults.iterator();
}
public Set<Fault> getFaultsSet() {
return _faults;
}
/* serialization */
public void setFaultsSet(Set<Fault> s) {
_faults = s;
initializeFaultNames();
}
private void initializeFaultNames() {
_faultNames = new HashSet<String>();
if (_faults != null) {
for (Iterator iter = _faults.iterator(); iter.hasNext();) {
Fault f = (Fault) iter.next();
if (f.getName() != null && _faultNames.contains(f.getName())) {
throw new ModelException("model.uniqueness");
}
_faultNames.add(f.getName());
}
}
}
public Iterator<Fault> getAllFaults() {
Set<Fault> allFaults = getAllFaultsSet();
return allFaults.iterator();
}
public Set<Fault> getAllFaultsSet() {
Set transSet = new HashSet();
transSet.addAll(_faults);
Iterator iter = _faults.iterator();
Fault fault;
Set tmpSet;
while (iter.hasNext()) {
tmpSet = ((Fault)iter.next()).getAllFaultsSet();
transSet.addAll(tmpSet);
}
return transSet;
}
public int getFaultCount() {
return _faults.size();
}
public Set<Block> getAllFaultBlocks(){
Set<Block> blocks = new HashSet<Block>();
Iterator faults = _faults.iterator();
while(faults.hasNext()){
Fault f = (Fault)faults.next();
blocks.add(f.getBlock());
}
return blocks;
}
public JavaMethod getJavaMethod() {
return _javaMethod;
}
public void setJavaMethod(JavaMethod i) {
_javaMethod = i;
}
public String getSOAPAction() {
return _soapAction;
}
public void setSOAPAction(String s) {
_soapAction = s;
}
public SOAPStyle getStyle() {
return _style;
}
public void setStyle(SOAPStyle s) {
_style = s;
}
public SOAPUse getUse() {
return _use;
}
public void setUse(SOAPUse u) {
_use = u;
}
public boolean isWrapped() {
return _isWrapped;
}
public void setWrapped(boolean isWrapped) {
_isWrapped = isWrapped;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
public void setCustomizedName(String name){
this.customizedName = name;
}
public String getCustomizedName(){
return customizedName;
}
public String getJavaMethodName(){
//if JavaMethod is created return the name
if(_javaMethod != null){
return _javaMethod.getName();
}
//return the customized operation name if any without mangling
if(customizedName != null){
return customizedName;
}
return BindingHelper.mangleNameToVariableName(_name.getLocalPart());
}
public com.sun.tools.internal.ws.wsdl.document.Operation getWSDLPortTypeOperation(){
return wsdlOperation;
}
public void setWSDLPortTypeOperation(com.sun.tools.internal.ws.wsdl.document.Operation wsdlOperation){
this.wsdlOperation = wsdlOperation;
}
private String customizedName;
private boolean _isWrapped = true;
private QName _name;
private String _uniqueName;
private Request _request;
private Response _response;
private JavaMethod _javaMethod;
private String _soapAction;
private SOAPStyle _style = SOAPStyle.DOCUMENT;
private SOAPUse _use = SOAPUse.LITERAL;
private Set<String> _faultNames;
private Set<Fault> _faults;
private com.sun.tools.internal.ws.wsdl.document.Operation wsdlOperation;
}

View File

@@ -0,0 +1,193 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.processor.model.java.JavaParameter;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wsdl.document.MessagePart;
import javax.jws.WebParam.Mode;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author WS Development Team
*/
public class Parameter extends ModelObject {
private final String entityName;
public Parameter(String name, Entity entity) {
super(entity);
this.name = name;
if(entity instanceof com.sun.tools.internal.ws.wsdl.document.Message){
this.entityName = ((com.sun.tools.internal.ws.wsdl.document.Message)entity).getName();
}else if(entity instanceof MessagePart){
this.entityName = ((MessagePart)entity).getName();
}else{
this.entityName = name;
}
}
public String getEntityName() {
return entityName;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public JavaParameter getJavaParameter() {
return javaParameter;
}
public void setJavaParameter(JavaParameter p) {
javaParameter = p;
}
public AbstractType getType() {
return type;
}
public void setType(AbstractType t) {
type = t;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String t) {
typeName = t;
}
public Block getBlock() {
return block;
}
public void setBlock(Block d) {
block = d;
}
public Parameter getLinkedParameter() {
return link;
}
public void setLinkedParameter(Parameter p) {
link = p;
}
public boolean isEmbedded() {
return embedded;
}
public void setEmbedded(boolean b) {
embedded = b;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
private String name;
private JavaParameter javaParameter;
private AbstractType type;
private Block block;
private Parameter link;
private boolean embedded;
private String typeName;
private String customName;
private Mode mode;
public int getParameterIndex() {
return parameterOrderPosition;
}
public void setParameterIndex(int parameterOrderPosition) {
this.parameterOrderPosition = parameterOrderPosition;
}
public boolean isReturn(){
return (parameterOrderPosition == -1);
}
// 0 is the first parameter, -1 is the return type
private int parameterOrderPosition;
/**
* @return Returns the customName.
*/
public String getCustomName() {
return customName;
}
/**
* @param customName The customName to set.
*/
public void setCustomName(String customName) {
this.customName = customName;
}
private List<String> annotations = new ArrayList<String>();
/**
* @return Returns the annotations.
*/
public List<String> getAnnotations() {
return annotations;
}
/**
* @param annotations The annotations to set.
*/
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
public void setMode(Mode mode){
this.mode = mode;
}
public boolean isIN(){
return (mode == Mode.IN);
}
public boolean isOUT(){
return (mode == Mode.OUT);
}
public boolean isINOUT(){
return (mode == Mode.INOUT);
}
}

View File

@@ -0,0 +1,179 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.wsdl.document.PortType;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author WS Development Team
*/
public class Port extends ModelObject {
public Port(Entity entity) {
super(entity);
}
public Port(QName name, Entity entity) {
super(entity);
_name = name;
}
public QName getName() {
return _name;
}
public void setName(QName n) {
_name = n;
}
public void addOperation(Operation operation) {
_operations.add(operation);
operationsByName.put(operation.getUniqueName(), operation);
}
public Operation getOperationByUniqueName(String name) {
if (operationsByName.size() != _operations.size()) {
initializeOperationsByName();
}
return operationsByName.get(name);
}
private void initializeOperationsByName() {
operationsByName = new HashMap<String, Operation>();
if (_operations != null) {
for (Operation operation : _operations) {
if (operation.getUniqueName() != null &&
operationsByName.containsKey(operation.getUniqueName())) {
throw new ModelException("model.uniqueness");
}
operationsByName.put(operation.getUniqueName(), operation);
}
}
}
/* serialization */
public List<Operation> getOperations() {
return _operations;
}
/* serialization */
public void setOperations(List<Operation> l) {
_operations = l;
}
public JavaInterface getJavaInterface() {
return _javaInterface;
}
public void setJavaInterface(JavaInterface i) {
_javaInterface = i;
}
public String getAddress() {
return _address;
}
public void setAddress(String s) {
_address = s;
}
public String getServiceImplName() {
return _serviceImplName;
}
public void setServiceImplName(String name) {
_serviceImplName = name;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
public boolean isProvider() {
JavaInterface intf = getJavaInterface();
if (intf != null) {
String sei = intf.getName();
if (sei.equals(javax.xml.ws.Provider.class.getName())) {
return true;
}
}
return false;
}
/**
* XYZ_Service.getABC() method name
*
* @return Returns the portGetterName.
*/
public String getPortGetter() {
return portGetter;
}
/**
* @param portGetterName The portGetterName to set.
*/
public void setPortGetter(String portGetterName) {
this.portGetter = portGetterName;
}
public SOAPStyle getStyle() {
return _style;
}
public void setStyle(SOAPStyle s) {
_style = s;
}
public boolean isWrapped() {
return _isWrapped;
}
public void setWrapped(boolean isWrapped) {
_isWrapped = isWrapped;
}
private SOAPStyle _style = null;
private boolean _isWrapped = true;
private String portGetter;
private QName _name;
private List<Operation> _operations = new ArrayList<Operation>();
private JavaInterface _javaInterface;
private String _address;
private String _serviceImplName;
private Map<String, Operation> operationsByName = new HashMap<String, Operation>();
public Map<QName, PortType> portTypes = new HashMap<QName, PortType>();
}

View File

@@ -0,0 +1,44 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
/**
*
* @author WS Development Team
*/
public class Request extends Message {
public Request(com.sun.tools.internal.ws.wsdl.document.Message entity, ErrorReceiver receiver) {
super(entity, receiver);
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
}

View File

@@ -0,0 +1,74 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author WS Development Team
*/
public class Response extends Message {
public Response(com.sun.tools.internal.ws.wsdl.document.Message entity, ErrorReceiver receiver) {
super(entity, receiver);
}
public void addFaultBlock(Block b) {
if (_faultBlocks.containsKey(b.getName())) {
throw new ModelException("model.uniqueness");
}
_faultBlocks.put(b.getName(), b);
}
public Iterator getFaultBlocks() {
return _faultBlocks.values().iterator();
}
public int getFaultBlockCount () {
return _faultBlocks.size();
}
/* serialization */
public Map getFaultBlocksMap() {
return _faultBlocks;
}
public void setFaultBlocksMap(Map m) {
_faultBlocks = m;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
private Map _faultBlocks = new HashMap();
}

View File

@@ -0,0 +1,120 @@
/*
* 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.processor.model;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import javax.xml.namespace.QName;
import java.util.*;
/**
*
* @author WS Development Team
*/
public class Service extends ModelObject {
public Service(Entity entity) {
super(entity);
}
public Service(QName name, JavaInterface javaInterface, Entity entity) {
super(entity);
this.name = name;
this.javaInterface = javaInterface;
}
public QName getName() {
return name;
}
public void setName(QName n) {
name = n;
}
public void addPort(Port port) {
if (portsByName.containsKey(port.getName())) {
throw new ModelException("model.uniqueness");
}
ports.add(port);
portsByName.put(port.getName(), port);
}
public Port getPortByName(QName n) {
if (portsByName.size() != ports.size()) {
initializePortsByName();
}
return (Port) portsByName.get(n);
}
/* serialization */
public List<Port> getPorts() {
return ports;
}
/* serialization */
public void setPorts(List<Port> m) {
ports = m;
// initializePortsByName();
}
private void initializePortsByName() {
portsByName = new HashMap();
if (ports != null) {
for (Iterator iter = ports.iterator(); iter.hasNext();) {
Port port = (Port) iter.next();
if (port.getName() != null &&
portsByName.containsKey(port.getName())) {
throw new ModelException("model.uniqueness");
}
portsByName.put(port.getName(), port);
}
}
}
public JavaInterface getJavaIntf() {
return getJavaInterface();
}
public JavaInterface getJavaInterface() {
return javaInterface;
}
public void setJavaInterface(JavaInterface i) {
javaInterface = i;
}
public void accept(ModelVisitor visitor) throws Exception {
visitor.visit(this);
}
private QName name;
private List<Port> ports = new ArrayList();
private Map<QName, Port> portsByName = new HashMap<QName, Port>();
private JavaInterface javaInterface;
}

View File

@@ -0,0 +1,48 @@
/*
* 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.processor.model.exporter;
import org.xml.sax.ContentHandler;
/**
* "Opaque" object in the object graph that knows how
* to persist itself to XML.
*
* TODO: ExternalObjectReader
*
*/
public interface ExternalObject {
/**
* Type name of this object. This will be used
* when loading the object back from XML.
*/
String getType();
/**
* Saves the object into XML.
*/
void saveTo(ContentHandler receiver);
}

View File

@@ -0,0 +1,77 @@
/*
* 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.processor.model.java;
/**
*
* @author WS Development Team
*/
public class JavaArrayType extends JavaType {
public JavaArrayType() {
}
public JavaArrayType(String name) {
super(name, true, "null");
}
public JavaArrayType(String name, String elementName,
JavaType elementType) {
super(name, true, "null");
this.elementName = elementName;
this.elementType = elementType;
}
public String getElementName() {
return elementName;
}
public void setElementName(String name) {
elementName = name;
}
public JavaType getElementType() {
return elementType;
}
public void setElementType(JavaType type) {
elementType = type;
}
// bug fix:4904604
public String getSOAPArrayHolderName() {
return soapArrayHolderName;
}
public void setSOAPArrayHolderName(String holderName) {
this.soapArrayHolderName = holderName;
}
private String elementName;
private JavaType elementType;
private String soapArrayHolderName;
}

View File

@@ -0,0 +1,39 @@
/*
* 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.processor.model.java;
/**
*
* @author WS Development Team
*/
public class JavaException extends JavaStructureType {
public JavaException() {}
public JavaException(String name, boolean present, Object owner) {
super(name, present, owner);
}
}

View File

@@ -0,0 +1,166 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.processor.model.ModelException;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* @author WS Development Team
*/
public class JavaInterface {
public JavaInterface() {}
public JavaInterface(String name) {
this(name, null);
}
public JavaInterface(String name, String impl) {
this.realName = name;
this.name = name.replace('$', '.');
this.impl = impl;
}
public String getName() {
return name;
}
public String getFormalName() {
return name;
}
public void setFormalName(String s) {
name = s;
}
public String getRealName() {
return realName;
}
public void setRealName(String s) {
realName = s;
}
public String getImpl() {
return impl;
}
public void setImpl(String s) {
impl = s;
}
public Iterator getMethods() {
return methods.iterator();
}
public boolean hasMethod(JavaMethod method) {
for (int i=0; i<methods.size();i++) {
if (method.equals(((JavaMethod)methods.get(i)))) {
return true;
}
}
return false;
}
public void addMethod(JavaMethod method) {
if (hasMethod(method)) {
throw new ModelException("model.uniqueness");
}
methods.add(method);
}
/* serialization */
public List getMethodsList() {
return methods;
}
/* serialization */
public void setMethodsList(List l) {
methods = l;
}
public boolean hasInterface(String interfaceName) {
for (int i=0; i<interfaces.size();i++) {
if (interfaceName.equals((String)interfaces.get(i))) {
return true;
}
}
return false;
}
public void addInterface(String interfaceName) {
// verify that an exception with this name does not already exist
if (hasInterface(interfaceName)) {
return;
}
interfaces.add(interfaceName);
}
public Iterator getInterfaces() {
return interfaces.iterator();
}
/* serialization */
public List getInterfacesList() {
return interfaces;
}
/* serialization */
public void setInterfacesList(List l) {
interfaces = l;
}
public String getSimpleName() {
return ClassNameInfo.getName(name);
}
/* NOTE - all these fields (except "interfaces") were final, but had to
* remove this modifier to enable serialization
*/
private String javadoc;
public String getJavaDoc() {
return javadoc;
}
public void setJavaDoc(String javadoc) {
this.javadoc = javadoc;
}
private String name;
private String realName;
private String impl;
private List methods = new ArrayList();
private List interfaces = new ArrayList();
}

View File

@@ -0,0 +1,129 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.resources.ModelMessages;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.processor.model.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
/**
* @author WS Development Team
*/
public class JavaMethod {
private final ErrorReceiver errorReceiver;
private final String name;
private final List<JavaParameter> parameters = new ArrayList<JavaParameter>();
private final List<String> exceptions = new ArrayList<String>();
private final WsimportOptions options;
private JavaType returnType;
public JavaMethod(String name, WsimportOptions options, ErrorReceiver receiver) {
this.name = name;
this.returnType = null;
this.errorReceiver = receiver;
this.options = options;
}
public String getName() {
return name;
}
public JavaType getReturnType() {
return returnType;
}
public void setReturnType(JavaType returnType) {
this.returnType = returnType;
}
private boolean hasParameter(String paramName) {
for (JavaParameter parameter : parameters) {
if (paramName.equals(parameter.getName())) {
return true;
}
}
return false;
}
private Parameter getParameter(String paramName){
for (JavaParameter parameter : parameters) {
if (paramName.equals(parameter.getName())) {
return parameter.getParameter();
}
}
return null;
}
public void addParameter(JavaParameter param) {
// verify that this member does not already exist
if (hasParameter(param.getName())) {
if (options.isExtensionMode()) {
param.setName(getUniqueName(param.getName()));
} else {
Parameter duplicParam = getParameter(param.getName());
if(param.getParameter().isEmbedded()){
errorReceiver.error(param.getParameter().getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE_WRAPPER(param.getName(), param.getParameter().getEntityName()));
errorReceiver.error(duplicParam.getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE_WRAPPER(param.getName(), duplicParam.getEntityName()));
} else {
errorReceiver.error(param.getParameter().getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE(param.getName(), param.getParameter().getEntityName()));
errorReceiver.error(duplicParam.getLocator(), ModelMessages.MODEL_PARAMETER_NOTUNIQUE(param.getName(), duplicParam.getEntityName()));
}
return;
}
}
parameters.add(param);
}
public List<JavaParameter> getParametersList() {
return parameters;
}
public void addException(String exception) {
// verify that this exception does not already exist
if (!exceptions.contains(exception)) {
exceptions.add(exception);
}
}
/** TODO: NB uses it, remove it once we expose it thru some API **/
public Iterator<String> getExceptions() {
return exceptions.iterator();
}
private String getUniqueName(String param){
int parmNum = 0;
while (hasParameter(param)) {
param = param + Integer.toString(parmNum++);
}
return param;
}
}

View File

@@ -0,0 +1,96 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.processor.model.Parameter;
/**
*
* @author WS Development Team
*/
public class JavaParameter {
public JavaParameter() {}
public JavaParameter(String name, JavaType type, Parameter parameter) {
this(name, type, parameter, false);
}
public JavaParameter(String name, JavaType type, Parameter parameter,
boolean holder) {
this.name = name;
this.type = type;
this.parameter = parameter;
this.holder = holder;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public JavaType getType() {
return type;
}
public void setType(JavaType t) {
type = t;
}
public Parameter getParameter() {
return parameter;
}
public void setParameter(Parameter p) {
parameter = p;
}
public boolean isHolder() {
return holder;
}
public void setHolder(boolean b) {
holder = b;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
private String name;
private JavaType type;
private Parameter parameter;
private boolean holder;
private String holderName;
}

View File

@@ -0,0 +1,46 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
/**
*
* @author WS Development Team
*/
public class JavaSimpleType extends JavaType {
public JavaSimpleType() {}
public JavaSimpleType(String name, String initString) {
super(name, true, initString);
}
public JavaSimpleType(JAXBTypeAndAnnotation jtype) {
super(jtype);
}
}

View File

@@ -0,0 +1,129 @@
/*
* 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.processor.model.java;
/**
*
* @author WS Development Team
*/
public class JavaStructureMember {
public JavaStructureMember() {}
public JavaStructureMember(String name, JavaType type, Object owner) {
this(name, type, owner, false);
}
public JavaStructureMember(String name, JavaType type,
Object owner, boolean isPublic) {
this.name = name;
this.type = type;
this.owner = owner;
this.isPublic = isPublic;
constructorPos = -1;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public JavaType getType() {
return type;
}
public void setType(JavaType t) {
type = t;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean b) {
isPublic = b;
}
public boolean isInherited() {
return isInherited;
}
public void setInherited(boolean b) {
isInherited = b;
}
public String getReadMethod() {
return readMethod;
}
public void setReadMethod(String readMethod) {
this.readMethod = readMethod;
}
public String getWriteMethod() {
return writeMethod;
}
public void setWriteMethod(String writeMethod) {
this.writeMethod = writeMethod;
}
public String getDeclaringClass() {
return declaringClass;
}
public void setDeclaringClass(String declaringClass) {
this.declaringClass = declaringClass;
}
public Object getOwner() {
return owner;
}
public void setOwner(Object owner) {
this.owner = owner;
}
public int getConstructorPos() {
return constructorPos;
}
public void setConstructorPos(int idx) {
constructorPos = idx;
}
private String name;
private JavaType type;
private boolean isPublic = false;
private boolean isInherited = false;
private String readMethod;
private String writeMethod;
private String declaringClass;
private Object owner;
private int constructorPos;
}

View File

@@ -0,0 +1,175 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.processor.model.ModelException;
import java.util.*;
/**
*
* @author WS Development Team
*/
public class JavaStructureType extends JavaType {
public JavaStructureType() {}
public JavaStructureType(String name, boolean present, Object owner) {
super(name, present, "null");
this.owner = owner;
}
public void add(JavaStructureMember m) {
if (membersByName.containsKey(m.getName())) {
throw new ModelException("model.uniqueness.javastructuretype",
new Object[] {m.getName(), getRealName()});
}
members.add(m);
membersByName.put(m.getName(), m);
}
public JavaStructureMember getMemberByName(String name) {
if (membersByName.size() != members.size()) {
initializeMembersByName();
}
return membersByName.get(name);
}
public Iterator getMembers() {
return members.iterator();
}
public int getMembersCount() {
return members.size();
}
/* serialization */
public List<JavaStructureMember> getMembersList() {
return members;
}
/* serialization */
public void setMembersList(List<JavaStructureMember> l) {
members = l;
}
private void initializeMembersByName() {
membersByName = new HashMap<String, JavaStructureMember>();
if (members != null) {
for (JavaStructureMember m : members) {
if (m.getName() != null &&
membersByName.containsKey(m.getName())) {
throw new ModelException("model.uniqueness");
}
membersByName.put(m.getName(), m);
}
}
}
public boolean isAbstract() {
return isAbstract;
}
public void setAbstract(boolean isAbstract) {
this.isAbstract = isAbstract;
}
public JavaStructureType getSuperclass() {
return superclass;
}
public void setSuperclass(JavaStructureType superclassType) {
superclass = superclassType;
}
public void addSubclass(JavaStructureType subclassType) {
subclasses.add(subclassType);
subclassType.setSuperclass(this);
}
public Iterator getSubclasses() {
if (subclasses == null || subclasses.size() == 0) {
return null;
}
return subclasses.iterator();
}
public Set getSubclassesSet() {
return subclasses;
}
/* serialization */
public void setSubclassesSet(Set s) {
subclasses = s;
for (Iterator iter = s.iterator(); iter.hasNext();) {
((JavaStructureType) iter.next()).setSuperclass(this);
}
}
public Iterator getAllSubclasses() {
Set subs = getAllSubclassesSet();
if (subs.size() == 0) {
return null;
}
return subs.iterator();
}
public Set getAllSubclassesSet() {
Set transitiveSet = new HashSet();
Iterator subs = subclasses.iterator();
while (subs.hasNext()) {
transitiveSet.addAll(
((JavaStructureType)subs.next()).getAllSubclassesSet());
}
transitiveSet.addAll(subclasses);
return transitiveSet;
}
public Object getOwner() {
// usually a SOAPStructureType
return owner;
}
public void setOwner(Object owner) {
// usually a SOAPStructureType
this.owner = owner;
}
private List<JavaStructureMember> members = new ArrayList();
private Map<String, JavaStructureMember> membersByName = new HashMap();
// known subclasses of this type
private Set subclasses = new HashSet();
private JavaStructureType superclass;
// usually a SOAPStructureType
private Object owner;
private boolean isAbstract = false;
}

View File

@@ -0,0 +1,145 @@
/*
* 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.processor.model.java;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
/**
*
* @author WS Development Team
*/
public abstract class JavaType {
private String name;
private String realName;
private boolean present;
private boolean holder;
private boolean holderPresent;
private String initString;
private String holderName;
private JAXBTypeAndAnnotation type;
public JavaType() {}
public JavaType(JAXBTypeAndAnnotation type){
this.type = type;
init(type.getName(), false, null, null);
}
public JavaType(String name, boolean present, String initString) {
init(name, present, initString, null);
}
public JavaType(String name, boolean present, String initString,
String holderName) {
init(name, present, initString, holderName);
}
public JAXBTypeAndAnnotation getType(){
return type;
}
private void init(String name, boolean present, String initString,
String holderName) {
this.realName = name;
this.name = name.replace('$', '.');
this.present = present;
this.initString = initString;
this.holderName = holderName;
holder = holderName != null;
}
public String getName() {
return name;
}
public void doSetName(String name) {
// renamed to avoid creating a "name" property with broken semantics
this.realName = name;
this.name = name.replace('$', '.');
}
public String getRealName() {
return realName;
}
/* serialization */
public void setRealName(String s) {
realName = s;
}
public String getFormalName() {
return name;
}
public void setFormalName(String s) {
name = s;
}
public boolean isPresent() {
return present;
}
/* serialization */
public void setPresent(boolean b) {
present = b;
}
public boolean isHolder() {
return holder;
}
public void setHolder(boolean holder) {
this.holder = holder;
}
public boolean isHolderPresent() {
return holderPresent;
}
public void setHolderPresent(boolean holderPresent) {
this.holderPresent = holderPresent;
}
public String getInitString() {
return initString;
}
/* serialization */
public void setInitString(String s) {
initString = s;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
}

View File

@@ -0,0 +1,100 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.ws.processor.model.java.JavaStructureMember;
import javax.xml.namespace.QName;
/**
* @author Kathy Walsh, Vivek Pandey
*
*
*/
public class JAXBElementMember {
public JAXBElementMember() {
}
public JAXBElementMember(QName name, JAXBType type) {
this(name, type, null);
}
public JAXBElementMember(QName name, JAXBType type,
JavaStructureMember javaStructureMember) {
_name = name;
_type = type;
_javaStructureMember = javaStructureMember;
}
public QName getName() {
return _name;
}
public void setName(QName n) {
_name = n;
}
public JAXBType getType() {
return _type;
}
public void setType(JAXBType t) {
_type = t;
}
public boolean isRepeated() {
return _repeated;
}
public void setRepeated(boolean b) {
_repeated = b;
}
public JavaStructureMember getJavaStructureMember() {
return _javaStructureMember;
}
public void setJavaStructureMember(JavaStructureMember javaStructureMember) {
_javaStructureMember = javaStructureMember;
}
public boolean isInherited() {
return isInherited;
}
public void setInherited(boolean b) {
isInherited = b;
}
public JAXBProperty getProperty() {
if(_prop == null && _type != null) {
for (JAXBProperty prop: _type.getWrapperChildren()){
if(prop.getElementName().equals(_name))
setProperty(prop);
}
}
return _prop;
}
public void setProperty(JAXBProperty prop) {
_prop = prop;
}
private QName _name;
private JAXBType _type;
private JavaStructureMember _javaStructureMember;
private boolean _repeated;
private boolean isInherited = false;
private JAXBProperty _prop;
private static final String JAXB_UNIQUE_PARRAM = "__jaxbUniqueParam_";
}

View File

@@ -0,0 +1,101 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.xjc.api.Mapping;
import com.sun.tools.internal.xjc.api.Property;
import com.sun.tools.internal.xjc.api.TypeAndAnnotation;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kohsuke Kawaguchi, Vivek Pandey
*/
public class JAXBMapping {
/**
* @see Mapping#getElement()
*/
private QName elementName;
/**
*
*/
private JAXBTypeAndAnnotation type;
/**
* @see Mapping#getWrapperStyleDrilldown()
*/
private List<JAXBProperty> wrapperStyleDrilldown;
/**
* Default constructor for the persistence.
*/
public JAXBMapping() {}
/**
* Constructor that fills in the values from the given raw model
*/
JAXBMapping( com.sun.tools.internal.xjc.api.Mapping rawModel ) {
elementName = rawModel.getElement();
TypeAndAnnotation typeAndAnno = rawModel.getType();
type = new JAXBTypeAndAnnotation(typeAndAnno);
List<? extends Property> list = rawModel.getWrapperStyleDrilldown();
if(list==null)
wrapperStyleDrilldown = null;
else {
wrapperStyleDrilldown = new ArrayList<JAXBProperty>(list.size());
for( Property p : list )
wrapperStyleDrilldown.add(new JAXBProperty(p));
}
}
/**
* @see Mapping#getElement()
*/
public QName getElementName() {
return elementName;
}
public void setElementName(QName elementName) {
this.elementName = elementName;
}
public JAXBTypeAndAnnotation getType() {
return type;
}
/**
* @see Mapping#getWrapperStyleDrilldown()
*/
public List<JAXBProperty> getWrapperStyleDrilldown() {
return wrapperStyleDrilldown;
}
}

View File

@@ -0,0 +1,141 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.xjc.api.J2SJAXBModel;
import com.sun.tools.internal.xjc.api.Mapping;
import com.sun.tools.internal.xjc.api.S2JJAXBModel;
import javax.xml.namespace.QName;
import java.util.*;
/**
* Root of the JAXB Model.
*
* <p>
* This is just a wrapper around a list of {@link JAXBMapping}s.
*
* @author Kohsuke Kawaguchi, Vivek Pandey
*/
public class JAXBModel {
/**
* All the mappings known to this model.
*/
private List<JAXBMapping> mappings;
// index for faster access.
private final Map<QName,JAXBMapping> byQName = new HashMap<QName,JAXBMapping>();
private final Map<String,JAXBMapping> byClassName = new HashMap<String,JAXBMapping>();
private com.sun.tools.internal.xjc.api.JAXBModel rawJAXBModel;
public com.sun.tools.internal.xjc.api.JAXBModel getRawJAXBModel() {
return rawJAXBModel;
}
/**
* @return Schema to Java model
*/
public S2JJAXBModel getS2JJAXBModel(){
if(rawJAXBModel instanceof S2JJAXBModel)
return (S2JJAXBModel)rawJAXBModel;
return null;
}
/**
* @return Java to Schema JAXBModel
*/
public J2SJAXBModel getJ2SJAXBModel(){
if(rawJAXBModel instanceof J2SJAXBModel)
return (J2SJAXBModel)rawJAXBModel;
return null;
}
/**
* Default constructor for the persistence.
*/
public JAXBModel() {}
/**
* Constructor that fills in the values from the given raw model
*/
public JAXBModel( com.sun.tools.internal.xjc.api.JAXBModel rawModel ) {
this.rawJAXBModel = rawModel;
if(rawModel instanceof S2JJAXBModel){
S2JJAXBModel model = (S2JJAXBModel)rawModel;
List<JAXBMapping> ms = new ArrayList<JAXBMapping>(model.getMappings().size());
for( Mapping m : model.getMappings())
ms.add(new JAXBMapping(m));
setMappings(ms);
}
}
/**
*/
public List<JAXBMapping> getMappings() {
return mappings;
}
//public void setMappings(List<JAXBMapping> mappings) {
public void setMappings(List<JAXBMapping> mappings) {
this.mappings = mappings;
byQName.clear();
byClassName.clear();
for( JAXBMapping m : mappings ) {
byQName.put(m.getElementName(),m);
byClassName.put(m.getType().getName(),m);
}
}
/**
*/
public JAXBMapping get( QName elementName ) {
return byQName.get(elementName);
}
/**
*/
public JAXBMapping get( String className ) {
return byClassName.get(className);
}
/**
*
* @return set of full qualified class names that jaxb will generate
*/
public Set<String> getGeneratedClassNames() {
return generatedClassNames;
}
public void setGeneratedClassNames(Set<String> generatedClassNames) {
this.generatedClassNames = generatedClassNames;
}
private Set<String> generatedClassNames;
}

View File

@@ -0,0 +1,93 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.xjc.api.Property;
import javax.xml.namespace.QName;
/**
* @author Kohsuke Kawaguchi
*/
public class JAXBProperty {
/**
* @see Property#name()
*/
private String name;
private JAXBTypeAndAnnotation type;
/**
* @see Property#elementName()
*/
private QName elementName;
/**
* @see Property#rawName()
*/
private QName rawTypeName;
/**
* Default constructor for the persistence.
*/
public JAXBProperty() {}
/**
* Constructor that fills in the values from the given raw model
*/
JAXBProperty( Property prop ) {
this.name = prop.name();
this.type = new JAXBTypeAndAnnotation(prop.type());
this.elementName = prop.elementName();
this.rawTypeName = prop.rawName();
}
/**
* @see Property#name()
*/
public String getName() {
return name;
}
public QName getRawTypeName() {
return rawTypeName;
}
public void setName(String name) {
this.name = name;
}
public JAXBTypeAndAnnotation getType() {
return type;
}
/**
* @see Property#elementName()
*/
public QName getElementName() {
return elementName;
}
}

View File

@@ -0,0 +1,138 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.ws.processor.model.ModelException;
import com.sun.tools.internal.ws.processor.model.java.JavaStructureType;
import javax.xml.namespace.QName;
import java.util.*;
/**
* Top-level binding between JAXB generated Java type
* and XML Schema element declaration.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class JAXBStructuredType extends JAXBType {
public JAXBStructuredType(JAXBType jaxbType){
super(jaxbType);
}
public JAXBStructuredType() {}
public JAXBStructuredType(QName name) {
this(name, null);
}
public JAXBStructuredType(QName name, JavaStructureType javaType) {
super(name, javaType);
}
public void add(JAXBElementMember m) {
if (_elementMembersByName.containsKey(m.getName())) {
throw new ModelException("model.uniqueness");
}
_elementMembers.add(m);
if (m.getName() != null) {
_elementMembersByName.put(m.getName().getLocalPart(), m);
}
}
public Iterator getElementMembers() {
return _elementMembers.iterator();
}
public int getElementMembersCount() {
return _elementMembers.size();
}
/* serialization */
public List getElementMembersList() {
return _elementMembers;
}
/* serialization */
public void setElementMembersList(List l) {
_elementMembers = l;
}
public void addSubtype(JAXBStructuredType type) {
if (_subtypes == null) {
_subtypes = new HashSet();
}
_subtypes.add(type);
type.setParentType(this);
}
public Iterator getSubtypes() {
if (_subtypes != null) {
return _subtypes.iterator();
}
return null;
}
/* (non-Javadoc)
* @see JAXBType#isUnwrapped()
*/
public boolean isUnwrapped() {
return true;
}
/* serialization */
public Set getSubtypesSet() {
return _subtypes;
}
/* serialization */
public void setSubtypesSet(Set s) {
_subtypes = s;
}
public void setParentType(JAXBStructuredType parent) {
if (_parentType != null &&
parent != null &&
!_parentType.equals(parent)) {
throw new ModelException("model.parent.type.already.set",
new Object[] { getName().toString(),
_parentType.getName().toString(),
parent.getName().toString()});
}
this._parentType = parent;
}
public JAXBStructuredType getParentType() {
return _parentType;
}
private List _elementMembers = new ArrayList();
private Map _elementMembersByName = new HashMap();
private Set _subtypes = null;
private JAXBStructuredType _parentType = null;
}

View File

@@ -0,0 +1,124 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.ws.processor.model.AbstractType;
import com.sun.tools.internal.ws.processor.model.java.JavaType;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
/**
* Top-level binding between JAXB generated Java type
* and XML Schema element declaration.
*
* @author
* Vivek Pandey
*/
public class JAXBType extends AbstractType{
public JAXBType(JAXBType jaxbType){
setName(jaxbType.getName());
this.jaxbMapping = jaxbType.getJaxbMapping();
this.jaxbModel = jaxbType.getJaxbModel();
init();
}
public JAXBType(){}
public JAXBType(QName name, JavaType type){
super(name, type);
}
public JAXBType(QName name, JavaType type, JAXBMapping jaxbMapping, JAXBModel jaxbModel){
super(name, type);
this.jaxbMapping = jaxbMapping;
this.jaxbModel = jaxbModel;
init();
}
public void accept(JAXBTypeVisitor visitor) throws Exception {
visitor.visit(this);
}
private void init() {
if (jaxbMapping != null)
wrapperChildren = jaxbMapping.getWrapperStyleDrilldown();
else
wrapperChildren = new ArrayList<JAXBProperty>();
}
public boolean isUnwrappable(){
return jaxbMapping != null && jaxbMapping.getWrapperStyleDrilldown() != null;
}
public boolean hasWrapperChildren(){
return wrapperChildren.size() > 0;
}
public boolean isLiteralType() {
return true;
}
public List<JAXBProperty> getWrapperChildren(){
return wrapperChildren;
}
public void setWrapperChildren(List<JAXBProperty> children) {
wrapperChildren = children;
}
public JAXBMapping getJaxbMapping() {
return jaxbMapping;
}
public void setJaxbMapping(JAXBMapping jaxbMapping) {
this.jaxbMapping = jaxbMapping;
init();
}
public void setUnwrapped(boolean unwrapped) {
this.unwrapped = unwrapped;
}
public boolean isUnwrapped() {
return unwrapped;
}
private JAXBMapping jaxbMapping;
public JAXBModel getJaxbModel() {
return jaxbModel;
}
public void setJaxbModel(JAXBModel jaxbModel) {
this.jaxbModel = jaxbModel;
}
private JAXBModel jaxbModel;
private boolean unwrapped = false;
private List<JAXBProperty> wrapperChildren;
}

View File

@@ -0,0 +1,78 @@
/*
* 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.processor.model.jaxb;
import com.sun.codemodel.internal.JAnnotatable;
import com.sun.codemodel.internal.JType;
import com.sun.tools.internal.xjc.api.TypeAndAnnotation;
/**
* Holds JAXB JType and TypeAndAnnotation. This provides abstration over
* types from JAXBMapping and Property.
*/
public class JAXBTypeAndAnnotation {
TypeAndAnnotation typeAnn;
JType type;
public JAXBTypeAndAnnotation(TypeAndAnnotation typeAnn) {
this.typeAnn = typeAnn;
this.type = typeAnn.getTypeClass();
}
public JAXBTypeAndAnnotation(JType type) {
this.type = type;
}
public JAXBTypeAndAnnotation(TypeAndAnnotation typeAnn, JType type) {
this.typeAnn = typeAnn;
this.type = type;
}
public void annotate(JAnnotatable typeVar) {
if(typeAnn != null)
typeAnn.annotate(typeVar);
}
public JType getType() {
return type;
}
public String getName(){
return type.fullName();
}
public TypeAndAnnotation getTypeAnn() {
return typeAnn;
}
public void setTypeAnn(TypeAndAnnotation typeAnn) {
this.typeAnn = typeAnn;
}
public void setType(JType type) {
this.type = type;
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.processor.model.jaxb;
/**
* @author Vivek Pandey
*
* To change the template for this generated type comment go to
* Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
*/
public interface JAXBTypeVisitor {
public void visit(JAXBType type) throws Exception;
public void visit(RpcLitStructure type) throws Exception;
}

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.processor.model.jaxb;
import com.sun.tools.internal.ws.processor.model.AbstractType;
import javax.xml.namespace.QName;
/**
* @author Vivek Pandey
*
* Represents RpcLit member parts
*/
public class RpcLitMember extends AbstractType {
//wsdl:part type attribute java mapped object
private String javaTypeName;
private QName schemaTypeName;
/**
*
*/
public RpcLitMember() {
super();
// TODO Auto-generated constructor stub
}
public RpcLitMember(QName name, String javaTypeName){
setName(name);
this.javaTypeName = javaTypeName;
}
public RpcLitMember(QName name, String javaTypeName, QName schemaTypeName){
setName(name);
this.javaTypeName = javaTypeName;
this.schemaTypeName = schemaTypeName;
}
/**
* @return Returns the type.
*/
public String getJavaTypeName() {
return javaTypeName;
}
/**
* @param type The type to set.
*/
public void setJavaTypeName(String type) {
this.javaTypeName = type;
}
/**
* @return Returns the type.
*/
public QName getSchemaTypeName() {
return schemaTypeName;
}
/**
* @param type The type to set.
*/
public void setSchemaTypeName(QName type) {
this.schemaTypeName = type;
}
}

View File

@@ -0,0 +1,92 @@
/*
* 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.processor.model.jaxb;
import com.sun.tools.internal.ws.processor.model.AbstractType;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
/**
* @author Vivek Pandey
*
* RPC Structure that will be used to create RpcLitPayload latter
*/
public class RpcLitStructure extends AbstractType {
private List<RpcLitMember> members;
private JAXBModel jaxbModel;
/**
*
*/
public RpcLitStructure() {
super();
// TODO Auto-generated constructor stub
}
public RpcLitStructure(QName name, JAXBModel jaxbModel){
setName(name);
this.jaxbModel = jaxbModel;
this.members = new ArrayList<RpcLitMember>();
}
public RpcLitStructure(QName name, JAXBModel jaxbModel, List<RpcLitMember> members){
setName(name);
this.members = members;
}
public void accept(JAXBTypeVisitor visitor) throws Exception {
visitor.visit(this);
}
public List<RpcLitMember> getRpcLitMembers(){
return members;
}
public List<RpcLitMember> setRpcLitMembers(List<RpcLitMember> members){
return this.members = members;
}
public void addRpcLitMember(RpcLitMember member){
members.add(member);
}
/**
* @return Returns the jaxbModel.
*/
public JAXBModel getJaxbModel() {
return jaxbModel;
}
/**
* @param jaxbModel The jaxbModel to set.
*/
public void setJaxbModel(JAXBModel jaxbModel) {
this.jaxbModel = jaxbModel;
}
public boolean isLiteralType() {
return true;
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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.processor.model.jaxb;
/**
* @author Kohsuke Kawaguchi
*/
class Util {
/**
* Replaces the marcros in the first string by the actual given arguments.
*/
static String replace( String macro, String... args ) {
int len = macro.length();
StringBuilder buf = new StringBuilder(len);
for( int i=0; i<len; i++ ) {
char ch = macro.charAt(i);
if(ch=='=' && i+2<len) {
char tail = macro.charAt(i+1);
char ch2 = macro.charAt(i+2);
if('0'<=ch2 && ch2<='9' && tail==':') {
buf.append(args[ch2-'0']);
i+=2;
continue;
}
}
buf.append(ch);
}
return buf.toString();
}
/**
* Creates a macro tempate so that it can be later used with {@link #replace(String, String[])}.
*/
static String createMacroTemplate( String s ) {
return s;
}
static final String MAGIC = "=:";
static final String MAGIC0 = MAGIC+"0";
static final String MAGIC1 = MAGIC+"1";
static final String MAGIC2 = MAGIC+"2";
}

View File

@@ -0,0 +1,121 @@
/*
* 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.processor.modeler;
import com.sun.tools.internal.ws.processor.model.java.JavaSimpleType;
import java.util.HashMap;
import java.util.Map;
import static com.sun.tools.internal.ws.processor.modeler.ModelerConstants.*;
/**
*
* @author WS Development Team
*/
public final class JavaSimpleTypeCreator {
/*
* Mapped JavaSimpleTypes
*/
public static final JavaSimpleType BOOLEAN_JAVATYPE = new JavaSimpleType(BOOLEAN_CLASSNAME.getValue(), FALSE_STR.getValue());
public static final JavaSimpleType BOXED_BOOLEAN_JAVATYPE = new JavaSimpleType(BOXED_BOOLEAN_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType BYTE_JAVATYPE = new JavaSimpleType(BYTE_CLASSNAME.getValue(), "(byte)" + ZERO_STR.getValue());
public static final JavaSimpleType BYTE_ARRAY_JAVATYPE = new JavaSimpleType(BYTE_ARRAY_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType BOXED_BYTE_JAVATYPE = new JavaSimpleType(BOXED_BYTE_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType BOXED_BYTE_ARRAY_JAVATYPE = new JavaSimpleType(BOXED_BYTE_ARRAY_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType DOUBLE_JAVATYPE = new JavaSimpleType(DOUBLE_CLASSNAME.getValue(), ZERO_STR.getValue());
public static final JavaSimpleType BOXED_DOUBLE_JAVATYPE = new JavaSimpleType(BOXED_DOUBLE_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType FLOAT_JAVATYPE = new JavaSimpleType(FLOAT_CLASSNAME.getValue(), ZERO_STR.getValue());
public static final JavaSimpleType BOXED_FLOAT_JAVATYPE = new JavaSimpleType(BOXED_FLOAT_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType INT_JAVATYPE = new JavaSimpleType(INT_CLASSNAME.getValue(), ZERO_STR.getValue());
public static final JavaSimpleType BOXED_INTEGER_JAVATYPE = new JavaSimpleType(BOXED_INTEGER_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType LONG_JAVATYPE = new JavaSimpleType(LONG_CLASSNAME.getValue(), ZERO_STR.getValue());
public static final JavaSimpleType BOXED_LONG_JAVATYPE = new JavaSimpleType(BOXED_LONG_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType SHORT_JAVATYPE = new JavaSimpleType(SHORT_CLASSNAME.getValue(), "(short)" + ZERO_STR.getValue());
public static final JavaSimpleType BOXED_SHORT_JAVATYPE = new JavaSimpleType(BOXED_SHORT_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType DECIMAL_JAVATYPE = new JavaSimpleType(BIGDECIMAL_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType BIG_INTEGER_JAVATYPE = new JavaSimpleType(BIGINTEGER_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType CALENDAR_JAVATYPE = new JavaSimpleType(CALENDAR_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType DATE_JAVATYPE = new JavaSimpleType(DATE_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType STRING_JAVATYPE = new JavaSimpleType(STRING_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType STRING_ARRAY_JAVATYPE = new JavaSimpleType(STRING_ARRAY_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType QNAME_JAVATYPE = new JavaSimpleType(QNAME_CLASSNAME.getValue(), NULL_STR.getValue());
public static final JavaSimpleType VOID_JAVATYPE = new JavaSimpleType(VOID_CLASSNAME.getValue(), null);
public static final JavaSimpleType OBJECT_JAVATYPE = new JavaSimpleType(OBJECT_CLASSNAME.getValue(), null);
public static final JavaSimpleType SOAPELEMENT_JAVATYPE = new JavaSimpleType(SOAPELEMENT_CLASSNAME.getValue(), null);
public static final JavaSimpleType URI_JAVATYPE = new JavaSimpleType(URI_CLASSNAME.getValue(), null);
// Attachment types
public static final JavaSimpleType IMAGE_JAVATYPE = new JavaSimpleType(IMAGE_CLASSNAME.getValue(), null);
public static final JavaSimpleType MIME_MULTIPART_JAVATYPE = new JavaSimpleType(MIME_MULTIPART_CLASSNAME.getValue(), null);
public static final JavaSimpleType SOURCE_JAVATYPE = new JavaSimpleType(SOURCE_CLASSNAME.getValue(), null);
public static final JavaSimpleType DATA_HANDLER_JAVATYPE = new JavaSimpleType(DATA_HANDLER_CLASSNAME.getValue(), null);
// bug fix: 4923650
private static final Map<String, JavaSimpleType> JAVA_TYPES = new HashMap<String, JavaSimpleType>(31);
static {
JAVA_TYPES.put(BOOLEAN_CLASSNAME.getValue(), BOOLEAN_JAVATYPE);
JAVA_TYPES.put(BOXED_BOOLEAN_CLASSNAME.getValue(), BOXED_BOOLEAN_JAVATYPE);
JAVA_TYPES.put(BYTE_CLASSNAME.getValue(), BYTE_JAVATYPE);
JAVA_TYPES.put(BYTE_ARRAY_CLASSNAME.getValue(), BYTE_ARRAY_JAVATYPE);
JAVA_TYPES.put(BOXED_BYTE_CLASSNAME.getValue(), BOXED_BYTE_JAVATYPE);
JAVA_TYPES.put(BOXED_BYTE_ARRAY_CLASSNAME.getValue(), BOXED_BYTE_ARRAY_JAVATYPE);
JAVA_TYPES.put(DOUBLE_CLASSNAME.getValue(), DOUBLE_JAVATYPE);
JAVA_TYPES.put(BOXED_DOUBLE_CLASSNAME.getValue(), BOXED_DOUBLE_JAVATYPE);
JAVA_TYPES.put(FLOAT_CLASSNAME.getValue(), FLOAT_JAVATYPE);
JAVA_TYPES.put(BOXED_FLOAT_CLASSNAME.getValue(), BOXED_FLOAT_JAVATYPE);
JAVA_TYPES.put(INT_CLASSNAME.getValue(), INT_JAVATYPE);
JAVA_TYPES.put(BOXED_INTEGER_CLASSNAME.getValue(), BOXED_INTEGER_JAVATYPE);
JAVA_TYPES.put(LONG_CLASSNAME.getValue(), LONG_JAVATYPE);
JAVA_TYPES.put(BOXED_LONG_CLASSNAME.getValue(), BOXED_LONG_JAVATYPE);
JAVA_TYPES.put(SHORT_CLASSNAME.getValue(), SHORT_JAVATYPE);
JAVA_TYPES.put(BOXED_SHORT_CLASSNAME.getValue(), BOXED_SHORT_JAVATYPE);
JAVA_TYPES.put(BIGDECIMAL_CLASSNAME.getValue(), DECIMAL_JAVATYPE);
JAVA_TYPES.put(BIGINTEGER_CLASSNAME.getValue(), BIG_INTEGER_JAVATYPE);
JAVA_TYPES.put(CALENDAR_CLASSNAME.getValue(), CALENDAR_JAVATYPE);
JAVA_TYPES.put(DATE_CLASSNAME.getValue(), DATE_JAVATYPE);
JAVA_TYPES.put(STRING_CLASSNAME.getValue(), STRING_JAVATYPE);
JAVA_TYPES.put(STRING_ARRAY_CLASSNAME.getValue(), STRING_ARRAY_JAVATYPE);
JAVA_TYPES.put(QNAME_CLASSNAME.getValue(), QNAME_JAVATYPE);
JAVA_TYPES.put(VOID_CLASSNAME.getValue(), VOID_JAVATYPE);
JAVA_TYPES.put(OBJECT_CLASSNAME.getValue(), OBJECT_JAVATYPE);
JAVA_TYPES.put(SOAPELEMENT_CLASSNAME.getValue(), SOAPELEMENT_JAVATYPE);
JAVA_TYPES.put(URI_CLASSNAME.getValue(), URI_JAVATYPE);
JAVA_TYPES.put(IMAGE_CLASSNAME.getValue(), IMAGE_JAVATYPE);
JAVA_TYPES.put(MIME_MULTIPART_CLASSNAME.getValue(), MIME_MULTIPART_JAVATYPE);
JAVA_TYPES.put(SOURCE_CLASSNAME.getValue(), SOURCE_JAVATYPE);
JAVA_TYPES.put(DATA_HANDLER_CLASSNAME.getValue(), DATA_HANDLER_JAVATYPE);
}
private JavaSimpleTypeCreator() {
}
// bug fix: 4923650
public static JavaSimpleType getJavaSimpleType(String className) {
return JAVA_TYPES.get(className);
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.processor.modeler;
import com.sun.tools.internal.ws.processor.model.Model;
/**
* A Modeler is used to create a Model of a Web Service from a particular Web
* Web Service description such as a WSDL
*
* @author WS Development Team
*/
public interface Modeler {
/**
* Returns the top model of a Web Service. May throw a
* ModelException if there is a problem with the model.
*
* @return Model - the root Node of the model of the Web Service
*
* @exception ModelerException
*/
public Model buildModel();
}

View File

@@ -0,0 +1,111 @@
/*
* 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.processor.modeler;
/**
*
* @author WS Development Team
*/
public enum ModelerConstants {
FALSE_STR("false"),
ZERO_STR("0"),
NULL_STR("null"),
ARRAY_STR("Array"),
/*
* Java ClassNames
*/
/*
* Java ClassNames
*/
IOEXCEPTION_CLASSNAME("java.io.IOException"),
BOOLEAN_CLASSNAME("boolean"),
BOXED_BOOLEAN_CLASSNAME("java.lang.Boolean"),
BYTE_CLASSNAME("byte"),
BYTE_ARRAY_CLASSNAME("byte[]"),
BOXED_BYTE_CLASSNAME("java.lang.Byte"),
BOXED_BYTE_ARRAY_CLASSNAME("java.lang.Byte[]"),
CLASS_CLASSNAME("java.lang.Class"),
CHAR_CLASSNAME("char"),
BOXED_CHAR_CLASSNAME("java.lang.Character"),
DOUBLE_CLASSNAME("double"),
BOXED_DOUBLE_CLASSNAME("java.lang.Double"),
FLOAT_CLASSNAME("float"),
BOXED_FLOAT_CLASSNAME("java.lang.Float"),
INT_CLASSNAME("int"),
BOXED_INTEGER_CLASSNAME("java.lang.Integer"),
LONG_CLASSNAME("long"),
BOXED_LONG_CLASSNAME("java.lang.Long"),
SHORT_CLASSNAME("short"),
BOXED_SHORT_CLASSNAME("java.lang.Short"),
BIGDECIMAL_CLASSNAME("java.math.BigDecimal"),
BIGINTEGER_CLASSNAME("java.math.BigInteger"),
CALENDAR_CLASSNAME("java.util.Calendar"),
DATE_CLASSNAME("java.util.Date"),
STRING_CLASSNAME("java.lang.String"),
STRING_ARRAY_CLASSNAME("java.lang.String[]"),
QNAME_CLASSNAME("javax.xml.namespace.QName"),
VOID_CLASSNAME("void"),
OBJECT_CLASSNAME("java.lang.Object"),
SOAPELEMENT_CLASSNAME("javax.xml.soap.SOAPElement"),
IMAGE_CLASSNAME("java.awt.Image"),
MIME_MULTIPART_CLASSNAME("javax.mail.internet.MimeMultipart"),
SOURCE_CLASSNAME("javax.xml.transform.Source"),
DATA_HANDLER_CLASSNAME("javax.activation.DataHandler"),
URI_CLASSNAME("java.net.URI"),
// URI_CLASSNAME ("java.lang.String"),
// Collections
COLLECTION_CLASSNAME("java.util.Collection"),
LIST_CLASSNAME("java.util.List"),
SET_CLASSNAME("java.util.Set"),
VECTOR_CLASSNAME("java.util.Vector"),
STACK_CLASSNAME("java.util.Stack"),
LINKED_LIST_CLASSNAME("java.util.LinkedList"),
ARRAY_LIST_CLASSNAME("java.util.ArrayList"),
HASH_SET_CLASSNAME("java.util.HashSet"),
TREE_SET_CLASSNAME("java.util.TreeSet"),
// Maps
MAP_CLASSNAME("java.util.Map"),
HASH_MAP_CLASSNAME("java.util.HashMap"),
TREE_MAP_CLASSNAME("java.util.TreeMap"),
HASHTABLE_CLASSNAME("java.util.Hashtable"),
PROPERTIES_CLASSNAME("java.util.Properties"),
// WEAK_HASH_MAP_CLASSNAME ("java.util.WeakHashMap"),
JAX_WS_MAP_ENTRY_CLASSNAME("com.sun.xml.internal.ws.encoding.soap.JAXWSMapEntry");
private String value;
private ModelerConstants(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,61 @@
/*
* 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.processor.modeler;
import com.sun.istack.internal.localization.Localizable;
import com.sun.tools.internal.ws.processor.ProcessorException;
/**
* ModelerException represents an exception that occurred while
* visiting service model.
*
* @see ProcessorException
*
* @author WS Development Team
*/
public class ModelerException extends ProcessorException {
public ModelerException(String key) {
super(key);
}
public ModelerException(String key, Object... args) {
super(key, args);
}
public ModelerException(Throwable throwable) {
super(throwable);
}
public ModelerException(Localizable arg) {
super("modeler.nestedModelError", arg);
}
public String getDefaultResourceBundleName() {
return "com.sun.tools.internal.ws.resources.modeler";
}
}

View File

@@ -0,0 +1,181 @@
/*
* 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.processor.modeler.annotation;
import com.sun.tools.internal.ws.processor.model.Model;
import com.sun.tools.internal.ws.processor.model.Operation;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.processor.model.Service;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPUse;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author dkohlert
*/
public class AnnotationProcessorContext {
private Map<Name, SeiContext> seiContextMap = new HashMap<Name, SeiContext>();
private int round = 1;
private boolean modelCompleted = false;
public void addSeiContext(Name seiName, SeiContext seiContext) {
seiContextMap.put(seiName, seiContext);
}
public SeiContext getSeiContext(Name seiName) {
SeiContext context = seiContextMap.get(seiName);
if (context == null) {
context = new SeiContext();
addSeiContext(seiName, context);
}
return context;
}
public SeiContext getSeiContext(TypeElement d) {
return getSeiContext(d.getQualifiedName());
}
public Collection<SeiContext> getSeiContexts() {
return seiContextMap.values();
}
public int getRound() {
return round;
}
public void incrementRound() {
round++;
}
public static boolean isEncoded(Model model) {
if (model == null)
return false;
for (Service service : model.getServices()) {
for (Port port : service.getPorts()) {
for (Operation operation : port.getOperations()) {
if (operation.getUse() != null && operation.getUse().equals(SOAPUse.LITERAL))
return false;
}
}
}
return true;
}
public void setModelCompleted(boolean modelCompleted) {
this.modelCompleted = modelCompleted;
}
public boolean isModelCompleted() {
return modelCompleted;
}
public static class SeiContext {
private Map<String, WrapperInfo> reqOperationWrapperMap = new HashMap<String, WrapperInfo>();
private Map<String, WrapperInfo> resOperationWrapperMap = new HashMap<String, WrapperInfo>();
private Map<Name, FaultInfo> exceptionBeanMap = new HashMap<Name, FaultInfo>();
private Name seiImplName;
private boolean implementsSei;
private String namespaceUri;
public SeiContext() {};
/**
* @deprecated use empty constructor, seiName value is ignored
* @param seiName
*/
public SeiContext(Name seiName) {};
public void setImplementsSei(boolean implementsSei) {
this.implementsSei = implementsSei;
}
public boolean getImplementsSei() {
return implementsSei;
}
public void setNamespaceUri(String namespaceUri) {
this.namespaceUri = namespaceUri;
}
public String getNamespaceUri() {
return namespaceUri;
}
public Name getSeiImplName() {
return seiImplName;
}
public void setSeiImplName(Name implName) {
seiImplName = implName;
}
public void setReqWrapperOperation(ExecutableElement method, WrapperInfo wrapperInfo) {
reqOperationWrapperMap.put(methodToString(method), wrapperInfo);
}
public WrapperInfo getReqOperationWrapper(ExecutableElement method) {
return reqOperationWrapperMap.get(methodToString(method));
}
public void setResWrapperOperation(ExecutableElement method, WrapperInfo wrapperInfo) {
resOperationWrapperMap.put(methodToString(method), wrapperInfo);
}
public WrapperInfo getResOperationWrapper(ExecutableElement method) {
return resOperationWrapperMap.get(methodToString(method));
}
public String methodToString(ExecutableElement method) {
StringBuilder buf = new StringBuilder(method.getSimpleName());
for (VariableElement param : method.getParameters())
buf.append(';').append(param.asType());
return buf.toString();
}
public void clearExceptionMap() {
exceptionBeanMap.clear();
}
public void addExceptionBeanEntry(Name exception, FaultInfo faultInfo, ModelBuilder builder) {
exceptionBeanMap.put(exception, faultInfo);
}
public FaultInfo getExceptionBeanName(Name exception) {
return exceptionBeanMap.get(exception);
}
}
}

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.processor.modeler.annotation;
import javax.xml.namespace.QName;
/**
*
* @author dkohlert
*/
public class FaultInfo {
public String beanName;
public TypeMoniker beanTypeMoniker;
public boolean isWsdlException;
public QName elementName;
/** Creates a new instance of FaultInfo */
public FaultInfo() {
}
public FaultInfo(String beanName) {
this.beanName = beanName;
}
public FaultInfo(String beanName, boolean isWsdlException) {
this.beanName = beanName;
this.isWsdlException = isWsdlException;
}
public FaultInfo(TypeMoniker typeMoniker, boolean isWsdlException) {
this.beanTypeMoniker = typeMoniker;
this.isWsdlException = isWsdlException;
}
public void setIsWsdlException(boolean isWsdlException) {
this.isWsdlException = isWsdlException;
}
public boolean isWsdlException() {
return isWsdlException;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setElementName(QName elementName) {
this.elementName = elementName;
}
public QName getElementName() {
return elementName;
}
public void setBeanTypeMoniker(TypeMoniker typeMoniker) {
this.beanTypeMoniker = typeMoniker;
}
public TypeMoniker getBeanTypeMoniker() {
return beanTypeMoniker;
}
}

View File

@@ -0,0 +1,78 @@
/*
* 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.processor.modeler.annotation;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.SimpleTypeVisitor6;
import javax.lang.model.util.Types;
import java.util.Collection;
import java.util.Map;
/**
*
* @author dkohlert
*/
public class MakeSafeTypeVisitor extends SimpleTypeVisitor6<TypeMirror, Types> {
TypeElement collectionType;
TypeElement mapType;
/**
* Creates a new instance of MakeSafeTypeVisitor
*/
public MakeSafeTypeVisitor(ProcessingEnvironment processingEnvironment) {
collectionType = processingEnvironment.getElementUtils().getTypeElement(Collection.class.getName());
mapType = processingEnvironment.getElementUtils().getTypeElement(Map.class.getName());
}
@Override
public TypeMirror visitDeclared(DeclaredType t, Types types) {
if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType)
|| TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) {
Collection<? extends TypeMirror> args = t.getTypeArguments();
TypeMirror[] safeArgs = new TypeMirror[args.size()];
int i = 0;
for (TypeMirror arg : args) {
safeArgs[i++] = visit(arg, types);
}
return types.getDeclaredType((TypeElement) t.asElement(), safeArgs);
}
return types.erasure(t);
}
@Override
public TypeMirror visitNoType(NoType type, Types types) {
return type;
}
@Override
protected TypeMirror defaultAction(TypeMirror e, Types types) {
return types.erasure(e);
}
}

View File

@@ -0,0 +1,79 @@
/*
* 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.processor.modeler.annotation;
import javax.lang.model.type.TypeMirror;
import java.lang.annotation.Annotation;
import java.util.List;
/**
* Note: this class has a natural ordering that is inconsistent with equals.
* @author WS Development Team
*/
final class MemberInfo implements Comparable<MemberInfo> {
private final TypeMirror paramType;
private final String paramName;
private final List<Annotation> jaxbAnnotations;
public MemberInfo(TypeMirror paramType, String paramName, List<Annotation> jaxbAnnotations) {
this.paramType = paramType;
this.paramName = paramName;
this.jaxbAnnotations = jaxbAnnotations;
}
public List<Annotation> getJaxbAnnotations() {
return jaxbAnnotations;
}
public TypeMirror getParamType() {
return paramType;
}
public String getParamName() {
return paramName;
}
@Override
public int compareTo(MemberInfo member) {
return paramName.compareTo(member.paramName);
}
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + (this.paramType != null ? this.paramType.hashCode() : 0);
hash = 47 * hash + (this.paramName != null ? this.paramName.hashCode() : 0);
hash = 47 * hash + (this.jaxbAnnotations != null ? this.jaxbAnnotations.hashCode() : 0);
return hash;
}
}

View File

@@ -0,0 +1,74 @@
/*
* 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.processor.modeler.annotation;
import com.sun.tools.internal.ws.processor.modeler.ModelerException;
import com.sun.tools.internal.ws.wscompile.WsgenOptions;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import java.io.File;
/**
* @author WS Development Team
*/
public interface ModelBuilder {
ProcessingEnvironment getProcessingEnvironment();
String getOperationName(Name methodName);
TypeMirror getHolderValueType(TypeMirror type);
boolean checkAndSetProcessed(TypeElement typeElement);
/**
* Checks if type is a service specific exception
*
* @param typeMirror the given element's type
* @return true if is not a service specific exception as defined by JAX-WS specification
*/
boolean isServiceException(TypeMirror typeMirror);
boolean isRemote(TypeElement typeElement);
boolean canOverWriteClass(String className);
WsgenOptions getOptions();
File getSourceDir();
void log(String msg);
void processWarning(String message);
void processError(String message);
void processError(String message, Element element) throws ModelerException;
}

View File

@@ -0,0 +1,163 @@
/*
* 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.processor.modeler.annotation;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import java.util.Collection;
/**
* @author WS Development Team
*/
final class TypeModeler {
private TypeModeler() {
}
public static TypeElement getDeclaration(TypeMirror typeMirror) {
if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED))
return (TypeElement) ((DeclaredType) typeMirror).asElement();
return null;
}
public static TypeElement getDeclaringClassMethod(TypeMirror theClass, String methodName, TypeMirror[] args) {
return getDeclaringClassMethod(getDeclaration(theClass), methodName, args);
}
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {
TypeElement retClass = null;
if (theClass.getKind().equals(ElementKind.CLASS)) {
TypeMirror superClass = theClass.getSuperclass();
if (!superClass.getKind().equals(TypeKind.NONE))
retClass = getDeclaringClassMethod(superClass, methodName, args);
}
if (retClass == null) {
for (TypeMirror interfaceType : theClass.getInterfaces()) {
retClass = getDeclaringClassMethod(interfaceType, methodName, args);
}
}
if (retClass == null) {
Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
for (ExecutableElement method : methods) {
if (method.getSimpleName().toString().equals(methodName)) {
retClass = theClass;
break;
}
}
}
return retClass;
}
public static Collection<DeclaredType> collectInterfaces(TypeElement type) {
@SuppressWarnings({"unchecked"})
Collection<DeclaredType> interfaces = (Collection<DeclaredType>) type.getInterfaces();
for (TypeMirror interfaceType : type.getInterfaces()) {
interfaces.addAll(collectInterfaces(getDeclaration(interfaceType)));
}
return interfaces;
}
public static boolean isSubclass(String subTypeName, String superTypeName, ProcessingEnvironment env) {
return isSubclass(env.getElementUtils().getTypeElement(subTypeName), env.getElementUtils().getTypeElement(superTypeName), env);
}
public static boolean isSubclass(TypeElement subType, TypeElement superType, ProcessingEnvironment env) {
return !subType.equals(superType) && isSubElement(subType, superType);
}
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
TypeElement typeElement = getDeclaration(type);
if (typeElement == null)
return null;
if (isSubElement(typeElement, defHolder)) {
if (type.getKind().equals(TypeKind.DECLARED)) {
Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
if (argTypes.size() == 1) {
return argTypes.iterator().next();
} else if (argTypes.isEmpty()) {
VariableElement member = getValueMember(typeElement);
if (member != null) {
return member.asType();
}
}
}
}
return null;
}
public static VariableElement getValueMember(TypeMirror classType) {
return getValueMember(getDeclaration(classType));
}
public static VariableElement getValueMember(TypeElement type) {
VariableElement member = null;
for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) {
if ("value".equals(field.getSimpleName().toString())) {
member = field;
break;
}
}
if (member == null && type.getKind().equals(ElementKind.CLASS))
member = getValueMember(type.getSuperclass());
return member;
}
public static boolean isSubElement(TypeElement d1, TypeElement d2) {
if (d1.equals(d2))
return true;
TypeElement superClassDecl = null;
if (d1.getKind().equals(ElementKind.CLASS)) {
TypeMirror superClass = d1.getSuperclass();
if (!superClass.getKind().equals(TypeKind.NONE)) {
superClassDecl = (TypeElement) ((DeclaredType) superClass).asElement();
if (superClassDecl.equals(d2))
return true;
}
}
for (TypeMirror superIntf : d1.getInterfaces()) {
DeclaredType declaredSuperIntf = (DeclaredType) superIntf;
if (declaredSuperIntf.asElement().equals(d2)) {
return true;
}
if (isSubElement((TypeElement) declaredSuperIntf.asElement(), d2)) {
return true;
} else if (superClassDecl != null && isSubElement(superClassDecl, d2)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,38 @@
/*
* 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.processor.modeler.annotation;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.TypeMirror;
/**
*
* @author dkohlert
*/
public interface TypeMoniker {
public TypeMirror create(ProcessingEnvironment apEnv);
}

View File

@@ -0,0 +1,114 @@
/*
* 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.processor.modeler.annotation;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author dkohlert
*/
public class TypeMonikerFactory {
public static TypeMoniker getTypeMoniker(TypeMirror typeMirror) {
if (typeMirror == null)
throw new NullPointerException();
if (typeMirror.getKind().isPrimitive())
return new PrimitiveTypeMoniker((PrimitiveType) typeMirror);
else if (typeMirror.getKind().equals(TypeKind.ARRAY))
return new ArrayTypeMoniker((ArrayType) typeMirror);
else if (typeMirror.getKind().equals(TypeKind.DECLARED))
return new DeclaredTypeMoniker((DeclaredType) typeMirror);
return getTypeMoniker(typeMirror.toString());
}
public static TypeMoniker getTypeMoniker(String typeName) {
return new StringMoniker(typeName);
}
static class ArrayTypeMoniker implements TypeMoniker {
private TypeMoniker arrayType;
public ArrayTypeMoniker(ArrayType type) {
arrayType = TypeMonikerFactory.getTypeMoniker(type.getComponentType());
}
public TypeMirror create(ProcessingEnvironment apEnv) {
return apEnv.getTypeUtils().getArrayType(arrayType.create(apEnv));
}
}
static class DeclaredTypeMoniker implements TypeMoniker {
private Name typeDeclName;
private Collection<TypeMoniker> typeArgs = new ArrayList<TypeMoniker>();
public DeclaredTypeMoniker(DeclaredType type) {
typeDeclName = ((TypeElement) type.asElement()).getQualifiedName();
for (TypeMirror arg : type.getTypeArguments())
typeArgs.add(TypeMonikerFactory.getTypeMoniker(arg));
}
public TypeMirror create(ProcessingEnvironment apEnv) {
TypeElement typeDecl = apEnv.getElementUtils().getTypeElement(typeDeclName);
TypeMirror[] tmpArgs = new TypeMirror[typeArgs.size()];
int idx = 0;
for (TypeMoniker moniker : typeArgs)
tmpArgs[idx++] = moniker.create(apEnv);
return apEnv.getTypeUtils().getDeclaredType(typeDecl, tmpArgs);
}
}
static class PrimitiveTypeMoniker implements TypeMoniker {
private TypeKind kind;
public PrimitiveTypeMoniker(PrimitiveType type) {
kind = type.getKind();
}
public TypeMirror create(ProcessingEnvironment apEnv) {
return apEnv.getTypeUtils().getPrimitiveType(kind);
}
}
static class StringMoniker implements TypeMoniker {
private String typeName;
public StringMoniker(String typeName) {
this.typeName = typeName;
}
public TypeMirror create(ProcessingEnvironment apEnv) {
return apEnv.getTypeUtils().getDeclaredType(apEnv.getElementUtils().getTypeElement(typeName));
}
}
}

View File

@@ -0,0 +1,363 @@
/*
* Copyright (c) 2010, 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.processor.modeler.annotation;
import com.sun.istack.internal.logging.Logger;
import com.sun.tools.internal.ws.processor.generator.GeneratorUtil;
import com.sun.tools.internal.ws.processor.modeler.ModelerException;
import com.sun.tools.internal.ws.resources.WebserviceapMessages;
import com.sun.tools.internal.ws.wscompile.AbortException;
import com.sun.tools.internal.ws.wscompile.WsgenOptions;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.jws.WebService;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceProvider;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
/**
* WebServiceAp is a AnnotationProcessor for processing javax.jws.* and
* javax.xml.ws.* annotations. This class is used either by the WsGen (CompileTool) tool or
* indirectly when invoked by javac.
*
* @author WS Development Team
*/
@SupportedAnnotationTypes({
"javax.jws.HandlerChain",
"javax.jws.Oneway",
"javax.jws.WebMethod",
"javax.jws.WebParam",
"javax.jws.WebResult",
"javax.jws.WebService",
"javax.jws.soap.InitParam",
"javax.jws.soap.SOAPBinding",
"javax.jws.soap.SOAPMessageHandler",
"javax.jws.soap.SOAPMessageHandlers",
"javax.xml.ws.BindingType",
"javax.xml.ws.RequestWrapper",
"javax.xml.ws.ResponseWrapper",
"javax.xml.ws.ServiceMode",
"javax.xml.ws.WebEndpoint",
"javax.xml.ws.WebFault",
"javax.xml.ws.WebServiceClient",
"javax.xml.ws.WebServiceProvider",
"javax.xml.ws.WebServiceRef"
})
@SupportedOptions({WebServiceAp.DO_NOT_OVERWRITE, WebServiceAp.IGNORE_NO_WEB_SERVICE_FOUND_WARNING})
public class WebServiceAp extends AbstractProcessor implements ModelBuilder {
private static final Logger LOGGER = Logger.getLogger(WebServiceAp.class);
public static final String DO_NOT_OVERWRITE = "doNotOverWrite";
public static final String IGNORE_NO_WEB_SERVICE_FOUND_WARNING = "ignoreNoWebServiceFoundWarning";
private WsgenOptions options;
protected AnnotationProcessorContext context;
private File sourceDir;
private boolean doNotOverWrite;
private boolean ignoreNoWebServiceFoundWarning = false;
private TypeElement remoteElement;
private TypeMirror remoteExceptionElement;
private TypeMirror exceptionElement;
private TypeMirror runtimeExceptionElement;
private TypeElement defHolderElement;
private boolean isCommandLineInvocation;
private PrintStream out;
private Collection<TypeElement> processedTypeElements = new HashSet<TypeElement>();
public WebServiceAp() {
this.context = new AnnotationProcessorContext();
}
public WebServiceAp(WsgenOptions options, PrintStream out) {
this.options = options;
this.sourceDir = (options != null) ? options.sourceDir : null;
this.doNotOverWrite = (options != null) && options.doNotOverWrite;
this.context = new AnnotationProcessorContext();
this.out = out;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
remoteElement = processingEnv.getElementUtils().getTypeElement(Remote.class.getName());
remoteExceptionElement = processingEnv.getElementUtils().getTypeElement(RemoteException.class.getName()).asType();
exceptionElement = processingEnv.getElementUtils().getTypeElement(Exception.class.getName()).asType();
runtimeExceptionElement = processingEnv.getElementUtils().getTypeElement(RuntimeException.class.getName()).asType();
defHolderElement = processingEnv.getElementUtils().getTypeElement(Holder.class.getName());
if (options == null) {
options = new WsgenOptions();
out = new PrintStream(new ByteArrayOutputStream());
doNotOverWrite = getOption(DO_NOT_OVERWRITE);
ignoreNoWebServiceFoundWarning = getOption(IGNORE_NO_WEB_SERVICE_FOUND_WARNING);
String classDir = parseArguments();
String property = System.getProperty("java.class.path");
options.classpath = classDir + File.pathSeparator + (property != null ? property : "");
isCommandLineInvocation = true;
}
options.filer = processingEnv.getFiler();
}
private String parseArguments() {
// let's try to parse JavacOptions
String classDir = null;
try {
ClassLoader cl = WebServiceAp.class.getClassLoader();
Class javacProcessingEnvironmentClass = Class.forName("com.sun.tools.javac.processing.JavacProcessingEnvironment", false, cl);
if (javacProcessingEnvironmentClass.isInstance(processingEnv)) {
Method getContextMethod = javacProcessingEnvironmentClass.getDeclaredMethod("getContext");
Object tmpContext = getContextMethod.invoke(processingEnv);
Class optionsClass = Class.forName("com.sun.tools.javac.util.Options", false, cl);
Class contextClass = Class.forName("com.sun.tools.javac.util.Context", false, cl);
Method instanceMethod = optionsClass.getDeclaredMethod("instance", new Class[]{contextClass});
Object tmpOptions = instanceMethod.invoke(null, tmpContext);
if (tmpOptions != null) {
Method getMethod = optionsClass.getDeclaredMethod("get", new Class[]{String.class});
Object result = getMethod.invoke(tmpOptions, "-s"); // todo: we have to check for -d also
if (result != null) {
classDir = (String) result;
}
this.options.verbose = getMethod.invoke(tmpOptions, "-verbose") != null;
}
}
} catch (Exception e) {
/// some Error was here - problems with reflection or security
processWarning(WebserviceapMessages.WEBSERVICEAP_PARSING_JAVAC_OPTIONS_ERROR());
report(e.getMessage());
}
if (classDir == null) { // some error within reflection block
String property = System.getProperty("sun.java.command");
if (property != null) {
Scanner scanner = new Scanner(property);
boolean sourceDirNext = false;
while (scanner.hasNext()) {
String token = scanner.next();
if (sourceDirNext) {
classDir = token;
sourceDirNext = false;
} else if ("-verbose".equals(token)) {
options.verbose = true;
} else if ("-s".equals(token)) {
sourceDirNext = true;
}
}
}
}
if (classDir != null) {
sourceDir = new File(classDir);
}
return classDir;
}
private boolean getOption(String key) {
String value = processingEnv.getOptions().get(key);
if (value != null) {
return Boolean.valueOf(value);
}
return false;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (context.getRound() != 1) {
return true;
}
context.incrementRound();
WebService webService;
WebServiceProvider webServiceProvider;
WebServiceVisitor webServiceVisitor = new WebServiceWrapperGenerator(this, context);
boolean processedEndpoint = false;
Collection<TypeElement> classes = new ArrayList<TypeElement>();
filterClasses(classes, roundEnv.getRootElements());
for (TypeElement element : classes) {
webServiceProvider = element.getAnnotation(WebServiceProvider.class);
webService = element.getAnnotation(WebService.class);
if (webServiceProvider != null) {
if (webService != null) {
processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_AND_WEBSERVICEPROVIDER(element.getQualifiedName()));
}
processedEndpoint = true;
}
if (webService == null) {
continue;
}
element.accept(webServiceVisitor, null);
processedEndpoint = true;
}
if (!processedEndpoint) {
if (isCommandLineInvocation) {
if (!ignoreNoWebServiceFoundWarning) {
processWarning(WebserviceapMessages.WEBSERVICEAP_NO_WEBSERVICE_ENDPOINT_FOUND());
}
} else {
processError(WebserviceapMessages.WEBSERVICEAP_NO_WEBSERVICE_ENDPOINT_FOUND());
}
}
return true;
}
private void filterClasses(Collection<TypeElement> classes, Collection<? extends Element> elements) {
for (Element element : elements) {
if (element.getKind().equals(ElementKind.CLASS)) {
classes.add((TypeElement) element);
filterClasses(classes, ElementFilter.typesIn(element.getEnclosedElements()));
}
}
}
@Override
public void processWarning(String message) {
if (isCommandLineInvocation) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message);
} else {
report(message);
}
}
protected void report(String msg) {
if (out == null) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "No output set for web service annotation processor reporting.");
}
return;
}
out.println(msg);
out.flush();
}
@Override
public void processError(String message) {
if (isCommandLineInvocation) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
throw new AbortException();
} else {
throw new ModelerException(message);
}
}
@Override
public void processError(String message, Element element) {
if (isCommandLineInvocation) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
} else {
throw new ModelerException(message);
}
}
@Override
public boolean canOverWriteClass(String className) {
return !((doNotOverWrite && GeneratorUtil.classExists(options, className)));
}
@Override
public File getSourceDir() {
return sourceDir;
}
@Override
public boolean isRemote(TypeElement typeElement) {
return processingEnv.getTypeUtils().isSubtype(typeElement.asType(), remoteElement.asType());
}
@Override
public boolean isServiceException(TypeMirror typeMirror) {
return processingEnv.getTypeUtils().isSubtype(typeMirror, exceptionElement)
&& !processingEnv.getTypeUtils().isSubtype(typeMirror, runtimeExceptionElement)
&& !processingEnv.getTypeUtils().isSubtype(typeMirror, remoteExceptionElement);
}
@Override
public TypeMirror getHolderValueType(TypeMirror type) {
return TypeModeler.getHolderValueType(type, defHolderElement, processingEnv);
}
@Override
public boolean checkAndSetProcessed(TypeElement typeElement) {
if (!processedTypeElements.contains(typeElement)) {
processedTypeElements.add(typeElement);
return false;
}
return true;
}
@Override
public void log(String message) {
if (options != null && options.verbose) {
message = new StringBuilder().append('[').append(message).append(']').toString(); // "[%s]"
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
}
}
@Override
public WsgenOptions getOptions() {
return options;
}
@Override
public ProcessingEnvironment getProcessingEnvironment() {
return processingEnv;
}
@Override
public String getOperationName(Name messageName) {
return messageName != null ? messageName.toString() : null;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
}

View File

@@ -0,0 +1,54 @@
/*
* 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.processor.modeler.annotation;
/**
* @author dkohlert
*/
public enum WebServiceConstants {
SERVICE("Service"),
JAXWS_PACKAGE_PD("jaxws."),
PD_JAXWS_PACKAGE_PD(".jaxws."),
BEAN("Bean"),
FAULT_INFO("faultInfo"),
RESPONSE("Response");
private String value;
private WebServiceConstants(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,870 @@
/*
* 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.processor.modeler.annotation;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.resources.WebserviceapMessages;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
import com.sun.xml.internal.ws.model.RuntimeModeler;
import javax.annotation.processing.ProcessingEnvironment;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleElementVisitor6;
import javax.lang.model.util.SimpleTypeVisitor6;
import javax.lang.model.util.Types;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* @author WS Development Team
*/
public abstract class WebServiceVisitor extends SimpleElementVisitor6<Void, Object> {
protected ModelBuilder builder;
protected String wsdlNamespace;
protected String typeNamespace;
protected Stack<SOAPBinding> soapBindingStack;
protected SOAPBinding typeElementSoapBinding;
protected SOAPStyle soapStyle = SOAPStyle.DOCUMENT;
protected boolean wrapped = true;
protected Port port;
protected Name serviceImplName;
protected Name endpointInterfaceName;
protected AnnotationProcessorContext context;
protected AnnotationProcessorContext.SeiContext seiContext;
protected boolean processingSei = false;
protected String serviceName;
protected Name packageName;
protected String portName;
protected boolean endpointReferencesInterface = false;
protected boolean hasWebMethods = false;
protected TypeElement typeElement;
protected Set<String> processedMethods;
protected boolean pushedSoapBinding = false;
private static final NoTypeVisitor NO_TYPE_VISITOR = new NoTypeVisitor();
public WebServiceVisitor(ModelBuilder builder, AnnotationProcessorContext context) {
this.builder = builder;
this.context = context;
soapBindingStack = new Stack<SOAPBinding>();
processedMethods = new HashSet<String>();
}
@Override
public Void visitType(TypeElement e, Object o) {
WebService webService = e.getAnnotation(WebService.class);
if (!shouldProcessWebService(webService, e))
return null;
if (builder.checkAndSetProcessed(e))
return null;
typeElement = e;
switch (e.getKind()) {
case INTERFACE: {
if (endpointInterfaceName != null && !endpointInterfaceName.equals(e.getQualifiedName())) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTERFACES_DO_NOT_MATCH(endpointInterfaceName, e.getQualifiedName()), e);
}
verifySeiAnnotations(webService, e);
endpointInterfaceName = e.getQualifiedName();
processingSei = true;
preProcessWebService(webService, e);
processWebService(webService, e);
postProcessWebService(webService, e);
break;
}
case CLASS: {
typeElementSoapBinding = e.getAnnotation(SOAPBinding.class);
if (serviceImplName == null)
serviceImplName = e.getQualifiedName();
String endpointInterfaceName = webService != null ? webService.endpointInterface() : null;
if (endpointInterfaceName != null && endpointInterfaceName.length() > 0) {
checkForInvalidImplAnnotation(e, SOAPBinding.class);
if (webService.name().length() > 0)
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTEFACE_PLUS_ELEMENT("name"), e);
endpointReferencesInterface = true;
verifyImplAnnotations(e);
inspectEndpointInterface(endpointInterfaceName, e);
serviceImplName = null;
return null;
}
processingSei = false;
preProcessWebService(webService, e);
processWebService(webService, e);
serviceImplName = null;
postProcessWebService(webService, e);
serviceImplName = null;
break;
}
default:
break;
}
return null;
}
protected void verifySeiAnnotations(WebService webService, TypeElement d) {
if (webService.endpointInterface().length() > 0) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTERFACE_ON_INTERFACE(
d.getQualifiedName(), webService.endpointInterface()), d);
}
if (webService.serviceName().length() > 0) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION_ELEMENT(
"serviceName", d.getQualifiedName()), d);
}
if (webService.portName().length() > 0) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION_ELEMENT(
"portName", d.getQualifiedName()), d);
}
}
protected void verifyImplAnnotations(TypeElement d) {
for (ExecutableElement method : ElementFilter.methodsIn(d.getEnclosedElements())) {
checkForInvalidImplAnnotation(method, WebMethod.class);
checkForInvalidImplAnnotation(method, Oneway.class);
checkForInvalidImplAnnotation(method, WebResult.class);
for (VariableElement param : method.getParameters()) {
checkForInvalidImplAnnotation(param, WebParam.class);
}
}
}
protected void checkForInvalidSeiAnnotation(TypeElement element, Class annotationClass) {
Object annotation = element.getAnnotation(annotationClass);
if (annotation != null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION(
annotationClass.getName(), element.getQualifiedName()), element);
}
}
protected void checkForInvalidImplAnnotation(Element element, Class annotationClass) {
Object annotation = element.getAnnotation(annotationClass);
if (annotation != null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTEFACE_PLUS_ANNOTATION(annotationClass.getName()), element);
}
}
protected void preProcessWebService(WebService webService, TypeElement element) {
processedMethods = new HashSet<String>();
seiContext = context.getSeiContext(element);
String targetNamespace = null;
if (webService != null)
targetNamespace = webService.targetNamespace();
PackageElement packageElement = builder.getProcessingEnvironment().getElementUtils().getPackageOf(element);
if (targetNamespace == null || targetNamespace.length() == 0) {
String packageName = packageElement.getQualifiedName().toString();
if (packageName == null || packageName.length() == 0) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_NO_PACKAGE_CLASS_MUST_HAVE_TARGETNAMESPACE(
element.getQualifiedName()), element);
}
targetNamespace = RuntimeModeler.getNamespace(packageName);
}
seiContext.setNamespaceUri(targetNamespace);
if (serviceImplName == null)
serviceImplName = seiContext.getSeiImplName();
if (serviceImplName != null) {
seiContext.setSeiImplName(serviceImplName);
context.addSeiContext(serviceImplName, seiContext);
}
portName = ClassNameInfo.getName(element.getSimpleName().toString().replace('$', '_'));
packageName = packageElement.getQualifiedName();
portName = webService != null && webService.name() != null && webService.name().length() > 0 ?
webService.name() : portName;
serviceName = ClassNameInfo.getName(element.getQualifiedName().toString()) + WebServiceConstants.SERVICE.getValue();
serviceName = webService != null && webService.serviceName() != null && webService.serviceName().length() > 0 ?
webService.serviceName() : serviceName;
wsdlNamespace = seiContext.getNamespaceUri();
typeNamespace = wsdlNamespace;
SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
if (soapBinding != null) {
pushedSoapBinding = pushSoapBinding(soapBinding, element, element);
} else if (element.equals(typeElement)) {
pushedSoapBinding = pushSoapBinding(new MySoapBinding(), element, element);
}
}
public static boolean sameStyle(SOAPBinding.Style style, SOAPStyle soapStyle) {
return style.equals(SOAPBinding.Style.DOCUMENT)
&& soapStyle.equals(SOAPStyle.DOCUMENT)
|| style.equals(SOAPBinding.Style.RPC)
&& soapStyle.equals(SOAPStyle.RPC);
}
protected boolean pushSoapBinding(SOAPBinding soapBinding, Element bindingElement, TypeElement classElement) {
boolean changed = false;
if (!sameStyle(soapBinding.style(), soapStyle)) {
changed = true;
if (pushedSoapBinding)
builder.processError(WebserviceapMessages.WEBSERVICEAP_MIXED_BINDING_STYLE(
classElement.getQualifiedName()), bindingElement);
}
if (soapBinding.style().equals(SOAPBinding.Style.RPC)) {
soapStyle = SOAPStyle.RPC;
wrapped = true;
if (soapBinding.parameterStyle().equals(ParameterStyle.BARE)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_RPC_LITERAL_MUST_NOT_BE_BARE(
classElement.getQualifiedName()), bindingElement);
}
} else {
soapStyle = SOAPStyle.DOCUMENT;
if (wrapped != soapBinding.parameterStyle().equals(ParameterStyle.WRAPPED)) {
wrapped = soapBinding.parameterStyle().equals(ParameterStyle.WRAPPED);
changed = true;
}
}
if (soapBinding.use().equals(SOAPBinding.Use.ENCODED)) {
String style = "rpc";
if (soapBinding.style().equals(SOAPBinding.Style.DOCUMENT))
style = "document";
builder.processError(WebserviceapMessages.WEBSERVICE_ENCODED_NOT_SUPPORTED(
classElement.getQualifiedName(), style), bindingElement);
}
if (changed || soapBindingStack.empty()) {
soapBindingStack.push(soapBinding);
pushedSoapBinding = true;
}
return changed;
}
protected SOAPBinding popSoapBinding() {
if (pushedSoapBinding)
soapBindingStack.pop();
SOAPBinding soapBinding = null;
if (!soapBindingStack.empty()) {
soapBinding = soapBindingStack.peek();
if (soapBinding.style().equals(SOAPBinding.Style.RPC)) {
soapStyle = SOAPStyle.RPC;
wrapped = true;
} else {
soapStyle = SOAPStyle.DOCUMENT;
wrapped = soapBinding.parameterStyle().equals(ParameterStyle.WRAPPED);
}
} else {
pushedSoapBinding = false;
}
return soapBinding;
}
protected String getNamespace(PackageElement packageElement) {
return RuntimeModeler.getNamespace(packageElement.getQualifiedName().toString());
}
protected boolean shouldProcessWebService(WebService webService, TypeElement element) {
switch (element.getKind()) {
case INTERFACE: {
hasWebMethods = false;
if (webService == null)
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTERFACE_HAS_NO_WEBSERVICE_ANNOTATION(
element.getQualifiedName()), element);
SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
if (soapBinding != null
&& soapBinding.style() == SOAPBinding.Style.RPC
&& soapBinding.parameterStyle() == SOAPBinding.ParameterStyle.BARE) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SOAPBINDING_PARAMETERSTYLE(
soapBinding, element), element);
return false;
}
return isLegalSei(element);
}
case CLASS: {
if (webService == null)
return false;
hasWebMethods = hasWebMethods(element);
SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
if (soapBinding != null
&& soapBinding.style() == SOAPBinding.Style.RPC
&& soapBinding.parameterStyle() == SOAPBinding.ParameterStyle.BARE) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SOAPBINDING_PARAMETERSTYLE(
soapBinding, element), element);
return false;
}
return isLegalImplementation(webService, element);
}
default: {
throw new IllegalArgumentException("Class or Interface was expecting. But element: " + element);
}
}
}
abstract protected void processWebService(WebService webService, TypeElement element);
protected void postProcessWebService(WebService webService, TypeElement element) {
processMethods(element);
popSoapBinding();
}
protected boolean hasWebMethods(TypeElement element) {
if (element.getQualifiedName().toString().equals(Object.class.getName()))
return false;
WebMethod webMethod;
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
webMethod = method.getAnnotation(WebMethod.class);
if (webMethod != null) {
if (webMethod.exclude()) {
if (webMethod.operationName().length() > 0)
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_WEBMETHOD_ELEMENT_WITH_EXCLUDE(
"operationName", element.getQualifiedName(), method.toString()), method);
if (webMethod.action().length() > 0)
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_WEBMETHOD_ELEMENT_WITH_EXCLUDE(
"action", element.getQualifiedName(), method.toString()), method);
} else {
return true;
}
}
}
return false;//hasWebMethods(d.getSuperclass().getDeclaration());
}
protected void processMethods(TypeElement element) {
switch (element.getKind()) {
case INTERFACE: {
builder.log("ProcessedMethods Interface: " + element);
hasWebMethods = false;
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
method.accept(this, null);
}
for (TypeMirror superType : element.getInterfaces())
processMethods((TypeElement) ((DeclaredType) superType).asElement());
break;
}
case CLASS: {
builder.log("ProcessedMethods Class: " + element);
hasWebMethods = hasWebMethods(element);
if (element.getQualifiedName().toString().equals(Object.class.getName()))
return;
if (element.getAnnotation(WebService.class) != null) {
// Super classes must have @WebService annotations to pick up their methods
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
method.accept(this, null);
}
}
TypeMirror superclass = element.getSuperclass();
if (!superclass.getKind().equals(TypeKind.NONE)) {
processMethods((TypeElement) ((DeclaredType) superclass).asElement());
}
break;
}
default:
break;
}
}
private TypeElement getEndpointInterfaceElement(String endpointInterfaceName, TypeElement element) {
TypeElement intTypeElement = null;
for (TypeMirror interfaceType : element.getInterfaces()) {
if (endpointInterfaceName.equals(interfaceType.toString())) {
intTypeElement = (TypeElement) ((DeclaredType) interfaceType).asElement();
seiContext = context.getSeiContext(intTypeElement.getQualifiedName());
assert (seiContext != null);
seiContext.setImplementsSei(true);
break;
}
}
if (intTypeElement == null) {
intTypeElement = builder.getProcessingEnvironment().getElementUtils().getTypeElement(endpointInterfaceName);
}
if (intTypeElement == null)
builder.processError(WebserviceapMessages.WEBSERVICEAP_ENDPOINTINTERFACE_CLASS_NOT_FOUND(endpointInterfaceName));
return intTypeElement;
}
private void inspectEndpointInterface(String endpointInterfaceName, TypeElement d) {
TypeElement intTypeElement = getEndpointInterfaceElement(endpointInterfaceName, d);
if (intTypeElement != null)
intTypeElement.accept(this, null);
}
@Override
public Void visitExecutable(ExecutableElement method, Object o) {
// Methods must be public
if (!method.getModifiers().contains(Modifier.PUBLIC))
return null;
if (processedMethod(method))
return null;
WebMethod webMethod = method.getAnnotation(WebMethod.class);
if (webMethod != null && webMethod.exclude())
return null;
SOAPBinding soapBinding = method.getAnnotation(SOAPBinding.class);
if (soapBinding == null && !method.getEnclosingElement().equals(typeElement)) {
if (method.getEnclosingElement().getKind().equals(ElementKind.CLASS)) {
soapBinding = method.getEnclosingElement().getAnnotation(SOAPBinding.class);
if (soapBinding != null)
builder.log("using " + method.getEnclosingElement() + "'s SOAPBinding.");
else {
soapBinding = new MySoapBinding();
}
}
}
boolean newBinding = false;
if (soapBinding != null) {
newBinding = pushSoapBinding(soapBinding, method, typeElement);
}
try {
if (shouldProcessMethod(method, webMethod)) {
processMethod(method, webMethod);
}
} finally {
if (newBinding) {
popSoapBinding();
}
}
return null;
}
protected boolean processedMethod(ExecutableElement method) {
String id = method.toString();
if (processedMethods.contains(id))
return true;
processedMethods.add(id);
return false;
}
protected boolean shouldProcessMethod(ExecutableElement method, WebMethod webMethod) {
builder.log("should process method: " + method.getSimpleName() + " hasWebMethods: " + hasWebMethods + " ");
/*
Fix for https://jax-ws.dev.java.net/issues/show_bug.cgi?id=577
if (hasWebMethods && webMethod == null) {
builder.log("webMethod == null");
return false;
}
*/
Collection<Modifier> modifiers = method.getModifiers();
boolean staticFinal = modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.FINAL);
if (staticFinal) {
if (webMethod != null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_METHOD_IS_STATIC_OR_FINAL(method.getEnclosingElement(),
method), method);
}
return false;
}
boolean result = (endpointReferencesInterface ||
method.getEnclosingElement().equals(typeElement) ||
(method.getEnclosingElement().getAnnotation(WebService.class) != null));
builder.log("endpointReferencesInterface: " + endpointReferencesInterface);
builder.log("declaring class has WebService: " + (method.getEnclosingElement().getAnnotation(WebService.class) != null));
builder.log("returning: " + result);
return result;
}
abstract protected void processMethod(ExecutableElement method, WebMethod webMethod);
protected boolean isLegalImplementation(WebService webService, TypeElement classElement) {
boolean isStateful = isStateful(classElement);
Collection<Modifier> modifiers = classElement.getModifiers();
if (!modifiers.contains(Modifier.PUBLIC)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_NOT_PUBLIC(classElement.getQualifiedName()), classElement);
return false;
}
if (modifiers.contains(Modifier.FINAL) && !isStateful) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_FINAL(classElement.getQualifiedName()), classElement);
return false;
}
if (modifiers.contains(Modifier.ABSTRACT) && !isStateful) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_ABSTRACT(classElement.getQualifiedName()), classElement);
return false;
}
boolean hasDefaultConstructor = false;
for (ExecutableElement constructor : ElementFilter.constructorsIn(classElement.getEnclosedElements())) {
if (constructor.getModifiers().contains(Modifier.PUBLIC) &&
constructor.getParameters().isEmpty()) {
hasDefaultConstructor = true;
break;
}
}
if (!hasDefaultConstructor && !isStateful) {
if (classElement.getEnclosingElement() != null && !modifiers.contains(Modifier.STATIC)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_CLASS_IS_INNERCLASS_NOT_STATIC(
classElement.getQualifiedName()), classElement);
return false;
}
builder.processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_NO_DEFAULT_CONSTRUCTOR(
classElement.getQualifiedName()), classElement);
return false;
}
if (webService.endpointInterface().isEmpty()) {
if (!methodsAreLegal(classElement))
return false;
} else {
TypeElement interfaceElement = getEndpointInterfaceElement(webService.endpointInterface(), classElement);
if (!classImplementsSei(classElement, interfaceElement))
return false;
}
return true;
}
private boolean isStateful(TypeElement classElement) {
try {
// We don't want dependency on rt-ha module as its not integrated in JDK
return classElement.getAnnotation((Class<? extends Annotation>) Class.forName("com.sun.xml.internal.ws.developer.Stateful")) != null;
} catch (ClassNotFoundException e) {
//ignore
}
return false;
}
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) {
for (TypeMirror interfaceType : classElement.getInterfaces()) {
if (((DeclaredType) interfaceType).asElement().equals(interfaceElement))
return true;
}
List<ExecutableElement> classMethods = getClassMethods(classElement);
boolean implementsMethod;
for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) {
implementsMethod = false;
for (ExecutableElement classMethod : classMethods) {
if (sameMethod(interfaceMethod, classMethod)) {
implementsMethod = true;
classMethods.remove(classMethod);
break;
}
}
if (!implementsMethod) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod);
return false;
}
}
return true;
}
private static List<ExecutableElement> getClassMethods(TypeElement classElement) {
if (classElement.getQualifiedName().toString().equals(Object.class.getName())) // we don't need Object's methods
return null;
TypeElement superclassElement = (TypeElement) ((DeclaredType) classElement.getSuperclass()).asElement();
List<ExecutableElement> superclassesMethods = getClassMethods(superclassElement);
List<ExecutableElement> classMethods = ElementFilter.methodsIn(classElement.getEnclosedElements());
if (superclassesMethods == null)
return classMethods;
else
superclassesMethods.addAll(classMethods);
return superclassesMethods;
}
protected boolean sameMethod(ExecutableElement method1, ExecutableElement method2) {
if (!method1.getSimpleName().equals(method2.getSimpleName()))
return false;
Types typeUtils = builder.getProcessingEnvironment().getTypeUtils();
if(!typeUtils.isSameType(method1.getReturnType(), method2.getReturnType())
&& !typeUtils.isSubtype(method2.getReturnType(), method1.getReturnType()))
return false;
List<? extends VariableElement> parameters1 = method1.getParameters();
List<? extends VariableElement> parameters2 = method2.getParameters();
if (parameters1.size() != parameters2.size())
return false;
for (int i = 0; i < parameters1.size(); i++) {
if (!typeUtils.isSameType(parameters1.get(i).asType(), parameters2.get(i).asType()))
return false;
}
return true;
}
protected boolean isLegalSei(TypeElement interfaceElement) {
for (VariableElement field : ElementFilter.fieldsIn(interfaceElement.getEnclosedElements()))
if (field.getConstantValue() != null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_SEI_CANNOT_CONTAIN_CONSTANT_VALUES(
interfaceElement.getQualifiedName(), field.getSimpleName()));
return false;
}
return methodsAreLegal(interfaceElement);
}
protected boolean methodsAreLegal(TypeElement element) {
switch (element.getKind()) {
case INTERFACE: {
hasWebMethods = false;
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
if (!isLegalMethod(method, element))
return false;
}
for (TypeMirror superInterface : element.getInterfaces()) {
if (!methodsAreLegal((TypeElement) ((DeclaredType) superInterface).asElement()))
return false;
}
return true;
}
case CLASS: {
hasWebMethods = hasWebMethods(element);
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
if (!method.getModifiers().contains(Modifier.PUBLIC))
continue; // let's validate only public methods
if (!isLegalMethod(method, element))
return false;
}
DeclaredType superClass = (DeclaredType) element.getSuperclass();
TypeElement tE = (TypeElement) superClass.asElement();
return tE.getQualifiedName().toString().equals(Object.class.getName())
|| methodsAreLegal(tE);
}
default: {
throw new IllegalArgumentException("Class or interface was expecting. But element: " + element);
}
}
}
protected boolean isLegalMethod(ExecutableElement method, TypeElement typeElement) {
WebMethod webMethod = method.getAnnotation(WebMethod.class);
//SEI cannot have methods with @WebMethod(exclude=true)
if (typeElement.getKind().equals(ElementKind.INTERFACE) && webMethod != null && webMethod.exclude())
builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION_ELEMENT_EXCLUDE("exclude=true", typeElement.getQualifiedName(), method.toString()), method);
// With https://jax-ws.dev.java.net/issues/show_bug.cgi?id=577, hasWebMethods has no effect
if (hasWebMethods && webMethod == null) // backwards compatibility (for legacyWebMethod computation)
return true;
if ((webMethod != null) && webMethod.exclude()) {
return true;
}
/*
This check is not needed as Impl class is already checked that it is not abstract.
if (typeElement instanceof TypeElement && method.getModifiers().contains(Modifier.ABSTRACT)) { // use Kind.equals instead of instanceOf
builder.processError(method.getPosition(), WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_METHOD_IS_ABSTRACT(typeElement.getQualifiedName(), method.getSimpleName()));
return false;
}
*/
TypeMirror returnType = method.getReturnType();
if (!isLegalType(returnType)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_RETURN_TYPE_CANNOT_IMPLEMENT_REMOTE(typeElement.getQualifiedName(),
method.getSimpleName(),
returnType), method);
}
boolean isOneWay = method.getAnnotation(Oneway.class) != null;
if (isOneWay && !isValidOneWayMethod(method, typeElement))
return false;
SOAPBinding soapBinding = method.getAnnotation(SOAPBinding.class);
if (soapBinding != null) {
if (soapBinding.style().equals(SOAPBinding.Style.RPC)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_RPC_SOAPBINDING_NOT_ALLOWED_ON_METHOD(typeElement.getQualifiedName(), method.toString()), method);
}
}
int paramIndex = 0;
for (VariableElement parameter : method.getParameters()) {
if (!isLegalParameter(parameter, method, typeElement, paramIndex++))
return false;
}
if (!isDocLitWrapped() && soapStyle.equals(SOAPStyle.DOCUMENT)) {
VariableElement outParam = getOutParameter(method);
int inParams = getModeParameterCount(method, WebParam.Mode.IN);
int outParams = getModeParameterCount(method, WebParam.Mode.OUT);
if (inParams != 1) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_AND_NO_ONE_IN(typeElement.getQualifiedName(), method.toString()), method);
}
if (returnType.accept(NO_TYPE_VISITOR, null)) {
if (outParam == null && !isOneWay) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
}
if (outParams != 1) {
if (!isOneWay && outParams != 0)
builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_RETURN_AND_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
}
} else {
if (outParams > 0) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_RETURN_AND_OUT(typeElement.getQualifiedName(), method.toString()), outParam);
}
}
}
return true;
}
protected boolean isLegalParameter(VariableElement param,
ExecutableElement method,
TypeElement typeElement,
int paramIndex) {
if (!isLegalType(param.asType())) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_PARAMETER_TYPES_CANNOT_IMPLEMENT_REMOTE(typeElement.getQualifiedName(),
method.getSimpleName(),
param.getSimpleName(),
param.asType().toString()), param);
return false;
}
TypeMirror holderType;
holderType = builder.getHolderValueType(param.asType());
WebParam webParam = param.getAnnotation(WebParam.class);
WebParam.Mode mode = null;
if (webParam != null)
mode = webParam.mode();
if (holderType != null) {
if (mode != null && mode == WebParam.Mode.IN)
builder.processError(WebserviceapMessages.WEBSERVICEAP_HOLDER_PARAMETERS_MUST_NOT_BE_IN_ONLY(typeElement.getQualifiedName(), method.toString(), paramIndex), param);
} else if (mode != null && mode != WebParam.Mode.IN) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_NON_IN_PARAMETERS_MUST_BE_HOLDER(typeElement.getQualifiedName(), method.toString(), paramIndex), param);
}
return true;
}
protected boolean isDocLitWrapped() {
return soapStyle.equals(SOAPStyle.DOCUMENT) && wrapped;
}
private static final class NoTypeVisitor extends SimpleTypeVisitor6<Boolean, Void> {
@Override
public Boolean visitNoType(NoType t, Void o) {
return true;
}
@Override
protected Boolean defaultAction(TypeMirror e, Void aVoid) {
return false;
}
}
protected boolean isValidOneWayMethod(ExecutableElement method, TypeElement typeElement) {
boolean valid = true;
if (!(method.getReturnType().accept(NO_TYPE_VISITOR, null))) {
// this is an error, cannot be OneWay and have a return type
builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_OPERATION_CANNOT_HAVE_RETURN_TYPE(typeElement.getQualifiedName(), method.toString()), method);
valid = false;
}
VariableElement outParam = getOutParameter(method);
if (outParam != null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_AND_OUT(typeElement.getQualifiedName(), method.toString()), outParam);
valid = false;
}
if (!isDocLitWrapped() && soapStyle.equals(SOAPStyle.DOCUMENT)) {
int inCnt = getModeParameterCount(method, WebParam.Mode.IN);
if (inCnt != 1) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_AND_NOT_ONE_IN(typeElement.getQualifiedName(), method.toString()), method);
valid = false;
}
}
for (TypeMirror thrownType : method.getThrownTypes()) {
TypeElement thrownElement = (TypeElement) ((DeclaredType) thrownType).asElement();
if (builder.isServiceException(thrownType)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_OPERATION_CANNOT_DECLARE_EXCEPTIONS(
typeElement.getQualifiedName(), method.toString(), thrownElement.getQualifiedName()), method);
valid = false;
}
}
return valid;
}
protected int getModeParameterCount(ExecutableElement method, WebParam.Mode mode) {
WebParam webParam;
int cnt = 0;
for (VariableElement param : method.getParameters()) {
webParam = param.getAnnotation(WebParam.class);
if (webParam != null) {
if (webParam.header())
continue;
if (isEquivalentModes(mode, webParam.mode()))
cnt++;
} else {
if (isEquivalentModes(mode, WebParam.Mode.IN)) {
cnt++;
}
}
}
return cnt;
}
protected boolean isEquivalentModes(WebParam.Mode mode1, WebParam.Mode mode2) {
if (mode1.equals(mode2))
return true;
assert mode1 == WebParam.Mode.IN || mode1 == WebParam.Mode.OUT;
return (mode1 == WebParam.Mode.IN && mode2 != WebParam.Mode.OUT) || (mode1 == WebParam.Mode.OUT && mode2 != WebParam.Mode.IN);
}
protected boolean isHolder(VariableElement param) {
return builder.getHolderValueType(param.asType()) != null;
}
protected boolean isLegalType(TypeMirror type) {
if (!(type != null && type.getKind().equals(TypeKind.DECLARED)))
return true;
TypeElement tE = (TypeElement) ((DeclaredType) type).asElement();
if (tE == null) {
// can be null, if this type's declaration is unknown. This may be the result of a processing error, such as a missing class file.
builder.processError(WebserviceapMessages.WEBSERVICEAP_COULD_NOT_FIND_TYPEDECL(type.toString(), context.getRound()));
}
return !builder.isRemote(tE);
}
protected VariableElement getOutParameter(ExecutableElement method) {
WebParam webParam;
for (VariableElement param : method.getParameters()) {
webParam = param.getAnnotation(WebParam.class);
if (webParam != null && webParam.mode() != WebParam.Mode.IN) {
return param;
}
}
return null;
}
protected static class MySoapBinding implements SOAPBinding {
@Override
public Style style() {
return SOAPBinding.Style.DOCUMENT;
}
@Override
public Use use() {
return SOAPBinding.Use.LITERAL;
}
@Override
public ParameterStyle parameterStyle() {
return SOAPBinding.ParameterStyle.WRAPPED;
}
@Override
public Class<? extends java.lang.annotation.Annotation> annotationType() {
return SOAPBinding.class;
}
}
}

View File

@@ -0,0 +1,569 @@
/*
* 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.processor.modeler.annotation;
import com.sun.codemodel.internal.CodeWriter;
import com.sun.codemodel.internal.JAnnotationArrayMember;
import com.sun.codemodel.internal.JAnnotationUse;
import com.sun.codemodel.internal.JBlock;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.codemodel.internal.JCommentPart;
import com.sun.codemodel.internal.JDefinedClass;
import com.sun.codemodel.internal.JDocComment;
import com.sun.codemodel.internal.JExpr;
import com.sun.codemodel.internal.JFieldVar;
import com.sun.codemodel.internal.JMethod;
import com.sun.codemodel.internal.JMod;
import com.sun.codemodel.internal.JType;
import com.sun.codemodel.internal.JVar;
import com.sun.codemodel.internal.writer.ProgressCodeWriter;
import com.sun.tools.internal.jxc.ap.InlineAnnotationReaderImpl;
import com.sun.tools.internal.jxc.model.nav.ApNavigator;
import com.sun.tools.internal.ws.ToolVersion;
import com.sun.tools.internal.ws.processor.generator.GeneratorBase;
import com.sun.tools.internal.ws.processor.generator.GeneratorConstants;
import com.sun.tools.internal.ws.processor.generator.Names;
import com.sun.tools.internal.ws.processor.modeler.ModelerException;
import com.sun.tools.internal.ws.processor.util.DirectoryUtil;
import com.sun.tools.internal.ws.resources.WebserviceapMessages;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import com.sun.tools.internal.ws.wscompile.FilerCodeWriter;
import com.sun.tools.internal.ws.wscompile.WsgenOptions;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
import com.sun.xml.internal.bind.v2.model.annotation.AnnotationReader;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
import com.sun.xml.internal.ws.model.AbstractWrapperBeanGenerator;
import com.sun.xml.internal.ws.spi.db.BindingHelper;
import com.sun.xml.internal.ws.util.StringUtils;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttachmentRef;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import javax.xml.ws.WebFault;
import javax.xml.ws.WebServiceException;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.sun.codemodel.internal.ClassType.CLASS;
import static com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceConstants.BEAN;
import static com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceConstants.FAULT_INFO;
import static com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceConstants.JAXWS_PACKAGE_PD;
import static com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceConstants.PD_JAXWS_PACKAGE_PD;
import static com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceConstants.RESPONSE;
/**
* This class generates the request/response and Exception Beans
* used by the JAX-WS runtime.
*
* @author WS Development Team
*/
public class WebServiceWrapperGenerator extends WebServiceVisitor {
private Set<String> wrapperNames;
private Set<String> processedExceptions;
private JCodeModel cm;
private final MakeSafeTypeVisitor makeSafeVisitor;
private static final FieldFactory FIELD_FACTORY = new FieldFactory();
private final AbstractWrapperBeanGenerator ap_generator =
new ApWrapperBeanGenerator(InlineAnnotationReaderImpl.theInstance,
new ApNavigator(builder.getProcessingEnvironment()), FIELD_FACTORY);
private final class ApWrapperBeanGenerator extends AbstractWrapperBeanGenerator<TypeMirror, TypeElement, ExecutableElement, MemberInfo> {
protected ApWrapperBeanGenerator(
AnnotationReader<TypeMirror, TypeElement, ?, ExecutableElement> annReader,
Navigator<TypeMirror, TypeElement, ?, ExecutableElement> nav, BeanMemberFactory<TypeMirror, MemberInfo> beanMemberFactory) {
super(annReader, nav, beanMemberFactory);
}
@Override
protected TypeMirror getSafeType(TypeMirror type) {
return WebServiceWrapperGenerator.this.getSafeType(type);
}
@Override
protected TypeMirror getHolderValueType(TypeMirror paramType) {
return builder.getHolderValueType(paramType);
}
@Override
protected boolean isVoidType(TypeMirror type) {
return type != null && type.getKind().equals(TypeKind.VOID);
}
}
private static final class FieldFactory implements AbstractWrapperBeanGenerator.BeanMemberFactory<TypeMirror, MemberInfo> {
@Override
public MemberInfo createWrapperBeanMember(TypeMirror paramType,
String paramName, List<Annotation> jaxb) {
return new MemberInfo(paramType, paramName, jaxb);
}
}
public WebServiceWrapperGenerator(ModelBuilder builder, AnnotationProcessorContext context) {
super(builder, context);
makeSafeVisitor = new MakeSafeTypeVisitor(builder.getProcessingEnvironment());
}
@Override
protected void processWebService(WebService webService, TypeElement d) {
cm = new JCodeModel();
wrapperNames = new HashSet<String>();
processedExceptions = new HashSet<String>();
}
@Override
protected void postProcessWebService(WebService webService, TypeElement d) {
super.postProcessWebService(webService, d);
doPostProcessWebService(webService, d);
}
@SuppressWarnings("CallToThreadDumpStack")
protected void doPostProcessWebService(WebService webService, TypeElement d) {
if (cm != null) {
File sourceDir = builder.getSourceDir();
assert(sourceDir != null);
WsgenOptions options = builder.getOptions();
try {
CodeWriter cw = new FilerCodeWriter(sourceDir, options);
if(options.verbose)
cw = new ProgressCodeWriter(cw, System.out);
cm.build(cw);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void processMethod(ExecutableElement method, WebMethod webMethod) {
builder.log("WrapperGen - method: "+method);
builder.log("method.getDeclaringType(): " + method.asType());
if (wrapped && soapStyle.equals(SOAPStyle.DOCUMENT)) {
generateWrappers(method, webMethod);
}
generateExceptionBeans(method);
}
private boolean generateExceptionBeans(ExecutableElement method) {
String beanPackage = packageName + PD_JAXWS_PACKAGE_PD.getValue();
if (packageName.length() == 0)
beanPackage = JAXWS_PACKAGE_PD.getValue();
boolean beanGenerated = false;
for (TypeMirror thrownType : method.getThrownTypes()) {
TypeElement typeDecl = (TypeElement) ((DeclaredType) thrownType).asElement();
if (typeDecl == null) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_COULD_NOT_FIND_TYPEDECL(
thrownType.toString(), context.getRound()));
return false;
}
boolean tmp = generateExceptionBean(typeDecl, beanPackage);
beanGenerated = beanGenerated || tmp;
}
return beanGenerated;
}
private boolean duplicateName(String name) {
for (String str : wrapperNames) {
if (str.equalsIgnoreCase(name))
return true;
}
wrapperNames.add(name);
return false;
}
private boolean generateWrappers(ExecutableElement method, WebMethod webMethod) {
boolean isOneway = method.getAnnotation(Oneway.class) != null;
String beanPackage = packageName + PD_JAXWS_PACKAGE_PD.getValue();
if (packageName.length() == 0)
beanPackage = JAXWS_PACKAGE_PD.getValue();
Name methodName = method.getSimpleName();
String operationName = builder.getOperationName(methodName);
operationName = webMethod != null && webMethod.operationName().length() > 0 ?
webMethod.operationName() : operationName;
String reqName = operationName;
String resName = operationName + WebServiceConstants.RESPONSE.getValue();
String reqNamespace = typeNamespace;
String resNamespace = typeNamespace;
String requestClassName = beanPackage + StringUtils.capitalize(method.getSimpleName().toString());
RequestWrapper reqWrapper = method.getAnnotation(RequestWrapper.class);
if (reqWrapper != null) {
if (reqWrapper.className().length() > 0)
requestClassName = reqWrapper.className();
if (reqWrapper.localName().length() > 0)
reqName = reqWrapper.localName();
if (reqWrapper.targetNamespace().length() > 0)
reqNamespace = reqWrapper.targetNamespace();
}
builder.log("requestWrapper: "+requestClassName);
///// fix for wsgen CR 6442344
File file = new File(DirectoryUtil.getOutputDirectoryFor(requestClassName, builder.getSourceDir()),
Names.stripQualifier(requestClassName) + GeneratorConstants.JAVA_SRC_SUFFIX.getValue());
builder.getOptions().addGeneratedFile(file);
//////////
boolean canOverwriteRequest = builder.canOverWriteClass(requestClassName);
if (!canOverwriteRequest) {
builder.log("Class " + requestClassName + " exists. Not overwriting.");
}
if (duplicateName(requestClassName) && canOverwriteRequest) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_REQUEST_WRAPPER_BEAN_NAME_NOT_UNIQUE(
typeElement.getQualifiedName(), method.toString()));
}
String responseClassName = null;
boolean canOverwriteResponse = canOverwriteRequest;
if (!isOneway) {
responseClassName = beanPackage+StringUtils.capitalize(method.getSimpleName().toString())+RESPONSE.getValue();
ResponseWrapper resWrapper = method.getAnnotation(ResponseWrapper.class);
if(resWrapper != null) {
if (resWrapper.className().length() > 0)
responseClassName = resWrapper.className();
if (resWrapper.localName().length() > 0)
resName = resWrapper.localName();
if (resWrapper.targetNamespace().length() > 0)
resNamespace = resWrapper.targetNamespace();
}
canOverwriteResponse = builder.canOverWriteClass(responseClassName);
if (!canOverwriteResponse) {
builder.log("Class " + responseClassName + " exists. Not overwriting.");
}
if (duplicateName(responseClassName) && canOverwriteResponse) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_RESPONSE_WRAPPER_BEAN_NAME_NOT_UNIQUE(
typeElement.getQualifiedName(), method.toString()));
}
file = new File(DirectoryUtil.getOutputDirectoryFor(responseClassName, builder.getSourceDir()),
Names.stripQualifier(responseClassName) + GeneratorConstants.JAVA_SRC_SUFFIX.getValue());
builder.getOptions().addGeneratedFile(file);
}
//ArrayList<MemberInfo> reqMembers = new ArrayList<MemberInfo>();
//ArrayList<MemberInfo> resMembers = new ArrayList<MemberInfo>();
WrapperInfo reqWrapperInfo = new WrapperInfo(requestClassName);
//reqWrapperInfo.setMembers(reqMembers);
WrapperInfo resWrapperInfo = null;
if (!isOneway) {
resWrapperInfo = new WrapperInfo(responseClassName);
//resWrapperInfo.setMembers(resMembers);
}
seiContext.setReqWrapperOperation(method, reqWrapperInfo);
if (!isOneway)
seiContext.setResWrapperOperation(method, resWrapperInfo);
try {
if (!canOverwriteRequest && !canOverwriteResponse) {
return false;
}
JDefinedClass reqCls = null;
if (canOverwriteRequest) {
reqCls = getCMClass(requestClassName, CLASS);
}
JDefinedClass resCls = null;
if (!isOneway && canOverwriteResponse) {
resCls = getCMClass(responseClassName, CLASS);
}
// XMLElement Declarations
writeXmlElementDeclaration(reqCls, reqName,reqNamespace);
writeXmlElementDeclaration(resCls, resName, resNamespace);
List<MemberInfo> reqMembers = ap_generator.collectRequestBeanMembers(method);
List<MemberInfo> resMembers = ap_generator.collectResponseBeanMembers(method);
// XmlType
writeXmlTypeDeclaration(reqCls, reqName, reqNamespace, reqMembers);
writeXmlTypeDeclaration(resCls, resName, resNamespace, resMembers);
// class members
writeMembers(reqCls, reqMembers);
writeMembers(resCls, resMembers);
} catch (Exception e) {
throw new ModelerException("modeler.nestedGeneratorError",e);
}
return true;
}
// private List<Annotation> collectJAXBAnnotations(Declaration decl) {
// List<Annotation> jaxbAnnotation = new ArrayList<Annotation>();
// for(Class jaxbClass : jaxbAnns) {
// Annotation ann = decl.getAnnotation(jaxbClass);
// if (ann != null) {
// jaxbAnnotation.add(ann);
// }
// }
// return jaxbAnnotation;
// }
private TypeMirror getSafeType(TypeMirror type) {
return makeSafeVisitor.visit(type, builder.getProcessingEnvironment().getTypeUtils());
}
private JType getType(TypeMirror typeMirror) {
String type = typeMirror.toString();
try {
// System.out.println("typeName: "+typeName);
return cm.parseType(type);
// System.out.println("type: "+type);
} catch (ClassNotFoundException e) {
return cm.ref(type);
}
}
private void writeMembers(JDefinedClass cls, Collection<MemberInfo> members) {
if (cls == null)
return;
for (MemberInfo memInfo : members) {
JType type = getType(memInfo.getParamType());
JFieldVar field = cls.field(JMod.PRIVATE, type, memInfo.getParamName());
annotateParameterWithJaxbAnnotations(memInfo, field);
}
for (MemberInfo memInfo : members) {
writeMember(cls, memInfo.getParamType(),
memInfo.getParamName());
}
}
private void annotateParameterWithJaxbAnnotations(MemberInfo memInfo, JFieldVar field) {
List<Annotation> jaxbAnnotations = memInfo.getJaxbAnnotations();
for(Annotation ann : jaxbAnnotations) {
if (ann instanceof XmlMimeType) {
JAnnotationUse jaxbAnn = field.annotate(XmlMimeType.class);
jaxbAnn.param("value", ((XmlMimeType)ann).value());
} else if (ann instanceof XmlJavaTypeAdapter) {
JAnnotationUse jaxbAnn = field.annotate(XmlJavaTypeAdapter.class);
XmlJavaTypeAdapter ja = (XmlJavaTypeAdapter) ann;
try {
ja.value();
throw new AssertionError();
} catch (MirroredTypeException e) {
jaxbAnn.param("value",getType(e.getTypeMirror()));
}
// XmlJavaTypeAdapter.type() is for package only. No need to copy.
} else if (ann instanceof XmlAttachmentRef) {
field.annotate(XmlAttachmentRef.class);
} else if (ann instanceof XmlList){
field.annotate(XmlList.class);
} else if (ann instanceof XmlElement) {
XmlElement elemAnn = (XmlElement)ann;
JAnnotationUse jAnn = field.annotate(XmlElement.class);
jAnn.param("name", elemAnn.name());
jAnn.param("namespace", elemAnn.namespace());
if (elemAnn.nillable()) {
jAnn.param("nillable", true);
}
if (elemAnn.required()) {
jAnn.param("required", true);
}
} else {
throw new WebServiceException("SEI Parameter cannot have this JAXB annotation: " + ann);
}
}
}
protected JDefinedClass getCMClass(String className, com.sun.codemodel.internal.ClassType type) {
JDefinedClass cls;
try {
cls = cm._class(className, type);
} catch (com.sun.codemodel.internal.JClassAlreadyExistsException e){
cls = cm._getClass(className);
}
return cls;
}
private boolean generateExceptionBean(TypeElement thrownDecl, String beanPackage) {
if (!builder.isServiceException(thrownDecl.asType()))
return false;
String exceptionName = ClassNameInfo.getName(thrownDecl.getQualifiedName().toString());
if (processedExceptions.contains(exceptionName))
return false;
processedExceptions.add(exceptionName);
WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
String className = beanPackage+ exceptionName + BEAN.getValue();
Collection<MemberInfo> members = ap_generator.collectExceptionBeanMembers(thrownDecl);
boolean isWSDLException = isWSDLException(members, thrownDecl);
String namespace = typeNamespace;
String name = exceptionName;
FaultInfo faultInfo;
if (isWSDLException) {
TypeMirror beanType = getFaultInfoMember(members).getParamType();
faultInfo = new FaultInfo(TypeMonikerFactory.getTypeMoniker(beanType), true);
namespace = webFault.targetNamespace().length()>0 ?
webFault.targetNamespace() : namespace;
name = webFault.name().length()>0 ?
webFault.name() : name;
faultInfo.setElementName(new QName(namespace, name));
seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
return false;
}
if (webFault != null) {
namespace = webFault.targetNamespace().length()>0 ?
webFault.targetNamespace() : namespace;
name = webFault.name().length()>0 ?
webFault.name() : name;
className = webFault.faultBean().length()>0 ?
webFault.faultBean() : className;
}
JDefinedClass cls = getCMClass(className, CLASS);
faultInfo = new FaultInfo(className, false);
if (duplicateName(className)) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_EXCEPTION_BEAN_NAME_NOT_UNIQUE(
typeElement.getQualifiedName(), thrownDecl.getQualifiedName()));
}
boolean canOverWriteBean = builder.canOverWriteClass(className);
if (!canOverWriteBean) {
builder.log("Class " + className + " exists. Not overwriting.");
seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
return false;
}
if (seiContext.getExceptionBeanName(thrownDecl.getQualifiedName()) != null)
return false;
//write class comment - JAXWS warning
JDocComment comment = cls.javadoc();
for (String doc : GeneratorBase.getJAXWSClassComment(ToolVersion.VERSION.MAJOR_VERSION)) {
comment.add(doc);
}
// XmlElement Declarations
writeXmlElementDeclaration(cls, name, namespace);
// XmlType Declaration
//members = sortMembers(members);
XmlType xmlType = thrownDecl.getAnnotation(XmlType.class);
String xmlTypeName = (xmlType != null && !xmlType.name().equals("##default")) ? xmlType.name() : exceptionName;
String xmlTypeNamespace = (xmlType != null && !xmlType.namespace().equals("##default")) ? xmlType.namespace() : typeNamespace;
writeXmlTypeDeclaration(cls, xmlTypeName, xmlTypeNamespace, members);
writeMembers(cls, members);
seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
return true;
}
protected boolean isWSDLException(Collection<MemberInfo> members, TypeElement thrownDecl) {
WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
return webFault != null && members.size() == 2 && getFaultInfoMember(members) != null;
}
/*
* Returns the corresponding MemberInfo for getFaultInfo()
* method of an exception. Returns null, if that method is not there.
*/
private MemberInfo getFaultInfoMember(Collection<MemberInfo> members) {
for(MemberInfo member : members) {
if (member.getParamName().equals(FAULT_INFO.getValue())) {
return member;
}
}
return null;
}
private void writeXmlElementDeclaration(JDefinedClass cls, String elementName, String namespaceUri) {
if (cls == null)
return;
JAnnotationUse xmlRootElementAnn = cls.annotate(XmlRootElement.class);
xmlRootElementAnn.param("name", elementName);
if (namespaceUri.length() > 0) {
xmlRootElementAnn.param("namespace", namespaceUri);
}
JAnnotationUse xmlAccessorTypeAnn = cls.annotate(cm.ref(XmlAccessorType.class));
xmlAccessorTypeAnn.param("value", XmlAccessType.FIELD);
}
private void writeXmlTypeDeclaration(JDefinedClass cls, String typeName, String namespaceUri,
Collection<MemberInfo> members) {
if (cls == null)
return;
JAnnotationUse xmlTypeAnn = cls.annotate(cm.ref(XmlType.class));
xmlTypeAnn.param("name", typeName);
xmlTypeAnn.param("namespace", namespaceUri);
if (members.size() > 1) {
JAnnotationArrayMember paramArray = xmlTypeAnn.paramArray("propOrder");
for (MemberInfo memInfo : members) {
paramArray.param(memInfo.getParamName());
}
}
}
private void writeMember(JDefinedClass cls, TypeMirror paramType,
String paramName) {
if (cls == null)
return;
String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
JType propType = getType(paramType);
JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
JDocComment methodDoc = m.javadoc();
JCommentPart ret = methodDoc.addReturn();
ret.add("returns "+propType.name());
JBlock body = m.body();
body._return( JExpr._this().ref(paramName) );
m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
JVar param = m.param(propType, paramName);
methodDoc = m.javadoc();
JCommentPart part = methodDoc.addParam(paramName);
part.add("the value for the "+ paramName+" property");
body = m.body();
body.assign( JExpr._this().ref(paramName), param );
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.processor.modeler.annotation;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author dkohlert
*/
public class WrapperInfo {
public String wrapperName;
/** Creates a new instance of FaultInfo */
public WrapperInfo() {
}
public WrapperInfo(String wrapperName) {
this.wrapperName = wrapperName;
}
public void setWrapperName(String wrapperName) {
this.wrapperName = wrapperName;
}
public String getWrapperName() {
return wrapperName;
}
}

View File

@@ -0,0 +1,74 @@
/*
* 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.processor.modeler.wsdl;
import javax.xml.namespace.QName;
/**
* @author Vivek Pandey
*
* Rpc/Lit AccessorElement to be used to generate pseudo schema
*/
class AccessorElement {
private QName type;
private String name;
/**
* @param type
* @param name
*/
public AccessorElement(String name, QName type) {
this.type = type;
this.name = name;
}
/**
* @return Returns the type.
*/
public QName getType() {
return type;
}
/**
* @param type The type to set.
*/
public void setType(QName type) {
this.type = type;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,78 @@
/*
* 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.processor.util.ClassNameCollector;
import com.sun.tools.internal.xjc.api.ClassNameAllocator;
import java.util.HashSet;
import java.util.Set;
/**
* @author Vivek Pandey
* <p/>
* Implementation of Callback interface that allows the driver of the XJC API to rename JAXB-generated classes/interfaces/enums.
*/
public class ClassNameAllocatorImpl implements ClassNameAllocator {
public ClassNameAllocatorImpl(ClassNameCollector classNameCollector) {
this.classNameCollector = classNameCollector;
this.jaxbClasses = new HashSet<String>();
}
public String assignClassName(String packageName, String className) {
if(packageName== null || className == null){
//TODO: throw Exception
return className;
}
//if either of the values are empty string return the default className
if(packageName.equals("") || className.equals(""))
return className;
String fullClassName = packageName+"."+className;
// Check if there is any conflict with jaxws generated classes
Set<String> seiClassNames = classNameCollector.getSeiClassNames();
if(seiClassNames != null && seiClassNames.contains(fullClassName)){
className += TYPE_SUFFIX;
}
jaxbClasses.add(packageName+"."+className);
return className;
}
/**
*
* @return jaxbGenerated classNames
*/
public Set<String> getJaxbGeneratedClasses() {
return jaxbClasses;
}
private final static String TYPE_SUFFIX = "_Type";
private ClassNameCollector classNameCollector;
private Set<String> jaxbClasses;
}

View File

@@ -0,0 +1,101 @@
/*
* 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import org.xml.sax.SAXParseException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.UnknownHostException;
public class ConsoleErrorReporter extends ErrorReceiver {
private boolean hasError;
private PrintStream output;
private boolean debug;
public ConsoleErrorReporter(PrintStream stream) {
this.output = stream;
}
public ConsoleErrorReporter(OutputStream outputStream) {
this.output = new PrintStream(outputStream);
}
public boolean hasError() {
return hasError;
}
public void error(SAXParseException e) {
if(debug)
e.printStackTrace();
hasError = true;
if((e.getSystemId() == null && e.getPublicId() == null) && (e.getCause() instanceof UnknownHostException)) {
print(WscompileMessages.WSIMPORT_ERROR_MESSAGE(e.toString()), e);
} else {
print(WscompileMessages.WSIMPORT_ERROR_MESSAGE(e.getMessage()), e);
}
}
public void fatalError(SAXParseException e) {
if(debug)
e.printStackTrace();
hasError = true;
print(WscompileMessages.WSIMPORT_ERROR_MESSAGE(e.getMessage()), e);
}
public void warning(SAXParseException e) {
print(WscompileMessages.WSIMPORT_WARNING_MESSAGE(e.getMessage()), e);
}
/**
* Used to report possibly verbose information that
* can be safely ignored.
*/
public void info(SAXParseException e) {
print(WscompileMessages.WSIMPORT_INFO_MESSAGE(e.getMessage()), e);
}
public void debug(SAXParseException e){
print(WscompileMessages.WSIMPORT_DEBUG_MESSAGE(e.getMessage()), e);
}
private void print(String message, SAXParseException e) {
output.println(message);
output.println(getLocationString(e));
output.println();
}
public void enableDebugging(){
this.debug = true;
}
}

View File

@@ -0,0 +1,148 @@
/*
* 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.processor.model.ModelException;
import com.sun.tools.internal.ws.processor.model.java.JavaSimpleType;
import com.sun.tools.internal.ws.processor.model.java.JavaType;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBMapping;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBModel;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBType;
import com.sun.tools.internal.ws.processor.util.ClassNameCollector;
import com.sun.tools.internal.ws.wscompile.AbortException;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wsdl.parser.DOMForestScanner;
import com.sun.tools.internal.ws.wsdl.parser.MetadataFinder;
import com.sun.tools.internal.xjc.api.S2JJAXBModel;
import com.sun.tools.internal.xjc.api.SchemaCompiler;
import com.sun.tools.internal.xjc.api.TypeAndAnnotation;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.LocatorImpl;
import javax.xml.namespace.QName;
/**
* @author Vivek Pandey
*
* Uses JAXB XJC apis to build JAXBModel and resolves xml to java type mapping from JAXBModel
*/
public class JAXBModelBuilder {
private final ErrorReceiver errReceiver;
private final WsimportOptions options;
private final MetadataFinder forest;
public JAXBModelBuilder(WsimportOptions options, ClassNameCollector classNameCollector, MetadataFinder finder, ErrorReceiver errReceiver) {
this._classNameAllocator = new ClassNameAllocatorImpl(classNameCollector);
this.errReceiver = errReceiver;
this.options = options;
this.forest = finder;
internalBuildJAXBModel();
}
/**
* Builds model from WSDL document. Model contains abstraction which is used by the
* generators to generate the stub/tie/serializers etc. code.
*
* @see com.sun.tools.internal.ws.processor.modeler.Modeler#buildModel()
*/
private void internalBuildJAXBModel(){
try {
schemaCompiler = options.getSchemaCompiler();
schemaCompiler.resetSchema();
if(options.entityResolver != null) {
//set if its not null so as not to override catalog option specified via xjc args
schemaCompiler.setEntityResolver(options.entityResolver);
}
schemaCompiler.setClassNameAllocator(_classNameAllocator);
schemaCompiler.setErrorListener(errReceiver);
int schemaElementCount = 1;
for (Element element : forest.getInlinedSchemaElement()) {
String location = element.getOwnerDocument().getDocumentURI();
String systemId = location + "#types?schema" + schemaElementCount++;
if(forest.isMexMetadata)
schemaCompiler.parseSchema(systemId,element);
else
new DOMForestScanner(forest).scan(element,schemaCompiler.getParserHandler(systemId));
}
//feed external jaxb:bindings file
InputSource[] externalBindings = options.getSchemaBindings();
if(externalBindings != null){
for(InputSource jaxbBinding : externalBindings){
schemaCompiler.parseSchema(jaxbBinding);
}
}
} catch (Exception e) {
throw new ModelException(e);
}
}
public JAXBType getJAXBType(QName qname){
JAXBMapping mapping = jaxbModel.get(qname);
if (mapping == null){
return null;
}
JavaType javaType = new JavaSimpleType(mapping.getType());
return new JAXBType(qname, javaType, mapping, jaxbModel);
}
public TypeAndAnnotation getElementTypeAndAnn(QName qname){
JAXBMapping mapping = jaxbModel.get(qname);
if (mapping == null){
return null;
}
return mapping.getType().getTypeAnn();
}
protected void bind(){
S2JJAXBModel rawJaxbModel = schemaCompiler.bind();
if(rawJaxbModel == null)
throw new AbortException();
options.setCodeModel(rawJaxbModel.generateCode(null, errReceiver));
jaxbModel = new JAXBModel(rawJaxbModel);
jaxbModel.setGeneratedClassNames(_classNameAllocator.getJaxbGeneratedClasses());
}
protected SchemaCompiler getJAXBSchemaCompiler(){
return schemaCompiler;
}
public JAXBModel getJAXBModel(){
return jaxbModel;
}
private JAXBModel jaxbModel;
private SchemaCompiler schemaCompiler;
private final ClassNameAllocatorImpl _classNameAllocator;
protected static final LocatorImpl NULL_LOCATOR = new LocatorImpl();
}

View File

@@ -0,0 +1,281 @@
/*
* 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.processor.model.AbstractType;
import com.sun.tools.internal.ws.processor.model.Block;
import com.sun.tools.internal.ws.processor.model.ModelProperties;
import com.sun.tools.internal.ws.processor.model.Parameter;
import com.sun.tools.internal.ws.processor.model.java.JavaSimpleType;
import com.sun.tools.internal.ws.processor.model.java.JavaStructureMember;
import com.sun.tools.internal.ws.processor.model.java.JavaStructureType;
import com.sun.tools.internal.ws.processor.model.java.JavaType;
import com.sun.tools.internal.ws.processor.model.jaxb.*;
import com.sun.tools.internal.ws.resources.ModelerMessages;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import com.sun.tools.internal.ws.wscompile.AbortException;
import com.sun.tools.internal.ws.wscompile.ErrorReceiverFilter;
import com.sun.tools.internal.ws.wsdl.document.Message;
import com.sun.tools.internal.ws.wsdl.document.MessagePart;
import com.sun.tools.internal.xjc.api.S2JJAXBModel;
import com.sun.tools.internal.xjc.api.TypeAndAnnotation;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Utilities to be used by WSDLModeler
*
* @author Vivek Pandey
*
*/
class ModelerUtils {
/**
* This method should be called incase of wrapper style operations. This is
* equivalent to wrapper style schema component or JAXB Mapping object.
*
* @param jaxbType JAXBType from which a JAXBStructured type will be created.
* @return returns JAXBStructured type
*/
public static JAXBStructuredType createJAXBStructureType(JAXBType jaxbType) {
JAXBStructuredType type = new JAXBStructuredType(jaxbType);
type.setName(jaxbType.getName());
type.setJavaType(jaxbType.getJavaType());
return type;
}
/**
* This method uses JAXBStructured type (wrapper style operations) and
* unwraps it to create list of parameters.
*
*
* @param jaxbType instance of JAXBType, could be JAXBStructured type.
* @param block The Block (body/Header/Attachment) to which the created Parameter belong.
* @return list of Parameters
*/
public static List<Parameter> createUnwrappedParameters(JAXBType jaxbType,
Block block) {
List<Parameter> paramList = new ArrayList<Parameter>();
JAXBStructuredType type = null;
if (!(jaxbType instanceof JAXBStructuredType))
type = createJAXBStructureType(jaxbType);
else
type = (JAXBStructuredType) jaxbType;
JavaStructureType jst = new JavaStructureType(jaxbType.getJavaType()
.getRealName(), true, type);
type.setJavaType(jst);
block.setType(type);
List memberList = jaxbType.getWrapperChildren();
Iterator props = memberList.iterator();
while (props.hasNext()) {
JAXBProperty prop = (JAXBProperty) props.next();
paramList.add(createUnwrappedParameter(prop, jaxbType, block, type,
jst));
}
return paramList;
}
/**
* @param prop
* @param jaxbType
* @param block
* @return unwrapped parameter
*/
private static Parameter createUnwrappedParameter(JAXBProperty prop,
JAXBType jaxbType, Block block, JAXBStructuredType type,
JavaStructureType jst) {
QName elementName = prop.getElementName();
JavaType javaType = new JavaSimpleType(prop.getType());
JAXBElementMember eType = new JAXBElementMember(elementName, jaxbType);
JavaStructureMember jsm = new JavaStructureMember(elementName
.getLocalPart(), javaType, eType);
eType.setJavaStructureMember(jsm);
jst.add(jsm);
eType.setProperty(prop);
type.add(eType);
JAXBType t = new JAXBType(elementName, javaType, jaxbType
.getJaxbMapping(), jaxbType.getJaxbModel());
t.setUnwrapped(true);
Parameter parameter = createParameter(elementName.getLocalPart(), t, block);
parameter.setEmbedded(true);
return parameter;
}
public static List<Parameter> createRpcLitParameters(Message message, Block block, S2JJAXBModel jaxbModel, ErrorReceiverFilter errReceiver){
RpcLitStructure rpcStruct = (RpcLitStructure)block.getType();
List<Parameter> parameters = new ArrayList<Parameter>();
for(MessagePart part : message.getParts()){
if(!ModelerUtils.isBoundToSOAPBody(part))
continue;
QName name = part.getDescriptor();
TypeAndAnnotation typeAndAnn = jaxbModel.getJavaType(name);
if(typeAndAnn == null){
String msgQName = "{"+message.getDefining().getTargetNamespaceURI()+"}"+message.getName();
errReceiver.error(part.getLocator(), ModelerMessages.WSDLMODELER_RPCLIT_UNKOWNSCHEMATYPE(name.toString(),
part.getName(), msgQName));
throw new AbortException();
}
String type = typeAndAnn.getTypeClass().fullName();
type = ClassNameInfo.getGenericClass(type);
RpcLitMember param = new RpcLitMember(new QName("", part.getName()), type);
JavaType javaType = new JavaSimpleType(new JAXBTypeAndAnnotation(typeAndAnn));
param.setJavaType(javaType);
rpcStruct.addRpcLitMember(param);
Parameter parameter = ModelerUtils.createParameter(part.getName(), param, block);
parameter.setEmbedded(true);
parameters.add(parameter);
}
return parameters;
}
/**
* Called for non-wrapper style operations. It returns a Parameter constructed
* using the JAXBType and the Block.
*
* @param partName typically wsdl:part or any name to be given to the parameter
* @param jaxbType type of Parameter
* @param block Block to which the parameter belongs to
* @return Parameter created.
*/
public static Parameter createParameter(String partName, AbstractType jaxbType,
Block block) {
Parameter parameter = new Parameter(partName, block.getEntity());
parameter.setProperty(ModelProperties.PROPERTY_PARAM_MESSAGE_PART_NAME,
partName);
parameter.setEmbedded(false);
parameter.setType(jaxbType);
parameter.setTypeName(jaxbType.getJavaType().getType().getName());
parameter.setBlock(block);
return parameter;
}
/**
* Get Parameter from the list of parameters.
*
* @param paramName
* @param parameters
* @return the Parameter with name paramName from parameters
*/
public static Parameter getParameter(String paramName, List<Parameter> parameters){
if(parameters == null)
return null;
for(Parameter param: parameters){
//if(param.getName().equals("_return") && paramName.equals("return") || param.getName().equals(paramName)) {
if(param.getName().equals(paramName)){
return param;
}
}
return null;
}
/**
* Compares two JAXBStructures.
*
* @param struct1
* @param struct2
* @return true if struct1 and struct2 are equivalent.
*/
public static boolean isEquivalentLiteralStructures(
JAXBStructuredType struct1,
JAXBStructuredType struct2) {
if (struct1.getElementMembersCount() != struct2.getElementMembersCount())
return false;
Iterator members = struct1.getElementMembers();
JAXBElementMember member1;
JavaStructureMember javaMember1, javaMember2;
for (int i = 0; members.hasNext(); i++) {
member1 = (JAXBElementMember)members.next();
javaMember1 = member1.getJavaStructureMember();
javaMember2 =
((JavaStructureType)struct2.getJavaType()).getMemberByName(
member1.getJavaStructureMember().getName());
if (javaMember2.getConstructorPos() != i
|| !javaMember1.getType().equals(javaMember2.getType())) {
return false;
}
}
return false;
}
public static QName getRawTypeName(Parameter parameter) {
String name = parameter.getName();
if (parameter.getType() instanceof JAXBType) {
JAXBType jt = (JAXBType)parameter.getType();
if (jt.isUnwrappable()) {
List<JAXBProperty> props = jt.getWrapperChildren();
for(JAXBProperty prop: props) {
if (prop.getName().equals(name)) {
return prop.getRawTypeName();
}
}
}
}
return null;
}
/**
* @param part
* @return true if part is bound to Mime content
*/
public static boolean isBoundToMimeContent(MessagePart part) {
if((part != null) && part.getBindingExtensibilityElementKind() == MessagePart.WSDL_MIME_BINDING)
return true;
return false;
}
/**
* @param part
* @return true if part is bound to SOAPBody
*/
public static boolean isBoundToSOAPBody(MessagePart part) {
if((part != null) && part.getBindingExtensibilityElementKind() == MessagePart.SOAP_BODY_BINDING)
return true;
return false;
}
/**
* @param part
* @return true if part is bound to SOAPHeader
*/
public static boolean isBoundToSOAPHeader(MessagePart part) {
if((part != null) && part.getBindingExtensibilityElementKind() == MessagePart.SOAP_HEADER_BINDING)
return true;
return false;
}
public static boolean isUnbound(MessagePart part) {
if((part != null) && part.getBindingExtensibilityElementKind() == MessagePart.PART_NOT_BOUNDED)
return true;
return false;
}
}

View File

@@ -0,0 +1,314 @@
/*
* Copyright (c) 1997, 2014, 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.processor.generator.Names;
import static com.sun.tools.internal.ws.processor.modeler.wsdl.WSDLModelerBase.getExtensionOfType;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wscompile.Options;
import com.sun.tools.internal.ws.wsdl.document.*;
import com.sun.tools.internal.ws.wsdl.document.jaxws.JAXWSBinding;
import com.sun.tools.internal.ws.wsdl.document.schema.SchemaKinds;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAP12Binding;
import com.sun.tools.internal.ws.wsdl.document.soap.SOAPBinding;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.*;
/**
* Builds all possible pseudo schemas for async operation ResponseBean to feed to XJC.
*
* @author Vivek Pandey
*/
public class PseudoSchemaBuilder {
private final StringWriter buf = new StringWriter();
private final WSDLDocument wsdlDocument;
private WSDLModeler wsdlModeler;
private final List<InputSource> schemas = new ArrayList<InputSource>();
private final HashMap<QName, Port> bindingNameToPortMap = new HashMap<QName, Port>();
private static final String w3ceprSchemaBinding = "<bindings\n" +
" xmlns=\"http://java.sun.com/xml/ns/jaxb\"\n" +
" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\"\n" +
" xmlns:xjc=\"http://java.sun.com/xml/ns/jaxb/xjc\"\n" +
" version=\"2.1\">\n" +
" \n" +
" <bindings scd=\"x-schema::wsa\" if-exists=\"true\">\n" +
//comment the following, otw JAXB won't generate ObjectFactory, classes from wsa schema. See JAX-WS-804
// " <schemaBindings map=\"false\" />\n" +
" <bindings scd=\"wsa:EndpointReference\">\n" +
" <class ref=\"javax.xml.ws.wsaddressing.W3CEndpointReference\" xjc:recursive=\"true\"/>\n" +
" </bindings>\n" +
" <bindings scd=\"~wsa:EndpointReferenceType\">\n" +
" <class ref=\"javax.xml.ws.wsaddressing.W3CEndpointReference\" xjc:recursive=\"true\"/>\n" +
" </bindings>\n" +
" </bindings>\n" +
"</bindings>";
private static final String memberSubmissionEPR = "<bindings\n" +
" xmlns=\"http://java.sun.com/xml/ns/jaxb\"\n" +
" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"\n" +
" version=\"2.1\">\n" +
" \n" +
" <bindings scd=\"x-schema::wsa\" if-exists=\"true\">\n" +
//comment the following, otw JAXB won't generate ObjectFactory, classes from wsa schema. See JAX-WS-804
// " <schemaBindings map=\"false\" />\n" +
" <bindings scd=\"wsa:EndpointReference\">\n" +
" <class ref=\"com.sun.xml.internal.ws.developer.MemberSubmissionEndpointReference\"/>\n" +
" </bindings>\n" +
" <bindings scd=\"~wsa:EndpointReferenceType\">\n" +
" <class ref=\"com.sun.xml.internal.ws.developer.MemberSubmissionEndpointReference\"/>\n" +
" </bindings>\n" +
" </bindings>\n" +
"</bindings>";
private final static String sysId = "http://dummy.pseudo-schema#schema";
private WsimportOptions options;
public static List<InputSource> build(WSDLModeler wsdlModeler, WsimportOptions options, ErrorReceiver errReceiver) {
PseudoSchemaBuilder b = new PseudoSchemaBuilder(wsdlModeler.document);
b.wsdlModeler = wsdlModeler;
b.options = options;
b.build();
int i;
for(i = 0; i < b.schemas.size(); i++){
InputSource is = b.schemas.get(i);
is.setSystemId(sysId+(i + 1));
}
//add w3c EPR binding
if(!(options.noAddressingBbinding) && options.target.isLaterThan(Options.Target.V2_1)){
InputSource is = new InputSource(new ByteArrayInputStream(w3ceprSchemaBinding.getBytes(StandardCharsets.UTF_8)));
is.setSystemId(sysId+(++i +1));
b.schemas.add(is);
}
//TODO: uncomment after JAXB fixes the issue related to passing multiples of such bindings
//add member submission EPR binding
// InputSource is1 = new InputSource(new ByteArrayInputStream(memberSubmissionEPR.getBytes()));
// is1.setSystemId(sysId+(++i + 1));
// b.schemas.add(is1);
return b.schemas;
}
private PseudoSchemaBuilder(WSDLDocument _wsdl) {
this.wsdlDocument = _wsdl;
}
private void build() {
for(Iterator<Service> itr=wsdlDocument.getDefinitions().services(); itr.hasNext(); ) {
build(itr.next());
}
}
private void build(Service service) {
for( Iterator<Port> itr=service.ports(); itr.hasNext(); ) {
build(itr.next() );
}
}
private void build(Port port) {
if(wsdlModeler.isProvider(port))
return;
Binding binding = port.resolveBinding(wsdlDocument);
SOAPBinding soapBinding =
(SOAPBinding)getExtensionOfType(binding, SOAPBinding.class);
//lets try and see if its SOAP 1.2. dont worry about extension flag, its
// handled much earlier
if (soapBinding == null) {
soapBinding =
(SOAPBinding)getExtensionOfType(binding, SOAP12Binding.class);
}
if(soapBinding == null)
return;
PortType portType = binding.resolvePortType(wsdlDocument);
QName bindingName = WSDLModelerBase.getQNameOf(binding);
//we dont want to process the port bound to the binding processed earlier
if(bindingNameToPortMap.containsKey(bindingName))
return;
bindingNameToPortMap.put(bindingName, port);
for(Iterator itr=binding.operations(); itr.hasNext();){
BindingOperation bindingOperation = (BindingOperation)itr.next();
// get only the bounded operations
Set boundedOps = portType.getOperationsNamed(bindingOperation.getName());
if(boundedOps.size() != 1)
continue;
Operation operation = (Operation)boundedOps.iterator().next();
// No pseudo schema required for doc/lit
if(wsdlModeler.isAsync(portType, operation)){
buildAsync(portType, operation, bindingOperation);
}
}
}
/**
* @param portType
* @param operation
* @param bindingOperation
*/
private void buildAsync(PortType portType, Operation operation, BindingOperation bindingOperation) {
String operationName = getCustomizedOperationName(operation);//operation.getName();
if(operationName == null)
return;
Message outputMessage = null;
if(operation.getOutput() != null)
outputMessage = operation.getOutput().resolveMessage(wsdlDocument);
if(outputMessage != null){
List<MessagePart> allParts = new ArrayList<MessagePart>(outputMessage.getParts());
if(options != null && options.additionalHeaders) {
List<MessagePart> addtionalHeaderParts = wsdlModeler.getAdditionHeaderParts(bindingOperation, outputMessage, false);
allParts.addAll(addtionalHeaderParts);
}
if(allParts.size() > 1)
build(getOperationName(operationName), allParts);
}
}
private String getCustomizedOperationName(Operation operation) {
JAXWSBinding jaxwsCustomization = (JAXWSBinding)getExtensionOfType(operation, JAXWSBinding.class);
String operationName = (jaxwsCustomization != null)?((jaxwsCustomization.getMethodName() != null)?jaxwsCustomization.getMethodName().getName():null):null;
if(operationName != null){
if(Names.isJavaReservedWord(operationName)){
return null;
}
return operationName;
}
return operation.getName();
}
private void writeImports(QName elementName, List<MessagePart> parts){
Set<String> uris = new HashSet<String>();
for(MessagePart p:parts){
String ns = p.getDescriptor().getNamespaceURI();
if(!uris.contains(ns) && !ns.equals("http://www.w3.org/2001/XMLSchema") && !ns.equals(elementName.getNamespaceURI())){
print("<xs:import namespace=''{0}''/>", ns);
uris.add(ns);
}
}
}
boolean asyncRespBeanBinding = false;
private void build(QName elementName, List<MessagePart> allParts){
print(
"<xs:schema xmlns:xs=''http://www.w3.org/2001/XMLSchema''" +
" xmlns:jaxb=''http://java.sun.com/xml/ns/jaxb''" +
" xmlns:xjc=''http://java.sun.com/xml/ns/jaxb/xjc''" +
" jaxb:extensionBindingPrefixes=''xjc''" +
" jaxb:version=''1.0''" +
" targetNamespace=''{0}''>",
elementName.getNamespaceURI());
writeImports(elementName, allParts);
if(!asyncRespBeanBinding){
print(
"<xs:annotation><xs:appinfo>" +
" <jaxb:schemaBindings>" +
" <jaxb:package name=''{0}'' />" +
" </jaxb:schemaBindings>" +
"</xs:appinfo></xs:annotation>",
wsdlModeler.getJavaPackage() );
asyncRespBeanBinding = true;
}
print("<xs:element name=''{0}''>", elementName.getLocalPart());
print("<xs:complexType>");
print("<xs:sequence>");
for(MessagePart p:allParts) {
//rpclit wsdl:part must reference schema type not element, also it must exclude headers and mime parts
if(p.getDescriptorKind() == SchemaKinds.XSD_ELEMENT){
print("<xs:element ref=''types:{0}'' xmlns:types=''{1}''/>",p.getDescriptor().getLocalPart(), p.getDescriptor().getNamespaceURI());
}else{
print("<xs:element name=''{0}'' type=''{1}'' xmlns=''{2}'' />",
p.getName(),
p.getDescriptor().getLocalPart(),
p.getDescriptor().getNamespaceURI() );
}
}
print("</xs:sequence>");
print("</xs:complexType>");
print("</xs:element>");
print("</xs:schema>");
// reset the StringWriter, so that next operation element could be written
if(buf.toString().length() > 0){
//System.out.println("Response bean Schema for operation========> "+ elementName+"\n\n"+buf);
InputSource is = new InputSource(new StringReader(buf.toString()));
schemas.add(is);
buf.getBuffer().setLength(0);
}
}
private QName getOperationName(String operationName){
if(operationName == null)
return null;
// String namespaceURI = wsdlDocument.getDefinitions().getTargetNamespaceURI()+"?"+portType.getName()+"?" + operationName;
String namespaceURI = "";
return new QName(namespaceURI, operationName+"Response");
}
private void print( String msg ) {
print( msg, new Object[0] );
}
private void print( String msg, Object arg1 ) {
print( msg, new Object[]{arg1} );
}
private void print( String msg, Object arg1, Object arg2 ) {
print( msg, new Object[]{arg1, arg2} );
}
private void print( String msg, Object arg1, Object arg2, Object arg3 ) {
print( msg, new Object[]{arg1,arg2,arg3} );
}
private void print( String msg, Object[] args ) {
buf.write(MessageFormat.format(msg,args));
buf.write('\n');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,791 @@
/*
* 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.processor.modeler.wsdl;
import com.sun.tools.internal.ws.api.wsdl.TWSDLExtensible;
import com.sun.tools.internal.ws.api.wsdl.TWSDLExtension;
import com.sun.tools.internal.ws.processor.generator.Names;
import com.sun.tools.internal.ws.processor.model.Fault;
import com.sun.tools.internal.ws.processor.model.Operation;
import com.sun.tools.internal.ws.processor.model.Port;
import com.sun.tools.internal.ws.processor.model.java.JavaException;
import com.sun.tools.internal.ws.processor.modeler.Modeler;
import com.sun.tools.internal.ws.resources.ModelerMessages;
import com.sun.tools.internal.ws.wscompile.AbortException;
import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
import com.sun.tools.internal.ws.wscompile.ErrorReceiverFilter;
import com.sun.tools.internal.ws.wscompile.WsimportOptions;
import com.sun.tools.internal.ws.wsdl.document.*;
import com.sun.tools.internal.ws.wsdl.document.jaxws.JAXWSBinding;
import com.sun.tools.internal.ws.wsdl.document.mime.MIMEContent;
import com.sun.tools.internal.ws.wsdl.document.mime.MIMEMultipartRelated;
import com.sun.tools.internal.ws.wsdl.document.mime.MIMEPart;
import com.sun.tools.internal.ws.wsdl.document.schema.SchemaKinds;
import com.sun.tools.internal.ws.wsdl.document.soap.*;
import com.sun.tools.internal.ws.wsdl.framework.Entity;
import com.sun.tools.internal.ws.wsdl.framework.GloballyKnown;
import com.sun.tools.internal.ws.wsdl.framework.NoSuchEntityException;
import com.sun.tools.internal.ws.wsdl.parser.WSDLParser;
import com.sun.tools.internal.ws.wsdl.parser.MetadataFinder;
import com.sun.xml.internal.ws.spi.db.BindingHelper;
import org.xml.sax.helpers.LocatorImpl;
import javax.xml.namespace.QName;
import java.util.*;
/**
*
* @author WS Development Team
*
* Base class for WSDL->Model classes.
*/
public abstract class WSDLModelerBase implements Modeler {
protected final ErrorReceiverFilter errReceiver;
protected final WsimportOptions options;
protected MetadataFinder forest;
public WSDLModelerBase(WsimportOptions options, ErrorReceiver receiver, MetadataFinder forest) {
this.options = options;
this.errReceiver = new ErrorReceiverFilter(receiver);
this.forest = forest;
}
/**
*
* @param port
* @param wsdlPort
*/
protected void applyPortMethodCustomization(Port port, com.sun.tools.internal.ws.wsdl.document.Port wsdlPort) {
if (isProvider(wsdlPort)) {
return;
}
JAXWSBinding jaxwsBinding = (JAXWSBinding)getExtensionOfType(wsdlPort, JAXWSBinding.class);
String portMethodName = (jaxwsBinding != null)?((jaxwsBinding.getMethodName() != null)?jaxwsBinding.getMethodName().getName():null):null;
if(portMethodName != null){
port.setPortGetter(portMethodName);
}else{
portMethodName = Names.getPortName(port);
portMethodName = BindingHelper.mangleNameToClassName(portMethodName);
port.setPortGetter("get"+portMethodName);
}
}
protected boolean isProvider(com.sun.tools.internal.ws.wsdl.document.Port wsdlPort){
JAXWSBinding portCustomization = (JAXWSBinding)getExtensionOfType(wsdlPort, JAXWSBinding.class);
Boolean isProvider = (portCustomization != null)?portCustomization.isProvider():null;
if(isProvider != null){
return isProvider;
}
JAXWSBinding jaxwsGlobalCustomization = (JAXWSBinding)getExtensionOfType(document.getDefinitions(), JAXWSBinding.class);
isProvider = (jaxwsGlobalCustomization != null)?jaxwsGlobalCustomization.isProvider():null;
if (isProvider != null) {
return isProvider;
}
return false;
}
protected SOAPBody getSOAPRequestBody() {
SOAPBody requestBody =
(SOAPBody)getAnyExtensionOfType(info.bindingOperation.getInput(),
SOAPBody.class);
if (requestBody == null) {
// the WSDL document is invalid
error(info.bindingOperation.getInput(), ModelerMessages.WSDLMODELER_INVALID_BINDING_OPERATION_INPUT_MISSING_SOAP_BODY(info.bindingOperation.getName()));
}
return requestBody;
}
protected boolean isRequestMimeMultipart() {
for (TWSDLExtension extension: info.bindingOperation.getInput().extensions()) {
if (extension.getClass().equals(MIMEMultipartRelated.class)) {
return true;
}
}
return false;
}
protected boolean isResponseMimeMultipart() {
for (TWSDLExtension extension: info.bindingOperation.getOutput().extensions()) {
if (extension.getClass().equals(MIMEMultipartRelated.class)) {
return true;
}
}
return false;
}
protected SOAPBody getSOAPResponseBody() {
SOAPBody responseBody =
(SOAPBody)getAnyExtensionOfType(info.bindingOperation.getOutput(),
SOAPBody.class);
if (responseBody == null) {
// the WSDL document is invalid
error(info.bindingOperation.getOutput(), ModelerMessages.WSDLMODELER_INVALID_BINDING_OPERATION_OUTPUT_MISSING_SOAP_BODY(info.bindingOperation.getName()));
}
return responseBody;
}
protected com.sun.tools.internal.ws.wsdl.document.Message getOutputMessage() {
if (info.portTypeOperation.getOutput() == null) {
return null;
}
return info.portTypeOperation.getOutput().resolveMessage(info.document);
}
protected com.sun.tools.internal.ws.wsdl.document.Message getInputMessage() {
return info.portTypeOperation.getInput().resolveMessage(info.document);
}
/**
* @param body request or response body, represents soap:body
* @param message Input or output message, equivalent to wsdl:message
* @return iterator over MessagePart
*/
protected List<MessagePart> getMessageParts(
SOAPBody body,
com.sun.tools.internal.ws.wsdl.document.Message message, boolean isInput) {
String bodyParts = body.getParts();
ArrayList<MessagePart> partsList = new ArrayList<MessagePart>();
List<MessagePart> parts = new ArrayList<MessagePart>();
//get Mime parts
List mimeParts;
if (isInput) {
mimeParts = getMimeContentParts(message, info.bindingOperation.getInput());
} else {
mimeParts = getMimeContentParts(message, info.bindingOperation.getOutput());
}
if (bodyParts != null) {
StringTokenizer in = new StringTokenizer(bodyParts.trim(), " ");
while (in.hasMoreTokens()) {
String part = in.nextToken();
MessagePart mPart = message.getPart(part);
if (null == mPart) {
error(message, ModelerMessages.WSDLMODELER_ERROR_PARTS_NOT_FOUND(part, message.getName()));
}
mPart.setBindingExtensibilityElementKind(MessagePart.SOAP_BODY_BINDING);
partsList.add(mPart);
}
} else {
for (MessagePart mPart : message.getParts()) {
if (!mimeParts.contains(mPart)) {
mPart.setBindingExtensibilityElementKind(MessagePart.SOAP_BODY_BINDING);
}
partsList.add(mPart);
}
}
for (MessagePart mPart : message.getParts()) {
if (mimeParts.contains(mPart)) {
mPart.setBindingExtensibilityElementKind(MessagePart.WSDL_MIME_BINDING);
parts.add(mPart);
} else if(partsList.contains(mPart)) {
mPart.setBindingExtensibilityElementKind(MessagePart.SOAP_BODY_BINDING);
parts.add(mPart);
}
}
return parts;
}
/**
* @param message
* @return MessageParts referenced by the mime:content
*/
protected List<MessagePart> getMimeContentParts(Message message, TWSDLExtensible ext) {
ArrayList<MessagePart> mimeContentParts = new ArrayList<MessagePart>();
for (MIMEPart mimePart : getMimeParts(ext)) {
MessagePart part = getMimeContentPart(message, mimePart);
if (part != null) {
mimeContentParts.add(part);
}
}
return mimeContentParts;
}
/**
* @param mimeParts
*/
protected boolean validateMimeParts(Iterable<MIMEPart> mimeParts) {
boolean gotRootPart = false;
List<MIMEContent> mimeContents = new ArrayList<MIMEContent>();
for (MIMEPart mPart : mimeParts) {
for (TWSDLExtension obj : mPart.extensions()) {
if (obj instanceof SOAPBody) {
if (gotRootPart) {
warning(mPart, ModelerMessages.MIMEMODELER_INVALID_MIME_PART_MORE_THAN_ONE_SOAP_BODY(info.operation.getName().getLocalPart()));
return false;
}
gotRootPart = true;
} else if (obj instanceof MIMEContent) {
mimeContents.add((MIMEContent) obj);
}
}
if (!validateMimeContentPartNames(mimeContents)) {
return false;
}
if(mPart.getName() != null) {
warning(mPart, ModelerMessages.MIMEMODELER_INVALID_MIME_PART_NAME_NOT_ALLOWED(info.portTypeOperation.getName()));
}
}
return true;
}
private MessagePart getMimeContentPart(Message message, MIMEPart part) {
for( MIMEContent mimeContent : getMimeContents(part) ) {
String mimeContentPartName = mimeContent.getPart();
MessagePart mPart = message.getPart(mimeContentPartName);
//RXXXX mime:content MUST have part attribute
if(null == mPart) {
error(mimeContent, ModelerMessages.WSDLMODELER_ERROR_PARTS_NOT_FOUND(mimeContentPartName, message.getName()));
}
mPart.setBindingExtensibilityElementKind(MessagePart.WSDL_MIME_BINDING);
return mPart;
}
return null;
}
//List of mimeTypes
protected List<String> getAlternateMimeTypes(List<MIMEContent> mimeContents) {
List<String> mimeTypes = new ArrayList<String>();
//validateMimeContentPartNames(mimeContents.iterator());
// String mimeType = null;
for(MIMEContent mimeContent:mimeContents){
String mimeType = getMimeContentType(mimeContent);
if (!mimeTypes.contains(mimeType)) {
mimeTypes.add(mimeType);
}
}
return mimeTypes;
}
private boolean validateMimeContentPartNames(List<MIMEContent> mimeContents) {
//validate mime:content(s) in the mime:part as per R2909
for (MIMEContent mimeContent : mimeContents) {
String mimeContnetPart;
mimeContnetPart = getMimeContentPartName(mimeContent);
if(mimeContnetPart == null) {
warning(mimeContent, ModelerMessages.MIMEMODELER_INVALID_MIME_CONTENT_MISSING_PART_ATTRIBUTE(info.operation.getName().getLocalPart()));
return false;
}
}
return true;
}
protected Iterable<MIMEPart> getMimeParts(TWSDLExtensible ext) {
MIMEMultipartRelated multiPartRelated =
(MIMEMultipartRelated) getAnyExtensionOfType(ext,
MIMEMultipartRelated.class);
if(multiPartRelated == null) {
return Collections.emptyList();
}
return multiPartRelated.getParts();
}
//returns MIMEContents
protected List<MIMEContent> getMimeContents(MIMEPart part) {
List<MIMEContent> mimeContents = new ArrayList<MIMEContent>();
for (TWSDLExtension mimeContent : part.extensions()) {
if (mimeContent instanceof MIMEContent) {
mimeContents.add((MIMEContent) mimeContent);
}
}
//validateMimeContentPartNames(mimeContents.iterator());
return mimeContents;
}
private String getMimeContentPartName(MIMEContent mimeContent){
/*String partName = mimeContent.getPart();
if(partName == null){
throw new ModelerException("mimemodeler.invalidMimeContent.missingPartAttribute",
new Object[] {info.operation.getName().getLocalPart()});
}
return partName;*/
return mimeContent.getPart();
}
private String getMimeContentType(MIMEContent mimeContent){
String mimeType = mimeContent.getType();
if(mimeType == null){
error(mimeContent, ModelerMessages.MIMEMODELER_INVALID_MIME_CONTENT_MISSING_TYPE_ATTRIBUTE(info.operation.getName().getLocalPart()));
}
return mimeType;
}
/**
* For Document/Lit the wsdl:part should only have element attribute and
* for RPC/Lit or RPC/Encoded the wsdl:part should only have type attribute
* inside wsdl:message.
*/
protected boolean isStyleAndPartMatch(
SOAPOperation soapOperation,
MessagePart part) {
// style attribute on soap:operation takes precedence over the
// style attribute on soap:binding
if ((soapOperation != null) && (soapOperation.getStyle() != null)) {
if ((soapOperation.isDocument()
&& (part.getDescriptorKind() != SchemaKinds.XSD_ELEMENT))
|| (soapOperation.isRPC()
&& (part.getDescriptorKind() != SchemaKinds.XSD_TYPE))) {
return false;
}
} else {
if ((info.soapBinding.isDocument()
&& (part.getDescriptorKind() != SchemaKinds.XSD_ELEMENT))
|| (info.soapBinding.isRPC()
&& (part.getDescriptorKind() != SchemaKinds.XSD_TYPE))) {
return false;
}
}
return true;
}
protected String getRequestNamespaceURI(SOAPBody body) {
String namespaceURI = body.getNamespace();
if (namespaceURI == null) {
if(options.isExtensionMode()){
return info.modelPort.getName().getNamespaceURI();
}
// the WSDL document is invalid
// at least, that's my interpretation of section 3.5 of the WSDL 1.1 spec!
error(body, ModelerMessages.WSDLMODELER_INVALID_BINDING_OPERATION_INPUT_SOAP_BODY_MISSING_NAMESPACE(info.bindingOperation.getName()));
}
return namespaceURI;
}
protected String getResponseNamespaceURI(SOAPBody body) {
String namespaceURI = body.getNamespace();
if (namespaceURI == null) {
if(options.isExtensionMode()){
return info.modelPort.getName().getNamespaceURI();
}
// the WSDL document is invalid
// at least, that's my interpretation of section 3.5 of the WSDL 1.1 spec!
error(body, ModelerMessages.WSDLMODELER_INVALID_BINDING_OPERATION_OUTPUT_SOAP_BODY_MISSING_NAMESPACE(info.bindingOperation.getName()));
}
return namespaceURI;
}
/**
* @return List of SOAPHeader extensions
*/
protected List<SOAPHeader> getHeaderExtensions(TWSDLExtensible extensible) {
List<SOAPHeader> headerList = new ArrayList<SOAPHeader>();
for (TWSDLExtension extension : extensible.extensions()) {
if (extension.getClass()==MIMEMultipartRelated.class) {
for( MIMEPart part : ((MIMEMultipartRelated) extension).getParts() ) {
boolean isRootPart = isRootPart(part);
for (TWSDLExtension obj : part.extensions()) {
if (obj instanceof SOAPHeader) {
//bug fix: 5024015
if (!isRootPart) {
warning((Entity) obj, ModelerMessages.MIMEMODELER_WARNING_IGNORINGINVALID_HEADER_PART_NOT_DECLARED_IN_ROOT_PART(info.bindingOperation.getName()));
return new ArrayList<SOAPHeader>();
}
headerList.add((SOAPHeader) obj);
}
}
}
} else if (extension instanceof SOAPHeader) {
headerList.add((SOAPHeader) extension);
}
}
return headerList;
}
/**
* @param part
* @return true if part is the Root part
*/
private boolean isRootPart(MIMEPart part) {
for (TWSDLExtension twsdlExtension : part.extensions()) {
if (twsdlExtension instanceof SOAPBody) {
return true;
}
}
return false;
}
protected Set getDuplicateFaultNames() {
// look for fault messages with the same soap:fault name
Set<QName> faultNames = new HashSet<QName>();
Set<QName> duplicateNames = new HashSet<QName>();
for( BindingFault bindingFault : info.bindingOperation.faults() ) {
com.sun.tools.internal.ws.wsdl.document.Fault portTypeFault = null;
for (com.sun.tools.internal.ws.wsdl.document.Fault aFault : info.portTypeOperation.faults()) {
if (aFault.getName().equals(bindingFault.getName())) {
if (portTypeFault != null) {
// the WSDL document is invalid
error(bindingFault, ModelerMessages.WSDLMODELER_INVALID_BINDING_FAULT_NOT_UNIQUE(bindingFault.getName(),
info.bindingOperation.getName()));
} else {
portTypeFault = aFault;
}
}
}
if (portTypeFault == null) {
// the WSDL document is invalid
error(bindingFault, ModelerMessages.WSDLMODELER_INVALID_BINDING_FAULT_NOT_FOUND(bindingFault.getName(),
info.bindingOperation.getName()));
}
SOAPFault soapFault =
(SOAPFault)getExtensionOfType(bindingFault, SOAPFault.class);
if (soapFault == null) {
// the WSDL document is invalid
if(options.isExtensionMode()){
warning(bindingFault, ModelerMessages.WSDLMODELER_INVALID_BINDING_FAULT_OUTPUT_MISSING_SOAP_FAULT(bindingFault.getName(),
info.bindingOperation.getName()));
}else {
error(bindingFault, ModelerMessages.WSDLMODELER_INVALID_BINDING_FAULT_OUTPUT_MISSING_SOAP_FAULT(bindingFault.getName(),
info.bindingOperation.getName()));
}
}
com.sun.tools.internal.ws.wsdl.document.Message faultMessage =
portTypeFault.resolveMessage(info.document);
if(faultMessage.getParts().isEmpty()) {
// the WSDL document is invalid
error(faultMessage, ModelerMessages.WSDLMODELER_INVALID_BINDING_FAULT_EMPTY_MESSAGE(bindingFault.getName(),
faultMessage.getName()));
}
// bug fix: 4852729
if (!options.isExtensionMode() && (soapFault != null && soapFault.getNamespace() != null)) {
warning(soapFault, ModelerMessages.WSDLMODELER_WARNING_R_2716_R_2726("soapbind:fault", soapFault.getName()));
}
String faultNamespaceURI = (soapFault != null && soapFault.getNamespace() != null)?soapFault.getNamespace():portTypeFault.getMessage().getNamespaceURI();
String faultName = faultMessage.getName();
QName faultQName = new QName(faultNamespaceURI, faultName);
if (faultNames.contains(faultQName)) {
duplicateNames.add(faultQName);
} else {
faultNames.add(faultQName);
}
}
return duplicateNames;
}
/**
* @param operation
* @return true if operation has valid body parts
*/
protected boolean validateBodyParts(BindingOperation operation) {
boolean isRequestResponse =
info.portTypeOperation.getStyle()
== OperationStyle.REQUEST_RESPONSE;
List<MessagePart> inputParts = getMessageParts(getSOAPRequestBody(), getInputMessage(), true);
if (!validateStyleAndPart(operation, inputParts)) {
return false;
}
if(isRequestResponse){
List<MessagePart> outputParts = getMessageParts(getSOAPResponseBody(), getOutputMessage(), false);
if (!validateStyleAndPart(operation, outputParts)) {
return false;
}
}
return true;
}
/**
* @param operation
* @return true if operation has valid style and part
*/
private boolean validateStyleAndPart(BindingOperation operation, List<MessagePart> parts) {
SOAPOperation soapOperation =
(SOAPOperation) getExtensionOfType(operation, SOAPOperation.class);
for (MessagePart part : parts) {
if (part.getBindingExtensibilityElementKind() == MessagePart.SOAP_BODY_BINDING) {
if (!isStyleAndPartMatch(soapOperation, part)) {
return false;
}
}
}
return true;
}
protected String getLiteralJavaMemberName(Fault fault) {
String javaMemberName;
QName memberName = fault.getElementName();
javaMemberName = fault.getJavaMemberName();
if (javaMemberName == null) {
javaMemberName = memberName.getLocalPart();
}
return javaMemberName;
}
/**
* @param ext
* @param message
* @param name
* @return List of MimeContents from ext
*/
protected List<MIMEContent> getMimeContents(TWSDLExtensible ext, Message message, String name) {
for (MIMEPart mimePart : getMimeParts(ext)) {
List<MIMEContent> mimeContents = getMimeContents(mimePart);
for (MIMEContent mimeContent : mimeContents) {
if (mimeContent.getPart().equals(name)) {
return mimeContents;
}
}
}
return null;
}
protected String makePackageQualified(String s) {
if (s.indexOf(".") != -1) {
// s is already package qualified
return s;
} else if (options.defaultPackage != null
&& !options.defaultPackage.equals("")) {
return options.defaultPackage + "." + s;
} else {//options.defaultPackage seems to be never null, and this is never executed
return s;
}
}
protected String getUniqueName(
com.sun.tools.internal.ws.wsdl.document.Operation operation,
boolean hasOverloadedOperations) {
if (hasOverloadedOperations) {
return operation.getUniqueKey().replace(' ', '_');
} else {
return operation.getName();
}
}
protected static QName getQNameOf(GloballyKnown entity) {
return new QName(
entity.getDefining().getTargetNamespaceURI(),
entity.getName());
}
protected static TWSDLExtension getExtensionOfType(
TWSDLExtensible extensible,
Class type) {
for (TWSDLExtension extension:extensible.extensions()) {
if (extension.getClass().equals(type)) {
return extension;
}
}
return null;
}
protected TWSDLExtension getAnyExtensionOfType(
TWSDLExtensible extensible,
Class type) {
if (extensible == null) {
return null;
}
for (TWSDLExtension extension:extensible.extensions()) {
if(extension.getClass().equals(type)) {
return extension;
}else if (extension.getClass().equals(MIMEMultipartRelated.class) &&
(type.equals(SOAPBody.class) || type.equals(MIMEContent.class)
|| type.equals(MIMEPart.class))) {
for (MIMEPart part : ((MIMEMultipartRelated)extension).getParts()) {
//bug fix: 5024001
TWSDLExtension extn = getExtensionOfType(part, type);
if (extn != null) {
return extn;
}
}
}
}
return null;
}
// bug fix: 4857100
protected static com.sun.tools.internal.ws.wsdl.document.Message findMessage(
QName messageName,
WSDLDocument document) {
com.sun.tools.internal.ws.wsdl.document.Message message = null;
try {
message =
(com.sun.tools.internal.ws.wsdl.document.Message)document.find(
Kinds.MESSAGE,
messageName);
} catch (NoSuchEntityException e) {
}
return message;
}
protected static boolean tokenListContains(
String tokenList,
String target) {
if (tokenList == null) {
return false;
}
StringTokenizer tokenizer = new StringTokenizer(tokenList, " ");
while (tokenizer.hasMoreTokens()) {
String s = tokenizer.nextToken();
if (target.equals(s)) {
return true;
}
}
return false;
}
protected String getUniqueClassName(String className) {
int cnt = 2;
String uniqueName = className;
while (reqResNames.contains(uniqueName.toLowerCase(Locale.ENGLISH))) {
uniqueName = className + cnt;
cnt++;
}
reqResNames.add(uniqueName.toLowerCase(Locale.ENGLISH));
return uniqueName;
}
protected boolean isConflictingClassName(String name) {
if (_conflictingClassNames == null) {
return false;
}
return _conflictingClassNames.contains(name);
}
protected boolean isConflictingServiceClassName(String name) {
return isConflictingClassName(name);
}
protected boolean isConflictingStubClassName(String name) {
return isConflictingClassName(name);
}
protected boolean isConflictingTieClassName(String name) {
return isConflictingClassName(name);
}
protected boolean isConflictingPortClassName(String name) {
return isConflictingClassName(name);
}
protected boolean isConflictingExceptionClassName(String name) {
return isConflictingClassName(name);
}
int numPasses = 0;
protected void warning(Entity entity, String message){
//avoid duplicate warning for the second pass
if (numPasses > 1) {
return;
}
if (entity == null) {
errReceiver.warning(null, message);
} else {
errReceiver.warning(entity.getLocator(), message);
}
}
protected void error(Entity entity, String message){
if (entity == null) {
errReceiver.error(null, message);
} else {
errReceiver.error(entity.getLocator(), message);
}
throw new AbortException();
}
protected static final String OPERATION_HAS_VOID_RETURN_TYPE =
"com.sun.xml.internal.ws.processor.modeler.wsdl.operationHasVoidReturnType";
protected static final String WSDL_PARAMETER_ORDER =
"com.sun.xml.internal.ws.processor.modeler.wsdl.parameterOrder";
public static final String WSDL_RESULT_PARAMETER =
"com.sun.xml.internal.ws.processor.modeler.wsdl.resultParameter";
public static final String MESSAGE_HAS_MIME_MULTIPART_RELATED_BINDING =
"com.sun.xml.internal.ws.processor.modeler.wsdl.mimeMultipartRelatedBinding";
protected ProcessSOAPOperationInfo info;
private Set _conflictingClassNames;
protected Map<String,JavaException> _javaExceptions;
protected Map _faultTypeToStructureMap;
protected Map<QName, Port> _bindingNameToPortMap;
private final Set<String> reqResNames = new HashSet<String>();
public static class ProcessSOAPOperationInfo {
public ProcessSOAPOperationInfo(
Port modelPort,
com.sun.tools.internal.ws.wsdl.document.Port port,
com.sun.tools.internal.ws.wsdl.document.Operation portTypeOperation,
BindingOperation bindingOperation,
SOAPBinding soapBinding,
WSDLDocument document,
boolean hasOverloadedOperations,
Map headers) {
this.modelPort = modelPort;
this.port = port;
this.portTypeOperation = portTypeOperation;
this.bindingOperation = bindingOperation;
this.soapBinding = soapBinding;
this.document = document;
this.hasOverloadedOperations = hasOverloadedOperations;
this.headers = headers;
}
public Port modelPort;
public com.sun.tools.internal.ws.wsdl.document.Port port;
public com.sun.tools.internal.ws.wsdl.document.Operation portTypeOperation;
public BindingOperation bindingOperation;
public SOAPBinding soapBinding;
public WSDLDocument document;
public boolean hasOverloadedOperations;
public Map headers;
// additional data
public Operation operation;
}
protected WSDLParser parser;
protected WSDLDocument document;
protected static final LocatorImpl NULL_LOCATOR = new LocatorImpl();
}

View File

@@ -0,0 +1,260 @@
/*
* 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.processor.util;
import com.sun.tools.internal.ws.processor.model.*;
import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBType;
import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeVisitor;
import com.sun.tools.internal.ws.processor.model.jaxb.RpcLitStructure;
import javax.xml.namespace.QName;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class writes out a Model as an XML document.
*
* @author WS Development Team
*/
public class ClassNameCollector extends ExtendedModelVisitor
implements JAXBTypeVisitor {
public ClassNameCollector() {
}
public void process(Model model) {
try {
_allClassNames = new HashSet();
_exceptions = new HashSet();
_wsdlBindingNames = new HashSet();
_conflictingClassNames = new HashSet();
_seiClassNames = new HashSet<String>();
_jaxbGeneratedClassNames = new HashSet<String>();
_exceptionClassNames = new HashSet<String>();
_portTypeNames = new HashSet<QName>();
visit(model);
} catch (Exception e) {
e.printStackTrace();
// fail silently
} finally {
_allClassNames = null;
_exceptions = null;
}
}
public Set getConflictingClassNames() {
return _conflictingClassNames;
}
protected void postVisit(Model model) throws Exception {
for (Iterator iter = model.getExtraTypes(); iter.hasNext();) {
visitType((AbstractType)iter.next());
}
}
protected void preVisit(Service service) throws Exception {
registerClassName(
((JavaInterface)service.getJavaInterface()).getName());
// We don't generate Impl classes, commenting it out.
// Otherwise, it would cause naming conflicts
//registerClassName(
// ((JavaInterface)service.getJavaInterface()).getImpl());
}
protected void processPort11x(Port port){
QName wsdlBindingName = (QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_BINDING_NAME);
if (!_wsdlBindingNames.contains(wsdlBindingName)) {
// multiple ports can share a binding without causing a conflict
registerClassName(port.getJavaInterface().getName());
}
registerClassName((String) port.getProperty(
ModelProperties.PROPERTY_STUB_CLASS_NAME));
registerClassName((String) port.getProperty(
ModelProperties.PROPERTY_TIE_CLASS_NAME));
}
protected void preVisit(Port port) throws Exception {
QName portTypeName = (QName)port.getProperty(ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
if(_portTypeNames.contains(portTypeName))
return;
//in 2.0, stub/tie class are binding agnostic so they should be per port, that is multiple
// bindings can share the same port
addSEIClassName(port.getJavaInterface().getName());
}
private void addSEIClassName(String s) {
_seiClassNames.add(s);
registerClassName(s);
}
protected void postVisit(Port port) throws Exception {
QName wsdlBindingName = (QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_BINDING_NAME);
if (!_wsdlBindingNames.contains(wsdlBindingName)) {
_wsdlBindingNames.add(wsdlBindingName);
}
QName portTypeName = (QName)port.getProperty(ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
if(!_portTypeNames.contains(portTypeName)){
_portTypeNames.add(portTypeName);
}
}
protected boolean shouldVisit(Port port) {
QName wsdlBindingName = (QName) port.getProperty(
ModelProperties.PROPERTY_WSDL_BINDING_NAME);
return !_wsdlBindingNames.contains(wsdlBindingName);
}
protected void preVisit(Fault fault) throws Exception {
if (!_exceptions.contains(fault.getJavaException())) {
/* the same exception can be used in several faults, but that
* doesn't mean that there is a conflict
*/
_exceptions.add(fault.getJavaException());
addExceptionClassName(fault.getJavaException().getName());
for (Iterator iter = fault.getSubfaults();
iter != null && iter.hasNext();) {
Fault subfault = (Fault) iter.next();
preVisit(subfault);
}
}
}
private void addExceptionClassName(String name) {
if(_allClassNames.contains(name))
_exceptionClassNames.add(name);
registerClassName(name);
//To change body of created methods use File | Settings | File Templates.
}
protected void visitBodyBlock(Block block) throws Exception {
visitBlock(block);
}
protected void visitHeaderBlock(Block block) throws Exception {
visitBlock(block);
}
protected void visitFaultBlock(Block block) throws Exception {
}
protected void visitBlock(Block block) throws Exception {
visitType(block.getType());
}
protected void visit(Parameter parameter) throws Exception {
visitType(parameter.getType());
}
private void visitType(AbstractType type) throws Exception {
if (type != null) {
if (type instanceof JAXBType)
visitType((JAXBType)type);
else if (type instanceof RpcLitStructure)
visitType((RpcLitStructure)type);
}
}
private void visitType(JAXBType type) throws Exception {
type.accept(this);
}
private void visitType(RpcLitStructure type) throws Exception {
type.accept(this);
}
private void registerClassName(String name) {
if (name == null || name.equals("")) {
return;
}
if (_allClassNames.contains(name)) {
_conflictingClassNames.add(name);
} else {
_allClassNames.add(name);
}
}
public Set<String> getSeiClassNames() {
return _seiClassNames;
}
private Set<String> _seiClassNames;
public Set<String> getJaxbGeneratedClassNames() {
return _jaxbGeneratedClassNames;
}
private Set<String> _jaxbGeneratedClassNames;
public Set<String> getExceptionClassNames() {
return _exceptionClassNames;
}
private Set<String> _exceptionClassNames;
boolean doneVisitingJAXBModel = false;
public void visit(JAXBType type) throws Exception {
if(!doneVisitingJAXBModel && type.getJaxbModel() != null){
Set<String> classNames = type.getJaxbModel().getGeneratedClassNames();
for(String className : classNames){
addJAXBGeneratedClassName(className);
}
doneVisitingJAXBModel = true;
}
}
public void visit(RpcLitStructure type) throws Exception {
if(!doneVisitingJAXBModel){
Set<String> classNames = type.getJaxbModel().getGeneratedClassNames();
for(String className : classNames){
addJAXBGeneratedClassName(className);
}
doneVisitingJAXBModel = true;
}
}
private void addJAXBGeneratedClassName(String name) {
_jaxbGeneratedClassNames.add(name);
registerClassName(name);
}
private Set _allClassNames;
private Set _exceptions;
private Set _wsdlBindingNames;
private Set _conflictingClassNames;
private Set<QName> _portTypeNames;
}

View File

@@ -0,0 +1,108 @@
/*
* 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.processor.util;
import com.sun.tools.internal.ws.processor.generator.GeneratorException;
import com.sun.tools.internal.ws.util.ClassNameInfo;
import java.io.File;
import java.io.IOException;
/**
* Util provides static utility methods used by other wscompile classes.
*
* @author WS Development Team
*/
public class DirectoryUtil {
public static File getOutputDirectoryFor(String theClass, File rootDir) throws GeneratorException {
File outputDir = null;
String qualifiedClassName = theClass;
String packagePath = null;
String packageName = ClassNameInfo.getQualifier(qualifiedClassName);
if (packageName != null && packageName.length() > 0) {
packagePath = packageName.replace('.', File.separatorChar);
}
// Do we have a root directory?
if (rootDir != null) {
// Yes, do we have a package name?
if (packagePath != null) {
// Yes, so use it as the root. Open the directory...
outputDir = new File(rootDir, packagePath);
// Make sure the directory exists...
ensureDirectory(outputDir);
} else {
// Default package, so use root as output dir...
outputDir = rootDir;
}
} else {
// No root directory. Get the current working directory...
String workingDirPath = System.getProperty("user.dir");
File workingDir = new File(workingDirPath);
// Do we have a package name?
if (packagePath == null) {
// No, so use working directory...
outputDir = workingDir;
} else {
// Yes, so use working directory as the root...
outputDir = new File(workingDir, packagePath);
// Make sure the directory exists...
ensureDirectory(outputDir);
}
}
// Finally, return the directory...
return outputDir;
}
public static String getRelativePathfromCommonBase(File file, File base) throws IOException {
String basePath = base.getCanonicalPath();
String filePath = file.getCanonicalPath();
return filePath.substring(basePath.length());
}
private static void ensureDirectory(File dir) throws GeneratorException {
if (!dir.exists()) {
boolean created = dir.mkdirs();
if (!created || !dir.exists()) {
throw new GeneratorException("generator.cannot.create.dir",
dir.getAbsolutePath());
}
}
}
}

View File

@@ -0,0 +1,330 @@
/*
* 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.processor.util;
import com.sun.tools.internal.ws.processor.generator.GeneratorException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.MessageFormat;
/**
*
* @author WS Development Team
*/
public class IndentingWriter extends BufferedWriter {
private boolean beginningOfLine = true;
private int currentIndent = 0;
private int indentStep = 4;
public IndentingWriter(Writer out) {
super(out);
}
public IndentingWriter(Writer out,int step) {
this(out);
if (indentStep < 0) {
throw new IllegalArgumentException("negative indent step");
}
indentStep = step;
}
public void write(int c) throws IOException {
checkWrite();
super.write(c);
}
public void write(char[] cbuf, int off, int len) throws IOException {
if (len > 0) {
checkWrite();
}
super.write(cbuf, off, len);
}
public void write(String s, int off, int len) throws IOException {
if (len > 0) {
checkWrite();
}
super.write(s, off, len);
}
public void newLine() throws IOException {
super.newLine();
beginningOfLine = true;
}
protected void checkWrite() throws IOException {
if (beginningOfLine) {
beginningOfLine = false;
int i = currentIndent;
while (i > 0) {
super.write(' ');
-- i;
}
}
}
protected void indentIn() {
currentIndent += indentStep;
}
protected void indentOut() {
currentIndent -= indentStep;
if (currentIndent < 0) {
currentIndent = 0;
}
}
public void pI() {
indentIn();
}
public void pO() {
indentOut();
}
public void pI(int levels) {
for (int i = 0; i < levels; ++i) {
indentIn();
}
}
public void pO(int levels) {
for (int i = 0; i < levels; ++i) {
indentOut();
}
}
public void p(String s) throws IOException {
/*
int tabCount = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '\t') {
++tabCount;
indentIn();
}
}
String printStr = s.substring(tabCount);
*/
boolean canEncode = true;
//bug fix: 4839636
try{
if(!canEncode(s)) {
canEncode = false;
}
} catch (Throwable t) {
// there was some exception, what should we do?
// lets ignore it for now and proceed with the code generation!
}
if(!canEncode) {
throw new GeneratorException(
"generator.indentingwriter.charset.cantencode", s);
}
write(s);
/*
while (tabCount-- > 0) {
indentOut();
}
*/
}
/**
* Check if encode can handle the chars in this string.
*
*/
protected boolean canEncode(String s) {
final CharsetEncoder encoder =
Charset.forName(System.getProperty("file.encoding")).newEncoder();
char[] chars = s.toCharArray();
for (int i=0; i<chars.length; i++) {
if(!encoder.canEncode(chars[i])) {
return false;
}
}
return true;
}
public void p(String s1, String s2) throws IOException {
p(s1);
p(s2);
}
public void p(String s1, String s2, String s3) throws IOException {
p(s1);
p(s2);
p(s3);
}
public void p(String s1, String s2, String s3, String s4) throws IOException {
p(s1);
p(s2);
p(s3);
p(s4);
}
public void p(String s1, String s2, String s3, String s4, String s5) throws IOException {
p(s1);
p(s2);
p(s3);
p(s4);
p(s5);
}
public void pln() throws IOException {
newLine();
}
public void pln(String s) throws IOException {
p(s);
pln();
}
public void pln(String s1, String s2) throws IOException {
p(s1, s2);
pln();
}
public void pln(String s1, String s2, String s3) throws IOException {
p(s1, s2, s3);
pln();
}
public void pln(String s1, String s2, String s3, String s4) throws IOException {
p(s1, s2, s3, s4);
pln();
}
public void pln(String s1, String s2, String s3, String s4, String s5) throws IOException {
p(s1, s2, s3, s4, s5);
pln();
}
public void plnI(String s) throws IOException {
p(s);
pln();
pI();
}
public void pO(String s) throws IOException {
pO();
p(s);
}
public void pOln(String s) throws IOException {
pO(s);
pln();
}
public void pOlnI(String s) throws IOException {
pO(s);
pln();
pI();
}
public void p(Object o) throws IOException {
write(o.toString());
}
public void pln(Object o) throws IOException {
p(o.toString());
pln();
}
public void plnI(Object o) throws IOException {
p(o.toString());
pln();
pI();
}
public void pO(Object o) throws IOException {
pO();
p(o.toString());
}
public void pOln(Object o) throws IOException {
pO(o.toString());
pln();
}
public void pOlnI(Object o) throws IOException {
pO(o.toString());
pln();
pI();
}
public void pM(String s) throws IOException {
int i = 0;
while (i < s.length()) {
int j = s.indexOf('\n', i);
if (j == -1) {
p(s.substring(i));
break;
} else {
pln(s.substring(i, j));
i = j + 1;
}
}
}
public void pMln(String s) throws IOException {
pM(s);
pln();
}
public void pMlnI(String s) throws IOException {
pM(s);
pln();
pI();
}
public void pMO(String s) throws IOException {
pO();
pM(s);
}
public void pMOln(String s) throws IOException {
pMO(s);
pln();
}
public void pF(String pattern, Object[] arguments) throws IOException {
pM(MessageFormat.format(pattern, arguments));
}
public void pFln(String pattern, Object[] arguments) throws IOException {
pF(pattern, arguments);
pln();
}
}