/* * jSoapServer is a Java library implementing a multi-threaded * soap server which can be easily integrated into java applications * to provide a SOAP Interface for external programmers. * * Copyright (C) 2006 Martin Thelian * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, please email thelian@users.sourceforge.net */ /* ======================================================================= * Revision Control Information * $Source: /cvsroot/jsoapserver/jSoapServer/test/java/source/org/jSoapServer/SoapServerTest.java,v $ * $Author: thelian $ * $Date: 2006/09/28 06:43:46 $ * $Revision: 1.6 $ * ======================================================================= */ package org.jSoapServer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import java.util.GregorianCalendar; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import junit.framework.TestCase; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.attachments.Attachments; import org.apache.axis.attachments.PlainTextDataSource; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.message.SOAPHeaderElement; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.jSoapServer.http.HttpHeaders; import org.jSoapServer.utils.FileUtils; public class SoapServerTest extends TestCase { public static final String hostIp = "localhost"; public static final int hostPort = 8090; private static SoapServer myServer = null; public static void main(String[] args) { junit.awtui.TestRunner.run(SoapServerTest.class); } protected void setUp() throws Exception { super.setUp(); // // if (myServer == null) { // try { // // creating a new soap server // SoapServer myServer = new SoapServer(); // // // deploing all needed services // myServer.deployRpcSoapService("org.jSoapServer.SoapService","test"); // // // configuring the server properties // String confFile = "conf" + File.separator + "jSoapServer.xml"; // if(myServer.initService(confFile)) { // // TODO: reading out application specific configuration and process it ... // // ApplicationConfiguration myConfig = myServer.getConfig().getApplicationConfiguration(); // // // starting the soap server // myServer.startServer(); // // // starting the quickserver admin server if configured // QSAdminServerConfig adminConfig = myServer.getConfig().getQSAdminServerConfig(); // if (adminConfig != null) myServer.startQSAdminServer(); // } // } catch(Exception e) { // System.err.println("Error in server : "+e); // e.printStackTrace(); // throw e; // } // } } protected void tearDown() throws Exception { super.tearDown(); // myServer.stopServer(); } private String getNamespace(String portname) { return "http://" + SoapServerTest.hostIp + ":" + SoapServerTest.hostPort + "/" + portname; } private URL getWsdlURL(String portname) throws MalformedURLException { String wsdl = "http://" + SoapServerTest.hostIp + ":" + SoapServerTest.hostPort + "/" + portname; return new URL(wsdl); } public Object invokeServiceWithWSDL(URL wsdlURL, String Namespace, String serviceName, String portName, String operationName, Object[] params) throws ServiceException, RemoteException { if (params == null) params = new Object[]{}; Service service = new Service(wsdlURL, new QName(Namespace,serviceName)); Call call = (Call)service.createCall(new QName(Namespace,portName), new QName(Namespace,operationName)); Object result = call.invoke(params); return result; } public Object invokeService(String endpoint, String operation, Object[] params, String[] usernamePwd, SOAPHeaderElement[] headers, String attachmentFormat, DataHandler[] attachments) throws ServiceException, MalformedURLException, RemoteException, SOAPException { if (params == null) params = new Object[]{}; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint)); call.setOperationName(new QName(endpoint, operation)); if (usernamePwd != null) { call.setUsername(usernamePwd[0]); call.setPassword(usernamePwd[1]); } if (headers != null) { for (int i=0; i < headers.length; i++) { call.addHeader(headers[i]); } } if (attachmentFormat != null && attachments != null) { call.setProperty(Call.ATTACHMENT_ENCAPSULATION_FORMAT, attachmentFormat); for (int i=0; i < attachments.length; i++) { call.addAttachmentPart(attachments[i]); } } Object result = call.invoke(params); return result; } public Object execService(String serviceName, String methodName, Object[] params, String[] usernamePwd, SOAPHeaderElement[] headers, String attachmentFormat, DataHandler[] attachments) throws ServiceException, MalformedURLException, RemoteException, SOAPException { assertNotNull(serviceName); assertNotNull(methodName); String endpoint = "http://" + SoapServerTest.hostIp + ":" + SoapServerTest.hostPort + "/" + serviceName; Object result = invokeService(endpoint, methodName, params, usernamePwd, headers, attachmentFormat, attachments); System.out.println("TEST " + serviceName + "." + methodName + (attachmentFormat !=null ? " with " + attachmentFormat + " attachment":"") + ": " + result); return result; } public void testDownloadServiceList() throws Exception { System.out.println("Downloading servicelist without content-encoding ..."); downloadServiceList(null); } public void testDownloadServiceListWithGzip() throws Exception { System.out.println("Downloading servicelist with gzip content-encoding ..."); downloadServiceList("x-gzip"); } public void testDownloadServiceListWithZip() throws Exception { System.out.println("Downloading servicelist with compress content-encoding ..."); downloadServiceList("x-compress"); } public void downloadServiceList(String contentEncoding) throws Exception { String serviceName = "test"; String endpoint = "http://" + SoapServerTest.hostIp + ":" + SoapServerTest.hostPort + "/" + serviceName; HttpClient client = new HttpClient(); GetMethod method = new GetMethod(endpoint); method.setQueryString(new NameValuePair[]{new NameValuePair("list","")}); if (contentEncoding != null) { method.setRequestHeader("Accept-Encoding",contentEncoding); } client.executeMethod(method); int httpStatus = method.getStatusCode(); if (contentEncoding != null) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); String usedEncoding = contentEncodingHeader.getValue(); if (usedEncoding.startsWith("x-") && !contentEncoding.startsWith("x-")) contentEncoding = "x-" + contentEncoding; else if (!usedEncoding.startsWith("x-") && contentEncoding.startsWith("x-")) usedEncoding = "x-" + usedEncoding; assertEquals(usedEncoding, contentEncoding); } assertEquals(httpStatus, 200); StringBuffer list = new StringBuffer(); if (contentEncoding != null) { Integer contentLength = Integer.valueOf(method.getResponseHeader("Content-Length").getValue()); InputStream compressedIn = null; if (contentEncoding.equals("x-gzip")) { compressedIn = new GZIPInputStream(method.getResponseBodyAsStream()); } else { compressedIn = new ZipInputStream(method.getResponseBodyAsStream()); ((ZipInputStream)compressedIn).getNextEntry(); } byte[] buffer = new byte[4096]; int c; while ((c = compressedIn.read(buffer)) > 0) { list.append(new String(buffer,0,c)); } } else { list.append(method.getResponseBodyAsString()); } method.releaseConnection(); } public void testDateChunk() throws Exception { transferAndContentEncodingTest(true, null); } public void testDateGzip() throws Exception { transferAndContentEncodingTest(false, "gzip"); } public void testDateCompress() throws Exception { transferAndContentEncodingTest(false, "compress"); } public void testDateDeflate() throws Exception { transferAndContentEncodingTest(false, "deflate"); } public void testDateChunkGzip() throws Exception { transferAndContentEncodingTest(true, "gzip"); } public void testDateChunkCompress() throws Exception { transferAndContentEncodingTest(true, "compress"); } public void testDateChunkDeflate() throws Exception { transferAndContentEncodingTest(true, "deflate"); } public void transferAndContentEncodingTest(boolean transferEncoding, String contentEncoding) throws Exception { String serviceName = "test"; String endpoint = "http://" + hostIp + ":" + hostPort + "/" + serviceName; String methodName = "testDate"; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(endpoint); if (transferEncoding) { method.setContentChunked(true); } StringBuffer fakeBody = new StringBuffer(); fakeBody.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"").append(Constants.URI_SOAP12_ENV).append("\">") .append("<SOAP-ENV:Body>") .append("<").append(methodName).append(">") // TODO: what about additional params .append("</").append(methodName).append(">") .append("</SOAP-ENV:Body>") .append("</SOAP-ENV:Envelope>"); RequestEntity entity = null; if (contentEncoding == null) { entity = new StringRequestEntity(fakeBody.toString(),"text/xml","utf-8"); } else { ByteArrayInputStream byteIn = new ByteArrayInputStream(fakeBody.toString().getBytes("UTF-8")); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); if (contentEncoding.equals(HttpHeaders.HTTP_CONTENT_ENCODING_GZIP)) { GZIPOutputStream zippedOut = new GZIPOutputStream(byteOut); FileUtils.copy(byteIn, zippedOut); zippedOut.close(); } else if (contentEncoding.equals(HttpHeaders.HTTP_CONTENT_ENCODING_COMPRESS)) { ZipOutputStream compressedOut = new ZipOutputStream(byteOut); compressedOut.putNextEntry(new ZipEntry("compressed output")); FileUtils.copy(byteIn, compressedOut); compressedOut.close(); } else if (contentEncoding.equals(HttpHeaders.HTTP_CONTENT_ENCODING_DEFLATE)) { DeflaterOutputStream deflateOut = new DeflaterOutputStream(byteOut, new Deflater(9)); FileUtils.copy(byteIn, deflateOut); deflateOut.close(); } byteIn = new ByteArrayInputStream(byteOut.toByteArray()); entity = new InputStreamRequestEntity(byteIn); method.addRequestHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding); } method.setRequestEntity(entity); client.executeMethod(method); int httpStatus = method.getStatusCode(); String httpStatusTxt = method.getStatusText(); assertEquals(httpStatus, 200); String response = method.getResponseBodyAsString(); method.releaseConnection(); System.out.println("TEST request with TransferEncoding=" + (transferEncoding?"ON ":"OFF") + " | ContentEncoding=" + (contentEncoding!=null?"ON (" + contentEncoding + ")":"OFF")); } public void testString() throws Exception { String serviceName = "test"; String methodName = "testString"; Object[] params = null; Object result = execService(serviceName, methodName, params, null, null, null, null); assertTrue(result instanceof String); } public void testBoolean() throws Exception { String serviceName = "test"; String methodName = "testBoolean"; Object[] params = null; Object result = execService(serviceName, methodName, params, null, null, null, null); assertTrue(result instanceof Boolean); } public void testDate() throws Exception { String serviceName = "test"; String methodName = "testDate"; Object[] params = null; Object result = execService(serviceName, methodName, params, null, null, null, null); assertTrue(result instanceof GregorianCalendar); } public void testIntAdd() throws Exception { String serviceName = "test"; String methodName = "testIntAdd"; Object[] params = new Object[]{new Integer(2),new Integer(3)}; Object result = execService(serviceName, methodName, params, null, null, null, null); assertTrue(result instanceof Integer); } public void testUserNamePwd() throws Exception { String serviceName = "test"; String methodName = "testUserNamePwd"; Object[] params = null; String username = "testUser"; String pwd = "testPwd"; Object result = execService(serviceName, methodName, params, new String[]{username,pwd}, null, null, null); assertTrue(result instanceof String); assertEquals(result, username + ":" + pwd); } public void testSoapHeader() throws Exception { String serviceName = "test"; String methodName = "testSoapHeader"; String username = "theUserName"; String pwd = "thePwd"; SOAPHeaderElement oHeaderElement = new SOAPHeaderElement("http://jSoapServer.org/securityTest", "securityHeader"); oHeaderElement.setPrefix("sec"); oHeaderElement.setMustUnderstand(false); SOAPElement oElement = oHeaderElement.addChildElement("username"); oElement.addTextNode(username); oElement = oHeaderElement.addChildElement("password"); oElement.addTextNode(pwd); Object result = execService(serviceName, methodName, null, null, new SOAPHeaderElement[]{oHeaderElement}, null, null); assertTrue(result instanceof String); assertEquals(result, username + ":" + pwd); } public void testException() throws Exception { String serviceName = "test"; String methodName = "testException"; try { execService(serviceName, methodName, null,null, null, null, null); assertTrue(false); } catch (AxisFault e) { System.out.println("TEST " + serviceName + "." + methodName + ": " + e.getMessage()); assertTrue(e.getMessage().endsWith("TestException Text")); } } public void testReceiveAttachmentMime() throws Exception { sendAttachment(Call.ATTACHMENT_ENCAPSULATION_FORMAT_MIME); } public void testReceiveAttachmentDime() throws Exception { sendAttachment(Call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME); } private void sendAttachment(String attachmentFormat)throws Exception { try { String serviceName = "test"; String methodName = "testReceiveAttachment"; String testData = "Testdata"; DataSource data = new PlainTextDataSource("Test.txt",testData); DataHandler attachmentFile = new DataHandler(data); Object result = execService(serviceName, methodName, null,null, null, attachmentFormat, new DataHandler[]{attachmentFile}); assertTrue(result instanceof String); assertEquals(result,testData); } catch (Exception e) { e.printStackTrace(); throw e; } } public void testSendAttachment() throws Exception { String serviceName = "test"; String methodName = "testSendAttachment"; String testMessageInput = "testdata"; try { // invoke the service Object result = execService(serviceName, methodName, new Object[]{new Integer(Attachments.SEND_TYPE_DIME),testMessageInput}, null, null, null, null); //Object result = invokeServiceWithWSDL(wsdlURL, namespace, serviceName, portName, methodName, new Object[]{new Integer(Attachments.SEND_TYPE_DIME),testMessageInput}); // the output must be of type DataHandler assertTrue(result instanceof DataHandler); // get the content of the datahandler Object content = ((DataHandler)result).getContent(); assertTrue(content instanceof String); // test if in and output are equal assertEquals(testMessageInput, (String)content); } catch (AxisFault e) { System.out.println("TEST " + serviceName + "." + methodName + ": " + e.getMessage()); assertTrue(e.getMessage().endsWith("TestException Text")); } } }
Friday, August 17, 2012
jSoapServer: sample server code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment