Cleaned up WS interfaces

This commit is contained in:
Ziver Koc 2018-07-05 16:58:02 +02:00
parent 1f8d5cfe2a
commit beb0ce754e
10 changed files with 121 additions and 146 deletions

View file

@ -32,29 +32,31 @@ import java.lang.annotation.Target;
*
* Specifies web service definitions. Which methods that will
* be published and other related metadata.
* Only public and non static methods will be published or
* the WSIgnore annotation can be used to ignore the specific method.
*
* Example:
* <pre>
* private static class Test implements WSInterface{
* public Test(){}
*
* &#64;WSDocumentation("blabla")
* &#64;WSDLParamDocumentation("olle = a variable?")
* &#64;WSDocumentation("This is a description of the method")
* &#64;WSDLParamDocumentation("arg1 = variable description?")
* public void pubZ(
* &#64;WSParamName("olle") int lol)
* &#64;WSParamName("arg1") int randomName)
* throws Exception{
* ....
* }
*
* &#64;WSReturnName("param")
* public String pubA(
* &#64;WSParamName(value="lol", optional=true) String lol)
* &#64;WSParamName(value="optArg", optional=true) String optionalParam)
* throws Exception{
* ....
* }
*
* &#64;WSIgnore()
* public void privaZ(....){
* public void privatZ(....){
* ...
* }
* }
@ -129,7 +131,7 @@ public interface WSInterface {
@interface WSHeader { }
/**
* Specifies the name space for method.
* Specifies the name space for the method.
*
* @author Ziver
*/

View file

@ -64,7 +64,7 @@ public class WSMethodDef {
* @param me is a method in a class that implements WSInterface
*/
protected WSMethodDef( WebServiceDef wsDef, Method me) {
if( !WSInterface.class.isAssignableFrom(me.getDeclaringClass()) )
if (!WSInterface.class.isAssignableFrom(me.getDeclaringClass()))
throw new ClassCastException("Declaring class does not implement WSInterface!");
this.wsDef = wsDef;
method = me;
@ -74,12 +74,12 @@ public class WSMethodDef {
name = method.getName();
//***** Documentation & Namespace
WSDocumentation tmpDoc = method.getAnnotation( WSDocumentation.class );
if(tmpDoc != null){
WSDocumentation tmpDoc = method.getAnnotation(WSDocumentation.class);
if (tmpDoc != null){
doc = tmpDoc.value();
}
WSNamespace tmpSpace = method.getAnnotation( WSNamespace.class );
if( tmpSpace != null )
WSNamespace tmpSpace = method.getAnnotation(WSNamespace.class);
if ( tmpSpace != null )
namespace = tmpSpace.value();
else
namespace = wsDef.getNamespace()+"?#"+name;
@ -91,10 +91,10 @@ public class WSMethodDef {
Annotation[][] paramAnnotation = method.getParameterAnnotations();
Class<?>[] inputTypes = method.getParameterTypes();
for(int i=0; i<paramAnnotation.length ;i++){
for (int i=0; i<paramAnnotation.length ;i++){
WSParameterDef param = new WSParameterDef( this );
for(Annotation annotation : paramAnnotation[i]){
if(annotation instanceof WSInterface.WSParamName){
for (Annotation annotation : paramAnnotation[i]){
if (annotation instanceof WSInterface.WSParamName){
WSInterface.WSParamName paramName = (WSInterface.WSParamName) annotation;
param.setName( paramName.value() );
param.setOptional( paramName.optional() );
@ -102,7 +102,7 @@ public class WSMethodDef {
}
param.setParamClass( inputTypes[i] );
// if no name was found then use default
if(param.getName() == null)
if (param.getName() == null)
param.setName( "args"+i );
inputs.add( param );
@ -110,11 +110,11 @@ public class WSMethodDef {
//******** The return parameter name ************
WSInterface.WSReturnName returnName = method.getAnnotation(WSInterface.WSReturnName.class);
if( WSReturnObject.class.isAssignableFrom( method.getReturnType() ) ){
if (WSReturnObject.class.isAssignableFrom( method.getReturnType())){
Class<?> retClass = method.getReturnType();
Field[] fields = retClass.getFields();
for(int i=0; i<fields.length ;i++){
for (int i=0; i<fields.length ;i++){
WSParameterDef ret_param = new WSParameterDef( this );
WSReturnObject.WSValueName retValName = fields[i]
.getAnnotation( WSReturnObject.WSValueName.class );
@ -128,7 +128,7 @@ public class WSMethodDef {
}
else if( method.getReturnType() != void.class ){
WSParameterDef ret_param = new WSParameterDef( this );
if(returnName != null)
if (returnName != null)
ret_param.setName(returnName.value());
else
ret_param.setName("return");
@ -144,13 +144,6 @@ public class WSMethodDef {
return name;
}
/**
* @return the number of exceptions this method throws
*/
public int exceptionCount(){
return exceptions.size();
}
/**
* @return a list of exceptions this method throws
*/
@ -158,13 +151,6 @@ public class WSMethodDef {
return exceptions;
}
/**
* @return the number of parameters for this method
*/
public int getInputCount(){
return inputs.size();
}
/**
* @return a list of input parameters
*/
@ -172,21 +158,6 @@ public class WSMethodDef {
return inputs;
}
/**
* @param index is a index
* @return a {@link WSParameterDef} object in the given index
*/
public WSParameterDef getInput( int index ){
return inputs.get( index );
}
/**
* @return the number of parameters for this method
*/
public int getOutputCount(){
return outputs.size();
}
/**
* @return a list of input parameters
*/
@ -194,14 +165,6 @@ public class WSMethodDef {
return outputs;
}
/**
* @param index is a index
* @return a {@link WSParameterDef} object in the given index
*/
public WSParameterDef getOutput( int index ){
return outputs.get( index );
}
/**
* @return Documentation of the method if one exists or else null
*/
@ -210,15 +173,12 @@ public class WSMethodDef {
}
/**
* @return the namespace of the method
* @return the namespace or endpoint url of the method
*/
public String getNamespace(){
return namespace;
}
public WebServiceDef getWebService(){
return wsDef;
}
/**
* Invokes a specified method
@ -235,8 +195,8 @@ public class WSMethodDef {
StringBuilder tmp = new StringBuilder();
boolean first = true;
tmp.append(name).append("(");
for(WSParameterDef param : inputs){
if(first)
for (WSParameterDef param : inputs){
if (first)
first = false;
else
tmp.append(" ,");
@ -246,8 +206,8 @@ public class WSMethodDef {
}
tmp.append(") => ");
first = true;
for(WSParameterDef param : outputs){
if(first)
for (WSParameterDef param : outputs){
if (first)
first = false;
else
tmp.append(" ,");

View file

@ -51,12 +51,12 @@ public class WebServiceDef {
methods = new HashMap<>();
name = intf.getSimpleName();
if( intf.getAnnotation( WSInterface.WSNamespace.class ) != null )
this.namespace = intf.getAnnotation( WSInterface.WSNamespace.class ).value();
if (intf.getAnnotation( WSInterface.WSNamespace.class) != null)
this.namespace = intf.getAnnotation(WSInterface.WSNamespace.class).value();
for(Method m : intf.getDeclaredMethods()){
// check for public methods
if((m.getModifiers() & Modifier.PUBLIC) > 0 &&
if ((m.getModifiers() & Modifier.PUBLIC) > 0 &&
!m.isAnnotationPresent(WSInterface.WSIgnore.class)){
WSMethodDef method = new WSMethodDef(this, m);
methods.put(method.getName(), method);

View file

@ -39,6 +39,7 @@ 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;
@ -97,8 +98,9 @@ public class RESTClientInvocationHandler implements InvocationHandler {
+ (serviceUrl.getPath().endsWith("/") ? "" : "/")
+ methodDef.getName());
for (int i = 0; i < methodDef.getOutputCount(); i++) {
WSParameterDef param = methodDef.getOutput(i);
List<WSParameterDef> params = methodDef.getOutputs();
for (int i = 0; i < params.size(); i++) {
WSParameterDef param = params.get(i);
url.setParameter(param.getName(), args[i].toString());
}

View file

@ -36,6 +36,7 @@ import zutil.net.ws.WebServiceDef;
import zutil.parser.json.JSONObjectOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
@ -71,32 +72,33 @@ public class RESTHttpPage implements HttpPage {
protected String execute(String targetMethod, Map<String, String> input) throws Exception {
if( wsDef.hasMethod(targetMethod) ){
if (wsDef.hasMethod(targetMethod)) {
// Parse request
WSMethodDef m = wsDef.getMethod(targetMethod);
Object[] params = prepareInputParams(m, input);
Object[] inputParams = prepareInputParams(m, input);
// Invoke
Object ret = m.invoke(ws, params);
Object ret = m.invoke(ws, inputParams);
// Generate Response
StringOutputStream dummyOut = new StringOutputStream();
JSONObjectOutputStream out = new JSONObjectOutputStream(dummyOut);
StringOutputStream strBuffer = new StringOutputStream();
JSONObjectOutputStream out = new JSONObjectOutputStream(strBuffer);
out.enableMetaData(false);
out.writeObject(ret);
out.close();
return dummyOut.toString();
return strBuffer.toString();
}
return "{error: \"Unknown target: "+targetMethod+"\"}";
}
private Object[] prepareInputParams(WSMethodDef method, Map<String, String> input){
Object[] inputParams = new Object[method.getInputCount()];
private Object[] prepareInputParams(WSMethodDef methodDef, Map<String, String> input){
List<WSParameterDef> inputParamDefs = methodDef.getInputs();
Object[] inputParams = new Object[inputParamDefs.size()];
// Get the parameter values
for(int i=0; i<method.getInputCount() ;i++){
WSParameterDef param = method.getInput( i );
if( input.containsKey(param.getName()) ){
for (int i=0; i<inputParamDefs.size(); i++){
WSParameterDef param = inputParamDefs.get(i);
if (input.containsKey(param.getName())){
inputParams[i] = Converter.fromString(
input.get(param.getName()),
param.getParamClass());

View file

@ -40,6 +40,7 @@ import zutil.net.ws.WebServiceDef;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -108,8 +109,10 @@ public class SOAPClientInvocationHandler implements InvocationHandler {
Element method = body.addElement("");
method.addNamespace("m", methodDef.getNamespace());
method.setName("m:" + methodDef.getName() + "Request");
for (int i = 0; i < methodDef.getOutputCount(); i++) {
WSParameterDef param = methodDef.getOutput(i);
List<WSParameterDef> outputParamDefs = methodDef.getOutputs();
for (int i = 0; i < outputParamDefs.size(); i++) {
WSParameterDef param = outputParamDefs.get(i);
SOAPHttpPage.generateSOAPXMLForObj(method, args[i], param.getName());
}

View file

@ -45,6 +45,7 @@ import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -90,7 +91,7 @@ public class SOAPHttpPage implements HttpPage{
/** Session enabled **/
private boolean session_enabled;
public SOAPHttpPage( WebServiceDef wsDef ){
public SOAPHttpPage( WebServiceDef wsDef ) {
this.wsDef = wsDef;
this.session_enabled = false;
}
@ -103,7 +104,7 @@ public class SOAPHttpPage implements HttpPage{
*
* @param enabled is if session should be enabled
*/
public void enableSession(boolean enabled){
public void enableSession(boolean enabled) {
this.session_enabled = enabled;
}
@ -143,16 +144,16 @@ public class SOAPHttpPage implements HttpPage{
out.flush();
WSInterface obj;
if(session_enabled){
if( session.containsKey("SOAPInterface"))
if (session_enabled) {
if ( session.containsKey("SOAPInterface"))
obj = (WSInterface)session.get("SOAPInterface");
else{
else {
obj = wsDef.newInstance();
session.put("SOAPInterface", obj);
}
}
else{
if( ws == null )
else {
if (ws == null)
ws = wsDef.newInstance();
obj = ws;
}
@ -165,7 +166,7 @@ public class SOAPHttpPage implements HttpPage{
// DEBUG
if( logger.isLoggable(Level.FINEST) ){
if (logger.isLoggable(Level.FINEST)) {
System.out.println("********** Request");
System.out.println(request);
System.out.println("********** Response");
@ -183,10 +184,10 @@ public class SOAPHttpPage implements HttpPage{
* @param xml is the XML request
* @return a Document with the response
*/
public Document genSOAPResponse(String xml){
public Document genSOAPResponse(String xml) {
try {
WSInterface obj;
if( ws == null )
if ( ws == null )
ws = wsDef.newInstance();
obj = ws;
@ -197,7 +198,7 @@ public class SOAPHttpPage implements HttpPage{
return null;
}
protected Document genSOAPResponse(String xml, WSInterface obj){
protected Document genSOAPResponse(String xml, WSInterface obj) {
Document document = DocumentHelper.createDocument();
Element envelope = document.addElement("soap:Envelope");
try {
@ -206,29 +207,29 @@ public class SOAPHttpPage implements HttpPage{
envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
Element body = envelope.addElement( "soap:Body" );
try{
try {
Element request = getXMLRoot(xml);
if(request == null) return document;
if (request == null) return document;
// Header
if( request.element("Header") != null){
if ( request.element("Header") != null) {
Element header = envelope.addElement( "soap:Header" );
prepareInvoke( obj, request.element("Header"), header );
}
// Body
if( request.element("Body") != null){
if ( request.element("Body") != null) {
prepareInvoke( obj, request.element("Body"), body );
}
}catch(Throwable e){
} catch(Throwable e) {
body.clearContent();
Element fault = body.addElement("soap:Fault");
// The fault source
if(e instanceof SOAPException || e instanceof SAXException || e instanceof DocumentException)
if (e instanceof SOAPException || e instanceof SAXException || e instanceof DocumentException)
fault.addElement("faultcode").setText( "soap:Client" );
else
fault.addElement("faultcode").setText( "soap:Server" );
// The fault message
if( e.getMessage() == null || e.getMessage().isEmpty())
if ( e.getMessage() == null || e.getMessage().isEmpty())
fault.addElement("faultstring").setText( ""+e.getClass().getSimpleName() );
else
fault.addElement("faultstring").setText( ""+e.getMessage() );
@ -248,7 +249,7 @@ public class SOAPHttpPage implements HttpPage{
* @return the XML root Element
*/
protected static Element getXMLRoot(String xml) throws DocumentException {
if(xml != null && !xml.isEmpty()){
if (xml != null && !xml.isEmpty()) {
Document document = DocumentHelper.parseText(xml);
return document.getRootElement();
}
@ -265,44 +266,46 @@ public class SOAPHttpPage implements HttpPage{
@SuppressWarnings("unchecked")
private void prepareInvoke(WSInterface obj, Element requestRoot, Element responseRoot) throws Throwable{
Iterator<Element> it = requestRoot.elementIterator();
while( it.hasNext() ){
while(it.hasNext()) {
Element e = it.next();
if( wsDef.hasMethod( e.getQName().getName()) ){
WSMethodDef m = wsDef.getMethod( e.getQName().getName() );
Object[] params = new Object[ m.getInputCount() ];
if (wsDef.hasMethod( e.getQName().getName())) {
WSMethodDef methodDef = wsDef.getMethod(e.getQName().getName());
List<WSParameterDef> inputParamDefs = methodDef.getInputs();
Object[] inputParams = new Object[inputParamDefs.size()];
// Get the parameter values
for(int i=0; i<m.getInputCount() ;i++){
WSParameterDef param = m.getInput( i );
if( e.element(param.getName()) != null ){
params[i] = Converter.fromString(
for(int i=0; i<inputParamDefs.size() ;i++) {
WSParameterDef param = inputParamDefs.get(i);
if ( e.element(param.getName()) != null ) {
inputParams[i] = Converter.fromString(
e.element(param.getName()).getTextTrim(),
param.getParamClass());
}
}
// Invoke
Object ret = m.invoke(obj, params);
Object outputParams = methodDef.invoke(obj, inputParams);
List<WSParameterDef> outputParamDefs = methodDef.getOutputs();
// generate response XML
if( m.getOutputCount()>0 ){
if (outputParamDefs.size() > 0) {
Element response = responseRoot.addElement("");
response.addNamespace("m", m.getNamespace() );
response.setName("m:"+m.getName()+"Response");
response.addNamespace("m", methodDef.getNamespace() );
response.setName("m:"+methodDef.getName()+"Response");
if( ret instanceof WSReturnObject ){
Field[] f = ret.getClass().getFields();
for(int i=0; i<m.getOutputCount() ;i++){
WSParameterDef param = m.getOutput( i );
generateSOAPXMLForObj(response,((WSReturnObject)ret).getValue(f[i]) , param.getName());
if (outputParams instanceof WSReturnObject) {
Field[] f = outputParams.getClass().getFields();
for(int i=0; i<outputParamDefs.size() ;i++) {
WSParameterDef param = outputParamDefs.get(i);
generateSOAPXMLForObj(response,((WSReturnObject)outputParams).getValue(f[i]) , param.getName());
}
}
else{
generateSOAPXMLForObj(response, ret, m.getOutput(0).getName());
else {
generateSOAPXMLForObj(response, outputParams, methodDef.getOutputs().get(0).getName());
}
}
}
else{
else {
throw new NoSuchMethodException("Unable to find method: "+e.getQName().getName()+"!");
}
}
@ -322,68 +325,70 @@ public class SOAPHttpPage implements HttpPage{
* @param elementName is the name of the parent Element
*/
protected static void generateSOAPXMLForObj(Element root, Object obj, String elementName) throws IllegalArgumentException, IllegalAccessException{
if(obj == null) return;
if(byte[].class.isAssignableFrom(obj.getClass())){
if (obj == null) return;
// Return binary data
if (byte[].class.isAssignableFrom(obj.getClass())) {
Element valueE = root.addElement( elementName );
valueE.addAttribute("type", "xsd:"+ getSOAPClassName(obj.getClass()));
String tmp = Base64Encoder.encode((byte[])obj);
tmp = tmp.replaceAll("\\s", "");
valueE.setText(tmp);
}
// return an array
else if(obj.getClass().isArray()){
// Return an array
else if (obj.getClass().isArray()) {
Element array = root.addElement( (elementName.equals("element") ? "Array" : elementName) );
String arrayType = "xsd:"+ getSOAPClassName(obj.getClass());
arrayType = arrayType.replaceFirst("\\[\\]", "["+Array.getLength(obj)+"]");
array.addAttribute("type", "soap:Array");
array.addAttribute("soap:arrayType", arrayType);
for(int i=0; i<Array.getLength(obj) ;i++){
for(int i=0; i<Array.getLength(obj) ;i++) {
generateSOAPXMLForObj(array, Array.get(obj, i), "element");
}
}
else{
else {
Element objectE = root.addElement( elementName );
if(obj instanceof Element)
if (obj instanceof Element)
objectE.add( (Element)obj );
else if(obj instanceof WSReturnObject){
else if (obj instanceof WSReturnObject) {
Field[] fields = obj.getClass().getFields();
for(int i=0; i<fields.length ;i++){
for(int i=0; i<fields.length ;i++) {
WSValueName tmp = fields[i].getAnnotation( WSValueName.class );
String name;
if(tmp != null) name = tmp.value();
if (tmp != null) name = tmp.value();
else name = "field"+i;
generateSOAPXMLForObj(objectE, fields[i].get(obj), name);
}
}
else {
objectE.addAttribute("type", "xsd:"+ getSOAPClassName(obj.getClass()));
objectE.addText( ""+obj );
objectE.addText("" + obj);
}
}
}
protected static String getSOAPClassName(Class<?> c){
protected static String getSOAPClassName(Class<?> c) {
Class<?> cTmp = getClass(c);
if(byte[].class.isAssignableFrom(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()){
protected static Class<?> getClass(Class<?> c) {
if (c!=null && c.isArray()) {
return getClass(c.getComponentType());
}
return c;

View file

@ -66,7 +66,7 @@ public class WSDLServiceSOAP extends WSDLService{
input_body.addAttribute("namespace", method.getNamespace());
//*************************** output
if( method.getOutputCount() > 0 ){
if(!method.getOutputs().isEmpty()){
// definitions -> binding -> operation -> output
Element output = operation.addElement("wsdl:output");
// definitions -> binding -> operation -> input -> body

View file

@ -139,7 +139,7 @@ public class WSDLWriter{
private void generateMessage(Element parent, WSMethodDef method){
//*************************** Input
if( method.getInputCount() > 0 ){
if(!method.getInputs().isEmpty()){
// definitions -> message
Element input = parent.addElement("wsdl:message");
input.addAttribute("name", method.getName()+"Request");
@ -156,7 +156,7 @@ public class WSDLWriter{
}
}
//*************************** Output
if( method.getOutputCount() > 0 ){
if(!method.getOutputs().isEmpty()){
// definitions -> message
Element output = parent.addElement("wsdl:message");
output.addAttribute("name", method.getName()+"Response");
@ -205,19 +205,19 @@ public class WSDLWriter{
}
//*************************** Input
if( method.getInputCount() > 0 ){
if( method.getInputs().size() > 0 ){
// definitions -> message
Element input = operation.addElement("wsdl:input");
input.addAttribute("message", "tns:"+method.getName()+"Request");
}
//*************************** Output
if( method.getOutputCount() > 0 ){
if( method.getOutputs().size() > 0 ){
// definitions -> message
Element output = operation.addElement("wsdl:output");
output.addAttribute("message", "tns:"+method.getName()+"Response");
}
//*************************** Fault
if( method.getOutputCount() > 0 ){
if( method.getOutputs().size() > 0 ){
// definitions -> message
Element fault = operation.addElement("wsdl:fault");
fault.addAttribute("message", "tns:exception");
@ -270,7 +270,7 @@ public class WSDLWriter{
ArrayList<Class<?>> types = new ArrayList<>();
// Find types
for( WSMethodDef method : ws.getMethods() ){
if( method.getOutputCount() > 0 ){
if(!method.getOutputs().isEmpty()){
for( WSParameterDef param : method.getOutputs() ){
Class<?> paramClass = param.getParamClass();
Class<?> valueClass = getClass(paramClass);

View file

@ -18,6 +18,7 @@ public class RESTClientTest {
public interface OpenWeartherMap extends WSInterface {
@WSNamespace("")
int weather(@WSParamName("q") String city);
}