Some SOAP Client progress

This commit is contained in:
Ziver Koc 2015-12-19 13:32:34 +01:00
parent 973dfdec35
commit 3508b7fdaf
10 changed files with 120 additions and 44 deletions

BIN
Zutil.jar

Binary file not shown.

View file

@ -60,10 +60,26 @@ public class IOUtil {
* @param stream * @param stream
* @return a String with the content of the stream * @return a String with the content of the stream
*/ */
public static String getContentString(InputStream stream) throws IOException{ public static String getContentAsString(InputStream stream) throws IOException{
return getContentAsString(new InputStreamReader(stream));
}
/**
* Reads and returns all the content of a stream as a String.
* This function will close the input stream at the end.
*
* @param reader
* @return a String with the content of the stream
*/
public static String getContentAsString(Reader reader) throws IOException{
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
BufferedReader in = null;
if(reader instanceof BufferedReader)
reader = (BufferedReader) reader;
else
in = new BufferedReader(reader);
String line; String line;
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
while((line = in.readLine()) != null){ while((line = in.readLine()) != null){
str.append(line).append("\n"); str.append(line).append("\n");
} }

64
src/zutil/net/http/HttpClient.java Normal file → Executable file
View file

@ -39,27 +39,25 @@ import java.util.HashMap;
* *
* @author Ziver * @author Ziver
*/ */
public class HttpClient { public class HttpClient implements AutoCloseable{
public static enum HttpRequestType{ public static enum HttpRequestType{
GET, POST GET, POST
} }
// Request variables
private HttpURL url; private HttpURL url;
private HttpRequestType type; private HttpRequestType type;
private HashMap<String,String> headers; private HashMap<String,String> headers;
private HashMap<String,String> cookies; private HashMap<String,String> cookies;
private String data;
// Response variables
private HttpHeaderParser rspHeader;
private BufferedReader rspReader;
public static HttpClient POST(){
return new HttpClient( HttpRequestType.POST );
}
public static HttpClient GET(){ public HttpClient(HttpRequestType type){
return new HttpClient( HttpRequestType.GET );
}
private HttpClient(HttpRequestType type){
this.type = type; this.type = type;
headers = new HashMap<String,String>(); headers = new HashMap<String,String>();
cookies = new HashMap<String,String>(); cookies = new HashMap<String,String>();
@ -91,6 +89,18 @@ public class HttpClient {
headers.put(key, value); headers.put(key, value);
} }
/**
* Sets the content data that will be included in the request.
* NOTE: this will override the POST data parameter inclusion.
*/
public void setData( String data ){
this.data = data;
}
/**
* Will send a HTTP request to the target host.
* NOTE: any previous request connections will be closed
*/
public HttpHeaderParser send() throws IOException{ public HttpHeaderParser send() throws IOException{
Socket conn = new Socket( url.getHost(), url.getPort()); Socket conn = new Socket( url.getHost(), url.getPort());
@ -102,20 +112,40 @@ public class HttpClient {
request.setCookies( cookies ); request.setCookies( cookies );
if( type == HttpRequestType.POST ){ if( type == HttpRequestType.POST ){
String data = url.getParameterString(); String postData = null;
request.setHeader("Content-Length", data); if(data != null)
postData = data;
else
postData = url.getParameterString();
request.setHeader("Content-Length", ""+postData.length());
request.println(); request.println();
request.print( data ); request.print( postData );
} }
else else
request.println(); request.println();
request.close(); request.close();
// Response // Response
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); if(rspHeader != null || rspReader != null) // Close previous request
HttpHeaderParser response = new HttpHeaderParser( in ); this.close();
conn.close(); rspReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
rspHeader = new HttpHeaderParser( rspReader );
return response; return rspHeader;
}
public HttpHeaderParser getResponseHeader(){
return rspHeader;
}
public BufferedReader getResponseReader(){
return rspReader;
}
@Override
public void close() throws IOException {
if(rspReader != null)
rspReader.close();
rspReader = null;
rspHeader = null;
} }
} }

View file

@ -154,7 +154,6 @@ public class HttpServer extends ThreadedTCPNetworkServer{
out = new HttpPrintStream(socket.getOutputStream()); out = new HttpPrintStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.socket = socket; this.socket = socket;
//logger.finest("New Connection: " + socket.getInetAddress().getHostName());
} }
public void run(){ public void run(){
@ -167,7 +166,6 @@ public class HttpServer extends ThreadedTCPNetworkServer{
try { try {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
HttpHeaderParser parser = new HttpHeaderParser(in); HttpHeaderParser parser = new HttpHeaderParser(in);
//logger.finest(parser.toString());
request = parser.getURLAttributes(); request = parser.getURLAttributes();
cookie = parser.getCookies(); cookie = parser.getCookies();
@ -231,6 +229,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
out.setHeader( "Content-Type", "text/html" ); out.setHeader( "Content-Type", "text/html" );
out.setCookie( "session_id", ""+client_session.get("session_id") ); out.setCookie( "session_id", ""+client_session.get("session_id") );
logRequest(parser, client_session, cookie, request, time);
if( parser.getRequestURL() != null && !parser.getRequestURL().isEmpty() && pages.containsKey(parser.getRequestURL()) ){ if( parser.getRequestURL() != null && !parser.getRequestURL().isEmpty() && pages.containsKey(parser.getRequestURL()) ){
pages.get(parser.getRequestURL()).respond(out, parser, client_session, cookie, request); pages.get(parser.getRequestURL()).respond(out, parser, client_session, cookie, request);
logRequest(parser, client_session, cookie, request, time); logRequest(parser, client_session, cookie, request, time);

2
src/zutil/net/torrent/TorrentTracker.java Normal file → Executable file
View file

@ -43,7 +43,7 @@ public class TorrentTracker {
// TODO: incomplete // TODO: incomplete
public void update() throws IOException { public void update() throws IOException {
HttpClient request = HttpClient.GET(); HttpClient request = new HttpClient(HttpClient.HttpRequestType.GET);
request.setURL( trackerURL ); request.setURL( trackerURL );
HttpHeaderParser response = request.send(); HttpHeaderParser response = request.send();
} }

View file

@ -32,6 +32,7 @@ import zutil.net.ws.WebServiceDef;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -47,24 +48,28 @@ public class SOAPClientFactory {
* Generates a Client Object for the web service. * Generates a Client Object for the web service.
* *
* @param <T> is the class of the web service definition * @param <T> is the class of the web service definition
* @param url is the target service url
* @param intf is the class of the web service definition * @param intf is the class of the web service definition
* @return a client Object * @return a client Object
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T createClient(Class<T> intf){ public static <T> T createClient(URL url, Class<T> intf){
return createClient( intf, new WebServiceDef((Class<? extends WSInterface>)intf) ); return createClient(url, intf,
new WebServiceDef((Class<? extends WSInterface>)intf) );
} }
/** /**
* Generates a Client Object for the web service. * Generates a Client Object for the web service.
* *
* @param <T> is the class of the web service definition * @param <T> is the class of the web service definition
* @param url is the target service url
* @param intf is the class of the web service definition * @param intf is the class of the web service definition
* @param wsDef is the web service definition of the intf parameter * @param wsDef is the web service definition of the intf parameter
* @return a client Object * @return a client Object
*/ */
public static <T> T createClient(Class<T> intf, WebServiceDef wsDef){ public static <T> T createClient(URL url, Class<T> intf, WebServiceDef wsDef){
T obj = WSClientFactory.createClient(intf, new SOAPClientInvocationHandler()); T obj = WSClientFactory.createClient( intf,
new SOAPClientInvocationHandler(url, wsDef));
return obj; return obj;
} }

View file

@ -28,7 +28,7 @@ import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper; import org.dom4j.DocumentHelper;
import org.dom4j.Element; import org.dom4j.Element;
import org.xml.sax.SAXException; import zutil.io.IOUtil;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import zutil.net.http.HttpClient; import zutil.net.http.HttpClient;
import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpHeaderParser;
@ -39,6 +39,7 @@ import zutil.net.ws.WebServiceDef;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -53,22 +54,46 @@ public class SOAPClientInvocationHandler implements InvocationHandler {
private WebServiceDef wsDef; private WebServiceDef wsDef;
/** Web address of the web service */ /** Web address of the web service */
protected String url; protected URL url;
public SOAPClientInvocationHandler(URL url, WebServiceDef wsDef){
this.url = url;
this.wsDef = wsDef;
}
/** /**
* Makes a request to the target web service * Makes a request to the target web service
*/ */
@Override @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HttpClient request = HttpClient.POST(); // Generate XML
Document document = genSOAPRequest((WSInterface)proxy, method.getName(), args);
String reqXml = document.asXML();
// Send request
HttpClient request = new HttpClient(HttpClient.HttpRequestType.POST);
request.setURL(url);
request.setData(reqXml);
HttpHeaderParser response = request.send(); HttpHeaderParser response = request.send();
String rspXml = IOUtil.getContentAsString( request.getResponseReader());
return null; // DEBUG
if( logger.isLoggable(Level.FINEST) ){
System.out.println("********** Request");
System.out.println(reqXml);
System.out.println("********** Response");
System.out.println(rspXml);
}
return parseSOAPResponse(rspXml);
} }
private Document genSOAPRequest(WSInterface obj, String targetMethod, Object[] args){ private Document genSOAPRequest(WSInterface obj, String targetMethod, Object[] args){
logger.fine("Sending request for "+targetMethod);
Document document = DocumentHelper.createDocument(); Document document = DocumentHelper.createDocument();
Element envelope = document.addElement("soap:Envelope"); Element envelope = document.addElement("soap:Envelope");
WSMethodDef methodDef = wsDef.getMethod( targetMethod ); WSMethodDef methodDef = wsDef.getMethod( targetMethod );

View file

@ -139,18 +139,17 @@ public class SOAPHttpPage implements HttpPage{
Document document = genSOAPResponse( request.get(""), obj); Document document = genSOAPResponse( request.get(""), obj);
OutputFormat format = OutputFormat.createCompactFormat(); OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( out, format ); XMLWriter writer = new XMLWriter( out, format );
writer.write( document ); writer.write( document );
// DEBUG // DEBUG
if( logger.isLoggable(Level.FINEST) ){ if( logger.isLoggable(Level.FINEST) ){
OutputFormat format2 = OutputFormat.createPrettyPrint(); System.out.println("********** Request");
System.err.println("********** Request"); System.out.println(request);
System.err.println(request);
System.out.println("********** Response"); System.out.println("********** Response");
writer = new XMLWriter( System.out, format2 ); writer = new XMLWriter( System.out, format );
writer.write( document ); writer.write( document );
} }
} catch (Exception e) { } catch (Exception e) {

View file

@ -70,7 +70,7 @@ public class PluginManager<T> implements Iterable<PluginData>{
log.fine("Searching for plugins..."); log.fine("Searching for plugins...");
for(FileSearcher.FileSearchItem file : search){ for(FileSearcher.FileSearchItem file : search){
try { try {
DataNode node = JSONParser.read(IOUtil.getContentString(file.getInputStream())); DataNode node = JSONParser.read(IOUtil.getContentAsString(file.getInputStream()));
log.fine("Found plugin: "+file.getPath()); log.fine("Found plugin: "+file.getPath());
PluginData plugin = new PluginData(node); PluginData plugin = new PluginData(node);

View file

@ -28,15 +28,17 @@ import zutil.log.LogUtil;
import zutil.net.ws.WSInterface; import zutil.net.ws.WSInterface;
import zutil.net.ws.soap.SOAPClientFactory; import zutil.net.ws.soap.SOAPClientFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level; import java.util.logging.Level;
public class SOAPClientTest { public class SOAPClientTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException{ public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException {
LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalLevel(Level.ALL);
LogUtil.setFormatter("", new CompactLogFormatter()); LogUtil.setFormatter("", new CompactLogFormatter());
TestClient intf = SOAPClientFactory.createClient(TestClient.class); TestClient intf = SOAPClientFactory.createClient(new URL("http://localhost:3289"), TestClient.class);
intf.m(); intf.m();
intf.c(); intf.c();
} }