Introduction of OpenAPI documentation for WebServices, including some refactorings

This commit is contained in:
Ziver Koc 2021-02-28 18:58:01 +01:00
parent 77e4bce99b
commit 5622a3b489
16 changed files with 519 additions and 267 deletions

View file

@ -183,4 +183,15 @@ public class ClassUtil {
}
return null;
}
/**
* @param c a array class
* @return the base class the array is based on, if the input is not an array then the input is returned.
*/
public static Class<?> getArrayClass(Class<?> c) {
if (c != null && c.isArray()) {
return getArrayClass(c.getComponentType());
}
return c;
}
}

View file

@ -24,16 +24,17 @@
package zutil.net.upnp.service;
import zutil.net.ws.WSInterface.WSParamName;
import zutil.net.ws.WSReturnObject;
public class BrowseRetObj extends WSReturnObject{
@WSValueName("Result")
@WSParamName("Result")
public String Result;
@WSValueName("NumberReturned")
@WSParamName("NumberReturned")
public int NumberReturned;
@WSValueName("TotalMatches")
@WSParamName("TotalMatches")
public int TotalMatches;
@WSValueName("UpdateID")
@WSParamName("UpdateID")
public int UpdateID;
}

View file

@ -141,13 +141,13 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
return ret;
}
public class BrowseRetObj extends WSReturnObject{
@WSValueName("Result")
@WSParamName("Result")
public String Result;
@WSValueName("NumberReturned")
@WSParamName("NumberReturned")
public int NumberReturned;
@WSValueName("TotalMatches")
@WSParamName("TotalMatches")
public int TotalMatches;
@WSValueName("UpdateID")
@WSParamName("UpdateID")
public int UpdateID;
}

View file

@ -67,10 +67,11 @@ import java.lang.annotation.Target;
public interface WSInterface {
enum RequestType {
HTTP_GET,
HTTP_POST,
HTTP_PUT,
HTTP_DELETE
GET,
POST,
PUT,
DELETE,
PATCH
}
@ -79,7 +80,7 @@ public interface WSInterface {
* in an method.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Target({ElementType.PARAMETER, ElementType.FIELD})
@interface WSParamName {
String value();
boolean optional() default false;

View file

@ -147,13 +147,17 @@ public class WSMethodDef {
for (Field field : fields) {
WSParameterDef ret_param = new WSParameterDef(this);
WSReturnObject.WSValueName retValName = field.getAnnotation(WSReturnObject.WSValueName.class);
if (retValName != null)
ret_param.setName(retValName.value());
WSInterface.WSParamName paramNameAnnotation = field.getAnnotation(WSInterface.WSParamName.class);
if (paramNameAnnotation != null)
ret_param.setName(paramNameAnnotation.value());
else
ret_param.setName(field.getName());
WSInterface.WSDocumentation documentationAnnotation = field.getAnnotation(WSInterface.WSDocumentation.class);
if (documentationAnnotation != null)
ret_param.setDocumentation(documentationAnnotation.value());
ret_param.setParamClass(field.getType());
outputs.add(ret_param);
}
@ -178,13 +182,15 @@ public class WSMethodDef {
// Specific request type was not provided, try to figure it out by the method name
if (name.startsWith("get"))
this.requestType = WSInterface.RequestType.HTTP_GET;
this.requestType = WSInterface.RequestType.GET;
if (name.startsWith("post"))
this.requestType = WSInterface.RequestType.HTTP_POST;
this.requestType = WSInterface.RequestType.POST;
if (name.startsWith("put"))
this.requestType = WSInterface.RequestType.HTTP_PUT;
this.requestType = WSInterface.RequestType.PUT;
if (name.startsWith("delete"))
this.requestType = WSInterface.RequestType.HTTP_DELETE;
this.requestType = WSInterface.RequestType.DELETE;
if (name.startsWith("patch"))
this.requestType = WSInterface.RequestType.PATCH;
}
// Handle endpoint path

View file

@ -37,11 +37,10 @@ public class WSParameterDef{
/** The web service name of the parameter **/
private String name;
/** Developer documentation **/
private String doc;
private String documentation;
/** If this parameter is optional **/
private boolean optional;
/** Is it an header parameter **/
//boolean header;
protected WSParameterDef(WSMethodDef mDef){
this.mDef = mDef;
@ -63,11 +62,11 @@ public class WSParameterDef{
this.name = name;
}
public String getDoc() {
return doc;
public String getDocumentation() {
return documentation;
}
protected void setDoc(String doc) {
this.doc = doc;
protected void setDocumentation(String documentation) {
this.documentation = documentation;
}
public boolean isOptional() {

View file

@ -32,15 +32,16 @@ import java.lang.reflect.Field;
/**
* This class is used as an return Object for a web service.
* If an class implements this interface then it can return
* multiple values through the WSInterface. And the
* implementing class will be transparent. Example:
* If a class implements this interface then it implies that multiple
* parameters can be returned through the WSInterface. And the
* implementing class will be transparent to the requester. Example:
*
* <pre>
* private static class TestObject implements WSReturnObject{
* &#64;WSValueName("name")
* &#64;WSParamName("name")
* public String name;
* &#64;WSValueName("lastname")
* &#64;WSParamName("lastname")
* &#64;WSDocumentation("The users last name")
* public String lastname;
*
* public TestObject(String n, String l){
@ -53,31 +54,7 @@ import java.lang.reflect.Field;
* @author Ziver
*
*/
public class WSReturnObject{
/**
* Method comments for the WSDL.
* These comments are put in the operation part of the WSDL
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface WSDLDocumentation{
String value();
}
/**
* Annotation that assigns a name to the return value
* to the field.
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface WSValueName {
String value();
boolean optional() default false;
}
public abstract class WSReturnObject{
public Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException{
return field.get(this);

View file

@ -36,26 +36,33 @@ import java.util.Set;
* @author Ziver
*/
public class WebServiceDef {
/** A map of methods in this Service **/
private HashMap<String,WSMethodDef> methods;
/** This is the WSInterface class **/
private Class<? extends WSInterface> intf;
/** Namespace of the service **/
private String namespace;
/** Name of the web service **/
private String name;
/** This is the WSInterface class **/
private Class<? extends WSInterface> intf;
/** Human readable description of the service **/
private String documentation = "";
/** A map of methods in this Service **/
private HashMap<String,WSMethodDef> methods = new HashMap<>();
public WebServiceDef(Class<? extends WSInterface> intf){
this.intf = intf;
methods = new HashMap<>();
name = intf.getSimpleName();
if (intf.getAnnotation( WSInterface.WSNamespace.class) != null)
this.namespace = intf.getAnnotation(WSInterface.WSNamespace.class).value();
WSInterface.WSNamespace namespaceAnnotation = intf.getAnnotation(WSInterface.WSNamespace.class);
if (namespaceAnnotation != null)
this.namespace = namespaceAnnotation.value();
WSInterface.WSDocumentation documentationAnnotation = intf.getAnnotation(WSInterface.WSDocumentation.class);
if (documentationAnnotation != null)
this.documentation = documentationAnnotation.value();
for(Method m : intf.getDeclaredMethods()){
// check for public methods
// Check for public methods
if ((m.getModifiers() & Modifier.PUBLIC) > 0 &&
!m.isAnnotationPresent(WSInterface.WSIgnore.class)){
WSMethodDef method = new WSMethodDef(this, m);
@ -78,6 +85,13 @@ public class WebServiceDef {
return name;
}
/**
* @return a human readable description of the service, or a empty String if no documentation has been provided.
*/
public String getDocumentation(){
return documentation;
}
/**
* @param name is the name of the method
* @return if there is a method by the given name

View file

@ -0,0 +1,90 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.ws.openapi;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.net.ws.WebServiceDef;
import zutil.net.ws.wsdl.WSDLWriter;
import java.io.IOException;
import java.util.Map;
/**
* User: Ziver
*/
public class OpenAPIHttpPage implements HttpPage {
/**
* The WSDL document
**/
private WSDLWriter wsdl;
public OpenAPIHttpPage(WebServiceDef wsDef) {
wsdl = new WSDLWriter(wsDef);
}
public void respond(HttpPrintStream out,
HttpHeader headers,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
if (request.containsKey("json")) {
out.setHeader(HttpHeader.HEADER_CONTENT_TYPE, "application/json");
wsdl.write(out);
} else {
// Output human readable interface
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println(" <title>OpenAPI Documentation</title>");
out.println();
out.println(" <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.17.0/swagger-ui.css\">");
out.println(" <script src=\"https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js\"></script>");
out.println();
out.println(" <script>");
out.println(" function render() {");
out.println(" var ui = SwaggerUIBundle({");
out.println(" url: '" + headers.getRequestURL() + "?json',");
out.println(" dom_id: '#swagger-ui',");
out.println(" presets: [");
out.println(" SwaggerUIBundle.presets.apis,");
out.println(" SwaggerUIBundle.SwaggerUIStandalonePreset");
out.println(" ]");
out.println(" });");
out.println(" }");
out.println(" </script>");
out.println("</head>");
out.println("<body onload=\"render()\">");
out.println(" <div id=\"swagger-ui\"></div>");
out.println("</body>");
out.println("</html>");
}
}
}

View file

@ -0,0 +1,164 @@
package zutil.net.ws.openapi;
import zutil.log.LogUtil;
import zutil.net.ws.WSMethodDef;
import zutil.net.ws.WSParameterDef;
import zutil.net.ws.WebServiceDef;
import zutil.parser.DataNode;
import zutil.parser.json.JSONWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* A OpenAPI specification generator class.
*
* @see <a href="https://swagger.io/specification/">OpenAPI Specification</a>
*/
public class OpenAPIWriter {
private static final Logger logger = LogUtil.getLogger();
private static final String OPENAPI_VERSION = "3.0.1";
/** Current Web service definition **/
private WebServiceDef ws;
/** Current Web service definition **/
private List<ServerData> servers = new ArrayList<>();
/** Cache of generated WSDL **/
private String cache;
public OpenAPIWriter(WebServiceDef ws) {
this.ws = ws;
}
public void addServer(String url, String description){
servers.add(new ServerData(url, description));
cache = null;
}
public void write(Writer out) throws IOException {
out.write(write());
}
public void write(PrintStream out) {
out.print(write());
}
public void write(OutputStream out) throws IOException {
out.write(write().getBytes());
}
public String write() {
if (cache == null) {
DataNode root = new DataNode(DataNode.DataType.Map);
root.set("openapi", OPENAPI_VERSION);
root.set("info", generateInfo());
root.set("servers", generateServers());
root.set("paths", generatePaths());
root.set("components", generateComponents());
this.cache = JSONWriter.toString(root);
}
return cache;
}
private DataNode generateInfo() {
DataNode infoRoot = new DataNode(DataNode.DataType.Map);
infoRoot.set("title", ws.getName());
infoRoot.set("description", ws.getDocumentation());
// Not implemented properties
// "termsOfService": xxx,
// "contact": {"name": xxx,"url": xxx,"email": xxx},
// "license": {"name": xxx, "url": xxx},
// "version": xxx
return infoRoot;
}
private DataNode generateServers() {
DataNode serversRoot = new DataNode(DataNode.DataType.List);
for (ServerData data : servers) {
DataNode serverNode = new DataNode(DataNode.DataType.Map);
serverNode.set("url", data.url);
serverNode.set("description", data.description);
serversRoot.add(serverNode);
}
return serversRoot;
}
private DataNode generatePaths() {
DataNode pathsRoot = new DataNode(DataNode.DataType.Map);
for (WSMethodDef methodDef : ws.getMethods()) {
DataNode pathNode = new DataNode(DataNode.DataType.Map);
DataNode typeNode = new DataNode(DataNode.DataType.Map);
typeNode.set("description", methodDef.getDocumentation());
pathNode.set(methodDef.getRequestType().toString().toLowerCase(), typeNode);
// --------------------------------------------
// Inputs
// --------------------------------------------
DataNode parameterNode = new DataNode(DataNode.DataType.Map);
for (WSParameterDef parameterDef : methodDef.getInputs()) {
parameterNode.set("name", parameterDef.getName());
parameterNode.set("description", parameterDef.getDocumentation());
parameterNode.set("in", "query");
parameterNode.set("required", parameterDef.isOptional());
parameterNode.set("schema", "");
}
typeNode.set("parameters", parameterNode);
// --------------------------------------------
// Outputs
// --------------------------------------------
DataNode responseNode = new DataNode(DataNode.DataType.Map);
for (WSParameterDef parameterDef : methodDef.getOutputs()) {
parameterNode.set("name", parameterDef.getName());
parameterNode.set("description", parameterDef.getDocumentation());
parameterNode.set("in", "query");
parameterNode.set("required", parameterDef.isOptional());
parameterNode.set("schema", "");
}
typeNode.set("responses", responseNode);
}
return pathsRoot;
}
private DataNode generateComponents() {
DataNode componentsRoot = new DataNode(DataNode.DataType.Map);
DataNode schemasNode = new DataNode(DataNode.DataType.Map);
componentsRoot.set("schemas", schemasNode);
// Generate schemas
return componentsRoot;
}
protected static class ServerData {
String url;
String description;
protected ServerData(String url, String description) {
this.url = url;
this.description = description;
}
}
}

View file

@ -28,23 +28,17 @@ import zutil.io.IOUtil;
import zutil.log.LogUtil;
import zutil.net.http.HttpClient;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpHeaderParser;
import zutil.net.http.HttpURL;
import zutil.net.ws.WSInterface;
import zutil.net.ws.WSMethodDef;
import zutil.net.ws.WSParameterDef;
import zutil.net.ws.WebServiceDef;
import zutil.net.ws.soap.SOAPHttpPage;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
import javax.naming.OperationNotSupportedException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
@ -80,10 +74,10 @@ public class RESTClientInvocationHandler implements InvocationHandler {
String requestType = "GET";
switch (methodDef.getRequestType()) {
case HTTP_GET: requestType = "GET"; break;
case HTTP_PUT: requestType = "PUT"; break;
case HTTP_POST: requestType = "POST"; break;
case HTTP_DELETE: requestType = "DELETE"; break;
case GET: requestType = "GET"; break;
case PUT: requestType = "PUT"; break;
case POST: requestType = "POST"; break;
case DELETE: requestType = "DELETE"; break;
}
// Send request

View file

@ -31,13 +31,13 @@ import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;
import zutil.ClassUtil;
import zutil.converter.Converter;
import zutil.log.LogUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.net.ws.*;
import zutil.net.ws.WSReturnObject.WSValueName;
import zutil.parser.Base64Encoder;
import java.io.BufferedReader;
@ -127,10 +127,12 @@ public class SOAPHttpPage implements HttpPage{
// Read http body
StringBuilder data = null;
String contentType = headers.getHeader("Content-Type");
if (contentType != null &&
(contentType.contains("application/soap+xml") ||
contentType.contains("text/xml") ||
contentType.contains("text/plain"))) {
int post_data_length = Integer.parseInt(headers.getHeader("Content-Length"));
BufferedReader in = new BufferedReader(new InputStreamReader(headers.getInputStream()));
data = new StringBuilder(post_data_length);
@ -140,7 +142,7 @@ public class SOAPHttpPage implements HttpPage{
}
// Response
out.setHeader("Content-Type", "text/xml");
out.setHeader(HttpHeader.HEADER_CONTENT_TYPE, "text/xml");
out.flush();
WSInterface obj;
@ -151,8 +153,7 @@ public class SOAPHttpPage implements HttpPage{
obj = wsDef.newInstance();
session.put("SOAPInterface", obj);
}
}
else {
} else {
if (ws == null)
ws = wsDef.newInstance();
obj = ws;
@ -312,9 +313,6 @@ public class SOAPHttpPage implements HttpPage{
}
/**
* Generates a XML Element for a given Object. This method can
* handle return values as XML Elements, WSReturnObject and
@ -342,7 +340,7 @@ public class SOAPHttpPage implements HttpPage{
arrayType = arrayType.replaceFirst("\\[\\]", "[" + Array.getLength(obj) + "]");
array.addAttribute("type", "soap:Array");
array.addAttribute("soap:arrayType", arrayType);
array.addAttribute("soap:arrayType", "xsd:" + arrayType);
for(int i=0; i<Array.getLength(obj) ;i++) {
generateSOAPXMLForObj(array, Array.get(obj, i), "element");
}
@ -354,10 +352,9 @@ public class SOAPHttpPage implements HttpPage{
else if (obj instanceof WSReturnObject) {
Field[] fields = obj.getClass().getFields();
for(int i=0; i<fields.length; i++) {
WSValueName tmp = fields[i].getAnnotation( WSValueName.class );
String name;
if (tmp != null) name = tmp.value();
else name = "field"+i;
WSInterface.WSParamName paramNameAnnotation = fields[i].getAnnotation(WSInterface.WSParamName.class);
String name = (paramNameAnnotation != null ? paramNameAnnotation.value() : "field" + i);
generateSOAPXMLForObj(objectE, fields[i].get(obj), name);
}
}
@ -368,30 +365,28 @@ public class SOAPHttpPage implements HttpPage{
}
}
protected static String getSOAPClassName(Class<?> c) {
Class<?> cTmp = getClass(c);
/**
* Will generate a SOAP based class name from a given class.
*
* @param c
* @return a String name that can be used by a SOAP call.
*/
public static String getSOAPClassName(Class<?> c) {
Class<?> cTmp = ClassUtil.getArrayClass(c);
if (byte[].class.isAssignableFrom(c)) {
return "base64Binary";
}
else if (WSReturnObject.class.isAssignableFrom(cTmp)) {
} else if (WSReturnObject.class.isAssignableFrom(cTmp)) {
return c.getSimpleName();
}
else {
} else {
String ret = c.getSimpleName().toLowerCase();
if (cTmp == Integer.class) ret = ret.replaceAll("integer", "int");
else if(cTmp == Character.class) ret = ret.replaceAll("character", "char");
if (cTmp == Integer.class)
ret = ret.replaceAll("integer", "int");
else if(cTmp == Character.class)
ret = ret.replaceAll("character", "char");
return ret;
}
}
protected static Class<?> getClass(Class<?> c) {
if (c!=null && c.isArray()) {
return getClass(c.getComponentType());
}
return c;
}
}

View file

@ -39,16 +39,19 @@ public class WSDLHttpPage implements HttpPage {
/** The WSDL document **/
private WSDLWriter wsdl;
public WSDLHttpPage(WebServiceDef wsDef) {
wsdl = new WSDLWriter(wsDef);
}
public void respond(HttpPrintStream out,
HttpHeader headers,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
out.setHeader("Content-Type", "text/xml");
out.setHeader(HttpHeader.HEADER_CONTENT_TYPE, "text/xml");
wsdl.write(out);
}
}

View file

@ -36,10 +36,12 @@ public abstract class WSDLService {
/** The URL of this service **/
private String url;
public WSDLService(String url){
this.url = url;
}
public String getServiceAddress(){
return url;
}

View file

@ -36,6 +36,7 @@ public class WSDLServiceSOAP extends WSDLService{
super(url);
}
@Override
public String getServiceType() { return "soap"; }
@ -57,7 +58,10 @@ public class WSDLServiceSOAP extends WSDLService{
Element soap_operation = operation.addElement("soap:operation");
soap_operation.addAttribute("soapAction", method.getNamespace());
//*************************** Input
// ------------------------------------------------
// Input
// ------------------------------------------------
// definitions -> binding -> operation -> input
Element input = operation.addElement("wsdl:input");
// definitions -> binding -> operation -> input -> body
@ -65,7 +69,10 @@ public class WSDLServiceSOAP extends WSDLService{
input_body.addAttribute("use", "literal");
input_body.addAttribute("namespace", method.getNamespace());
//*************************** output
// ------------------------------------------------
// Output
// ------------------------------------------------
if(!method.getOutputs().isEmpty()){
// definitions -> binding -> operation -> output
Element output = operation.addElement("wsdl:output");

View file

@ -29,30 +29,34 @@ import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import zutil.ClassUtil;
import zutil.io.StringOutputStream;
import zutil.net.ws.WSMethodDef;
import zutil.net.ws.WSParameterDef;
import zutil.net.ws.WSReturnObject;
import zutil.net.ws.WSReturnObject.WSValueName;
import zutil.net.ws.WebServiceDef;
import zutil.log.LogUtil;
import zutil.net.ws.*;
import zutil.net.ws.soap.SOAPHttpPage;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WSDLWriter {
/** Current Web service definition ***/
private static final Logger logger = LogUtil.getLogger();
/** Current Web service definition **/
private WebServiceDef ws;
/** A list of services **/
private ArrayList<WSDLService> services = new ArrayList<>();
/** Cache of generated WSDL **/
private String cache;
/** A list of services **/
private ArrayList<WSDLService> services;
public WSDLWriter(WebServiceDef ws) {
this.services = new ArrayList<>();
this.ws = ws;
}
/**
* Add a service to be published with the WSDL
*/
@ -63,17 +67,18 @@ public class WSDLWriter{
public void write(Writer out) throws IOException {
out.write(generate());
out.write(write());
}
public void write(PrintStream out) {
out.print(generate());
out.print(write());
}
public void write(OutputStream out) throws IOException {
out.write(generate().getBytes() );
out.write(write().getBytes());
}
private String generate(){
public String write() {
if (cache == null) {
try {
OutputFormat outformat = OutputFormat.createPrettyPrint();
@ -87,12 +92,13 @@ public class WSDLWriter{
this.cache = out.toString();
out.close();
} catch (IOException e) {
e.printStackTrace();
logger.log(Level.SEVERE, "Unable to generate WSDL specification.", e);
}
}
return cache;
}
private Document generateDefinition() {
Document wsdl = DocumentHelper.createDocument();
Element definitions = wsdl.addElement("wsdl:definitions");
@ -119,6 +125,7 @@ public class WSDLWriter{
}
// Default message used for functions without input parameters
// definitions -> message: empty
Element empty = definitions.addElement("wsdl:message");
empty.addAttribute("name", "empty");
@ -128,6 +135,7 @@ public class WSDLWriter{
empty_part.addAttribute("type", "td:empty");
// Exception message
// definitions -> message: exception
Element exception = definitions.addElement("wsdl:message");
exception.addAttribute("name", "exception");
@ -138,7 +146,10 @@ public class WSDLWriter{
}
private void generateMessage(Element parent, WSMethodDef method) {
//*************************** Input
// ------------------------------------------------
// Input
// ------------------------------------------------
if (!method.getInputs().isEmpty()) {
// definitions -> message
Element input = parent.addElement("wsdl:message");
@ -149,13 +160,17 @@ public class WSDLWriter{
// definitions -> message -> part
Element part = input.addElement("wsdl:part");
part.addAttribute("name", param.getName());
part.addAttribute("type", "xsd:"+getClassName( param.getParamClass()));
part.addAttribute("type", "xsd:" + SOAPHttpPage.getSOAPClassName(param.getParamClass()));
if (param.isOptional())
part.addAttribute("minOccurs", "0");
}
}
//*************************** Output
// ------------------------------------------------
// Output
// ------------------------------------------------
if (!method.getOutputs().isEmpty()) {
// definitions -> message
Element output = parent.addElement("wsdl:message");
@ -168,7 +183,7 @@ public class WSDLWriter{
part.addAttribute("name", param.getName());
Class<?> paramClass = param.getParamClass();
Class<?> valueClass = getClass( paramClass );
Class<?> valueClass = ClassUtil.getArrayClass(paramClass);
// is an binary array
if (byte[].class.isAssignableFrom(paramClass)) {
part.addAttribute("type", "xsd:base64Binary");
@ -176,13 +191,11 @@ public class WSDLWriter{
// is an array?
else if (paramClass.isArray()) {
part.addAttribute("type", "td:" + getArrayClassName(paramClass));
}
else if( WSReturnObject.class.isAssignableFrom(valueClass) ){
} else if (WSReturnObject.class.isAssignableFrom(valueClass)) {
// its an SOAPObject
part.addAttribute("type", "td:"+getClassName( paramClass ));
}
else{// its an Object
part.addAttribute("type", "xsd:"+getClassName( paramClass ));
part.addAttribute("type", "td:" + SOAPHttpPage.getSOAPClassName(paramClass));
} else {// its an Object
part.addAttribute("type", "xsd:" + SOAPHttpPage.getSOAPClassName(paramClass));
}
}
}
@ -199,24 +212,30 @@ public class WSDLWriter{
operation.addAttribute("name", method.getName());
// Documentation
if (method.getDocumentation() != null) {
Element doc = operation.addElement("wsdl:documentation");
doc.setText(method.getDocumentation());
}
//*************************** Input
// Input
if (method.getInputs().size() > 0) {
// definitions -> message
Element input = operation.addElement("wsdl:input");
input.addAttribute("message", "tns:" + method.getName() + "Request");
}
//*************************** Output
// Output
if (method.getOutputs().size() > 0) {
// definitions -> message
Element output = operation.addElement("wsdl:output");
output.addAttribute("message", "tns:" + method.getName() + "Response");
}
//*************************** Fault
// Fault
if (method.getOutputs().size() > 0) {
// definitions -> message
Element fault = operation.addElement("wsdl:fault");
@ -273,7 +292,7 @@ public class WSDLWriter{
if (!method.getOutputs().isEmpty()) {
for (WSParameterDef param : method.getOutputs()) {
Class<?> paramClass = param.getParamClass();
Class<?> valueClass = getClass(paramClass);
Class<?> valueClass = ClassUtil.getArrayClass(paramClass);
// is an array? or special class
if (paramClass.isArray() || WSReturnObject.class.isAssignableFrom(valueClass)) {
// add to type generation list
@ -294,11 +313,10 @@ public class WSDLWriter{
empty.addAttribute("name", "empty");
empty.addElement("xsd:sequence");
for(int n=0; n<types.size() ;n++){
Class<?> c = types.get(n);
for (Class<?> c : types) {
// Generate Array type
if (c.isArray()) {
Class<?> ctmp = getClass(c);
Class<?> ctmp = ClassUtil.getArrayClass(c);
Element type = schema.addElement("xsd:complexType");
type.addAttribute("name", getArrayClassName(c));
@ -311,9 +329,9 @@ public class WSDLWriter{
element.addAttribute("name", "element");
element.addAttribute("nillable", "true");
if (WSReturnObject.class.isAssignableFrom(ctmp))
element.addAttribute("type", "tns:"+getClassName(c).replace("[]", ""));
element.addAttribute("type", "tns:" + SOAPHttpPage.getSOAPClassName(c).replace("[]", ""));
else
element.addAttribute("type", "xsd:"+getClassName(c).replace("[]", ""));
element.addAttribute("type", "xsd:" + SOAPHttpPage.getSOAPClassName(c).replace("[]", ""));
if (!types.contains(ctmp))
types.add(ctmp);
@ -321,30 +339,33 @@ public class WSDLWriter{
// Generate SOAPObject type
else if (WSReturnObject.class.isAssignableFrom(c)) {
Element type = schema.addElement("xsd:complexType");
type.addAttribute("name", getClassName(c));
type.addAttribute("name", SOAPHttpPage.getSOAPClassName(c));
Element sequence = type.addElement("xsd:sequence");
Field[] fields = c.getFields();
for (int i = 0; i < fields.length; i++) {
WSValueName tmp = fields[i].getAnnotation( WSValueName.class );
WSInterface.WSParamName tmp = fields[i].getAnnotation(WSInterface.WSParamName.class);
String name;
if(tmp != null) name = tmp.value();
else name = "field"+i;
if (tmp != null)
name = tmp.value();
else
name = "field" + i;
Element element = sequence.addElement("xsd:element");
element.addAttribute("name", name);
// Check if the object is an SOAPObject
Class<?> cTmp = getClass(fields[i].getType());
Class<?> cTmp = ClassUtil.getArrayClass(fields[i].getType());
if (WSReturnObject.class.isAssignableFrom(cTmp)) {
element.addAttribute("type", "tns:"+getClassName(cTmp));
element.addAttribute("type", "tns:" + SOAPHttpPage.getSOAPClassName(cTmp));
if (!types.contains(cTmp))
types.add(cTmp);
} else {
element.addAttribute("type", "xsd:" + SOAPHttpPage.getSOAPClassName(fields[i].getType()));
}
else{
element.addAttribute("type", "xsd:"+getClassName(fields[i].getType()));
}
// Is the Field optional
if (tmp != null && tmp.optional())
element.addAttribute("minOccurs", "0");
@ -353,40 +374,7 @@ public class WSDLWriter{
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// TODO: FIX THESE ARE DUPLICATES FROM SOAPHttpPage
///////////////////////////////////////////////////////////////////////////////////////////////
private Class<?> getClass(Class<?> c){
if(c!=null && c.isArray()){
return getClass(c.getComponentType());
}
return c;
}
private String getArrayClassName(Class<?> c) {
return "ArrayOf"+getClassName(c).replaceAll("[\\[\\]]", "");
}
private String getClassName(Class<?> c){
Class<?> cTmp = getClass(c);
if( byte[].class.isAssignableFrom(c) ){
return "base64Binary";
}
else if( WSReturnObject.class.isAssignableFrom(cTmp) ){
return c.getSimpleName();
}
else{
String ret = c.getSimpleName().toLowerCase();
if( cTmp == Integer.class ) ret = ret.replaceAll("integer", "int");
else if( cTmp == Character.class ) ret = ret.replaceAll("character", "char");
return ret;
return "ArrayOf" + SOAPHttpPage.getSOAPClassName(c).replaceAll("[\\[\\]]", "");
}
}
public void close() {}
}