moving remoting.*, scheduling.* unit tests from .testsuite -> .context, .web

This commit is contained in:
Chris Beams
2008-12-17 06:13:28 +00:00
parent f5b1cae78c
commit 31f5961dce
14 changed files with 22 additions and 79 deletions

View File

@@ -1,224 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.caucho;
import com.caucho.burlap.client.BurlapProxyFactory;
import com.caucho.hessian.client.HessianProxyFactory;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.remoting.RemoteAccessException;
/**
* @author Juergen Hoeller
* @since 16.05.2003
*/
public class CauchoRemotingTests extends TestCase {
public void testHessianProxyFactoryBeanWithAccessError() throws Exception {
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
try {
factory.setServiceInterface(TestBean.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testHessianProxyFactoryBeanWithAuthenticationAndAccessError() throws Exception {
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
try {
factory.setServiceInterface(TestBean.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testHessianProxyFactoryBeanWithCustomProxyFactory() throws Exception {
TestHessianProxyFactory proxyFactory = new TestHessianProxyFactory();
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setProxyFactory(proxyFactory);
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
assertEquals(proxyFactory.user, "test");
assertEquals(proxyFactory.password, "bean");
assertTrue(proxyFactory.overloadEnabled);
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithAccessError() throws Exception {
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithAuthenticationAndAccessError() throws Exception {
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithCustomProxyFactory() throws Exception {
TestBurlapProxyFactory proxyFactory = new TestBurlapProxyFactory();
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setProxyFactory(proxyFactory);
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
assertEquals(proxyFactory.user, "test");
assertEquals(proxyFactory.password, "bean");
assertTrue(proxyFactory.overloadEnabled);
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
private static class TestHessianProxyFactory extends HessianProxyFactory {
private String user;
private String password;
private boolean overloadEnabled;
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setOverloadEnabled(boolean overloadEnabled) {
this.overloadEnabled = overloadEnabled;
}
}
private static class TestBurlapProxyFactory extends BurlapProxyFactory {
private String user;
private String password;
private boolean overloadEnabled;
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setOverloadEnabled(boolean overloadEnabled) {
this.overloadEnabled = overloadEnabled;
}
}
}

View File

@@ -1,469 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.httpinvoker;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.support.DefaultRemoteInvocationExecutor;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationFactory;
import org.springframework.remoting.support.RemoteInvocationResult;
/**
* @author Juergen Hoeller
* @since 09.08.2004
*/
public class HttpInvokerTests extends TestCase {
public void testHttpInvokerProxyFactoryBeanAndServiceExporter() throws Throwable {
doTestHttpInvokerProxyFactoryBeanAndServiceExporter(false);
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithExplicitClassLoader() throws Throwable {
doTestHttpInvokerProxyFactoryBeanAndServiceExporter(true);
}
private void doTestHttpInvokerProxyFactoryBeanAndServiceExporter(boolean explicitClassLoader) throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
if (explicitClassLoader) {
((BeanClassLoaderAware) pfb.getHttpInvokerRequestExecutor()).setBeanClassLoader(getClass().getClassLoader());
}
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
proxy.setStringArray(new String[] {"str1", "str2"});
assertTrue(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray()));
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithIOException() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new HttpInvokerRequestExecutor() {
public RemoteInvocationResult executeRequest(
HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws IOException {
throw new IOException("argh");
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithGzipCompression() throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() {
protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException {
if ("gzip".equals(request.getHeader("Compression"))) {
return new GZIPInputStream(is);
}
else {
return is;
}
}
protected OutputStream decorateOutputStream(
HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
if ("gzip".equals(request.getHeader("Compression"))) {
return new GZIPOutputStream(os);
}
else {
return os;
}
}
};
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
throws IOException, ClassNotFoundException {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Compression", "gzip");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
try {
exporter.handleRequest(request, response);
}
catch (ServletException ex) {
throw new IOException(ex.toString());
}
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
protected OutputStream decorateOutputStream(OutputStream os) throws IOException {
return new GZIPOutputStream(os);
}
protected InputStream decorateInputStream(InputStream is) throws IOException {
return new GZIPInputStream(is);
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithWrappedInvocations() throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() {
protected RemoteInvocation doReadRemoteInvocation(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
Object obj = ois.readObject();
if (!(obj instanceof TestRemoteInvocationWrapper)) {
throw new IOException("Deserialized object needs to be assignable to type [" +
TestRemoteInvocationWrapper.class.getName() + "]: " + obj);
}
return ((TestRemoteInvocationWrapper) obj).remoteInvocation;
}
protected void doWriteRemoteInvocationResult(RemoteInvocationResult result, ObjectOutputStream oos)
throws IOException {
oos.writeObject(new TestRemoteInvocationResultWrapper(result));
}
};
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
protected void doWriteRemoteInvocation(RemoteInvocation invocation, ObjectOutputStream oos) throws IOException {
oos.writeObject(new TestRemoteInvocationWrapper(invocation));
}
protected RemoteInvocationResult doReadRemoteInvocationResult(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
Object obj = ois.readObject();
if (!(obj instanceof TestRemoteInvocationResultWrapper)) {
throw new IOException("Deserialized object needs to be assignable to type ["
+ TestRemoteInvocationResultWrapper.class.getName() + "]: " + obj);
}
return ((TestRemoteInvocationResultWrapper) obj).remoteInvocationResult;
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithInvocationAttributes() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setRemoteInvocationExecutor(new DefaultRemoteInvocationExecutor() {
public Object invoke(RemoteInvocation invocation, Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
assertNotNull(invocation.getAttributes());
assertEquals(1, invocation.getAttributes().size());
assertEquals("myValue", invocation.getAttributes().get("myKey"));
assertEquals("myValue", invocation.getAttribute("myKey"));
return super.invoke(invocation, targetObject);
}
});
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setRemoteInvocationFactory(new RemoteInvocationFactory() {
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
RemoteInvocation invocation = new RemoteInvocation(methodInvocation);
invocation.addAttribute("myKey", "myValue");
try {
invocation.addAttribute("myKey", "myValue");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected: already defined
}
assertNotNull(invocation.getAttributes());
assertEquals(1, invocation.getAttributes().size());
assertEquals("myValue", invocation.getAttributes().get("myKey"));
assertEquals("myValue", invocation.getAttribute("myKey"));
return invocation;
}
});
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithCustomInvocationObject() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setRemoteInvocationExecutor(new DefaultRemoteInvocationExecutor() {
public Object invoke(RemoteInvocation invocation, Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
assertTrue(invocation instanceof TestRemoteInvocation);
assertNull(invocation.getAttributes());
assertNull(invocation.getAttribute("myKey"));
return super.invoke(invocation, targetObject);
}
});
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setRemoteInvocationFactory(new RemoteInvocationFactory() {
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
RemoteInvocation invocation = new TestRemoteInvocation(methodInvocation);
assertNull(invocation.getAttributes());
assertNull(invocation.getAttribute("myKey"));
return invocation;
}
});
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
}
public void testHttpInvokerWithSpecialLocalMethods() throws Exception {
String serviceUrl = "http://myurl";
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl(serviceUrl);
pfb.setHttpInvokerRequestExecutor(new HttpInvokerRequestExecutor() {
public RemoteInvocationResult executeRequest(
HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws IOException {
throw new IOException("argh");
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
// shouldn't go through to remote service
assertTrue(proxy.toString().indexOf("HTTP invoker") != -1);
assertTrue(proxy.toString().indexOf(serviceUrl) != -1);
assertEquals(proxy.hashCode(), proxy.hashCode());
assertTrue(proxy.equals(proxy));
// should go through
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
}
private static class TestRemoteInvocation extends RemoteInvocation {
public TestRemoteInvocation(MethodInvocation methodInvocation) {
super(methodInvocation);
}
}
private static class TestRemoteInvocationWrapper implements Serializable {
private final RemoteInvocation remoteInvocation;
public TestRemoteInvocationWrapper(RemoteInvocation remoteInvocation) {
this.remoteInvocation = remoteInvocation;
}
}
private static class TestRemoteInvocationResultWrapper implements Serializable {
private final RemoteInvocationResult remoteInvocationResult;
public TestRemoteInvocationResultWrapper(RemoteInvocationResult remoteInvocationResult) {
this.remoteInvocationResult = remoteInvocationResult;
}
}
}

View File

@@ -1,705 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.jaxrpc;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Stub;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.RemoteLookupFailureException;
import org.springframework.util.ObjectUtils;
/**
* @author Juergen Hoeller
* @since 18.12.2003
*/
public class JaxRpcSupportTests extends TestCase {
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndNamespace() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.afterPropertiesSet();
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndWsdl() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setServiceName("myService2");
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service2, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndWsdlAndProperties() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setServiceName("myService2");
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
Properties props = new Properties();
props.setProperty("myKey", "myValue");
factory.setJaxRpcServiceProperties(props);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithJaxRpcServiceInterface() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setJaxRpcServiceInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service2, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithJaxRpcServiceInterfaceAndWsdl() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
factory.setJaxRpcServiceInterface(IRemoteBean.class);
Properties props = new Properties();
props.setProperty("myKey", "myValue");
factory.setJaxRpcServiceProperties(props);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testJaxRpcPortProxyFactoryBean() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("user", stub._getProperty(Stub.USERNAME_PROPERTY));
assertEquals("pw", stub._getProperty(Stub.PASSWORD_PROPERTY));
assertEquals("ea", stub._getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY));
assertTrue(((Boolean) stub._getProperty(Stub.SESSION_MAINTAIN_PROPERTY)).booleanValue());
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithCustomProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
Properties customProps = new Properties();
customProps.setProperty("myProp", "myValue");
factory.setCustomProperties(customProps);
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("user", stub._getProperty(Stub.USERNAME_PROPERTY));
assertEquals("pw", stub._getProperty(Stub.PASSWORD_PROPERTY));
assertEquals("myValue", stub._getProperty("myProp"));
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithCustomPropertyMap() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
Map customProps = new HashMap();
customProps.put("myProp", new Integer(1));
factory.setCustomPropertyMap(customProps);
factory.addCustomProperty("myOtherProp", "myOtherValue");
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("ea", stub._getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY));
assertTrue(((Boolean) stub._getProperty(Stub.SESSION_MAINTAIN_PROPERTY)).booleanValue());
assertEquals(new Integer(1), stub._getProperty("myProp"));
assertEquals("myOtherValue", stub._getProperty("myOtherProp"));
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCalls() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertNull(factory.getPortStub());
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallWithPropertiesMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertNull(factory.getPortStub());
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
try {
factory.afterPropertiesSet();
fail("Should have thrown RemoteLookupFailureException");
}
catch (RemoteLookupFailureException ex) {
// expected
}
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndLazyLookupAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.setLookupServiceOnStartup(false);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteLookupFailureException ex) {
// expected
assertTrue(ex.getCause() instanceof ServiceException);
}
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteException() throws Exception {
ExceptionCallMockServiceFactory serviceFactory = new ExceptionCallMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(1, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
ExceptionCallMockServiceFactory.call2Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteExceptionAndRefresh() throws Exception {
ExceptionCallMockServiceFactory serviceFactory = new ExceptionCallMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.setRefreshServiceAfterConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(2, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
ExceptionCallMockServiceFactory.call2Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterface() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortInterface(IRemoteBean.class);
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
try {
factory.afterPropertiesSet();
fail("Should have thrown RemoteLookupFailureException");
}
catch (RemoteLookupFailureException ex) {
// expected
}
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndLazyLookupAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IRemoteBean.class);
factory.setLookupServiceOnStartup(false);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown Service");
}
catch (RemoteLookupFailureException ex) {
// expected
assertTrue(ex.getCause() instanceof ServiceException);
}
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteException() throws Exception {
MockServiceFactory serviceFactory = new MockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(1, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteExceptionAndRefresh() throws Exception {
ExceptionMockServiceFactory serviceFactory = new ExceptionMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.setRefreshServiceAfterConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(2, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
}
public static class MockServiceFactory extends ServiceFactory {
protected static MockControl service1Control;
protected static Service service1;
protected static MockControl service2Control;
protected static Service service2;
protected int serviceCount = 0;
public MockServiceFactory() throws Exception {
service1Control = MockControl.createControl(Service.class);
service1 = (Service) service1Control.getMock();
service2Control = MockControl.createControl(Service.class);
service2 = (Service) service2Control.getMock();
initMocks();
service1Control.replay();
}
protected void initMocks() throws Exception {
service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class);
service1Control.setReturnValue(new RemoteBean());
}
public Service createService(QName qName) throws ServiceException {
if (!"myNamespace".equals(qName.getNamespaceURI()) || !"myService1".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
serviceCount++;
return service1;
}
public Service createService(URL url, QName qName) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !"".equals(qName.getNamespaceURI()) ||
!"myService2".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
serviceCount++;
return service2;
}
public Service loadService(URL url, QName qName, Properties props) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !"".equals(qName.getNamespaceURI()) ||
!"myService2".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
if (props == null || !"myValue".equals(props.getProperty("myKey"))) {
throw new ServiceException("invalid properties");
}
serviceCount++;
return service1;
}
public Service loadService(Class ifc) throws ServiceException {
if (!IRemoteBean.class.equals(ifc)) {
throw new ServiceException("not supported");
}
serviceCount++;
return service2;
}
public Service loadService(URL url, Class ifc, Properties props) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !IRemoteBean.class.equals(ifc)) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
if (props == null || !"myValue".equals(props.getProperty("myKey"))) {
throw new ServiceException("invalid properties");
}
serviceCount++;
return service1;
}
}
public static class ExceptionMockServiceFactory extends MockServiceFactory {
public ExceptionMockServiceFactory() throws Exception {
super();
}
protected void initMocks() throws Exception {
super.initMocks();
service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class);
service1Control.setReturnValue(new RemoteBean());
}
}
public static class CallMockServiceFactory extends MockServiceFactory {
protected static MockControl call1Control;
protected static Call call1;
public CallMockServiceFactory() throws Exception {
super();
}
protected void initMocks() throws Exception {
initStandardCall(1);
}
protected void initStandardCall(int count) throws Exception {
call1Control = MockControl.createControl(Call.class);
call1 = (Call) call1Control.getMock();
service1.createCall(new QName("myNamespace", "myPort"), "setName");
service1Control.setReturnValue(call1, count);
call1.invoke(new Object[] {"myName"});
call1Control.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] objects, Object[] objects1) {
return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]);
}
public String toString(Object[] objects) {
return ObjectUtils.nullSafeToString(objects[0]);
}
});
call1Control.setReturnValue(null, count);
extendStandardCall();
call1Control.replay();
}
protected void extendStandardCall() {
}
}
public static class ExceptionCallMockServiceFactory extends CallMockServiceFactory {
protected static MockControl call2Control;
protected static Call call2;
public ExceptionCallMockServiceFactory() throws Exception {
}
protected void initMocks() throws Exception {
initExceptionCall();
initStandardCall(2);
}
protected void initExceptionCall() throws Exception {
call2Control = MockControl.createControl(Call.class);
call2 = (Call) call2Control.getMock();
service1.createCall(new QName("myNamespace", "myPort"), "setName");
service1Control.setReturnValue(call2);
call2.invoke(new Object[] {"exception"});
call2Control.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] objects, Object[] objects1) {
return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]);
}
public String toString(Object[] objects) {
return ObjectUtils.nullSafeToString(objects[0]);
}
});
call2Control.setThrowable(new RemoteException());
call2Control.replay();
}
}
public static class CallWithPropertiesMockServiceFactory extends CallMockServiceFactory {
public CallWithPropertiesMockServiceFactory() throws Exception {
}
protected void extendStandardCall() {
call1.setProperty(Call.USERNAME_PROPERTY, "user");
call1Control.setVoidCallable();
call1.setProperty(Call.PASSWORD_PROPERTY, "pw");
call1Control.setVoidCallable();
call1.setTargetEndpointAddress("ea");
call1Control.setVoidCallable();
call1.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
call1Control.setVoidCallable();
}
}
public static interface IBusinessBean {
public void setName(String name);
}
public static interface IRemoteBean extends Remote {
public void setName(String name) throws RemoteException;
}
public static class RemoteBean implements IRemoteBean, Stub {
private static String name;
private static Map properties;
public RemoteBean() {
properties = new HashMap();
}
public void setName(String nam) throws RemoteException {
if ("exception".equals(nam)) {
throw new RemoteException();
}
name = nam;
}
public void _setProperty(String key, Object o) {
properties.put(key, o);
}
public Object _getProperty(String key) {
return properties.get(key);
}
public Iterator _getPropertyNames() {
return properties.keySet().iterator();
}
}
}

View File

@@ -1,144 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.jaxws;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceRef;
import junit.framework.TestCase;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
/**
* @author Juergen Hoeller
* @since 2.5
*/
public class JaxWsSupportTests extends TestCase {
public void testJaxWsPortAccess() throws Exception {
GenericApplicationContext ac = new GenericApplicationContext();
GenericBeanDefinition serviceDef = new GenericBeanDefinition();
serviceDef.setBeanClass(OrderServiceImpl.class);
ac.registerBeanDefinition("service", serviceDef);
GenericBeanDefinition exporterDef = new GenericBeanDefinition();
exporterDef.setBeanClass(SimpleJaxWsServiceExporter.class);
exporterDef.getPropertyValues().addPropertyValue("baseAddress", "http://localhost:9999/");
ac.registerBeanDefinition("exporter", exporterDef);
GenericBeanDefinition clientDef = new GenericBeanDefinition();
clientDef.setBeanClass(JaxWsPortProxyFactoryBean.class);
clientDef.getPropertyValues().addPropertyValue("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
clientDef.getPropertyValues().addPropertyValue("namespaceUri", "http://jaxws.remoting.springframework.org/");
clientDef.getPropertyValues().addPropertyValue("username", "juergen");
clientDef.getPropertyValues().addPropertyValue("password", "hoeller");
clientDef.getPropertyValues().addPropertyValue("serviceName", "OrderService");
clientDef.getPropertyValues().addPropertyValue("serviceInterface", OrderService.class);
clientDef.getPropertyValues().addPropertyValue("lookupServiceOnStartup", Boolean.FALSE);
ac.registerBeanDefinition("client", clientDef);
GenericBeanDefinition serviceFactoryDef = new GenericBeanDefinition();
serviceFactoryDef.setBeanClass(LocalJaxWsServiceFactoryBean.class);
serviceFactoryDef.getPropertyValues().addPropertyValue("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
serviceFactoryDef.getPropertyValues().addPropertyValue("namespaceUri", "http://jaxws.remoting.springframework.org/");
serviceFactoryDef.getPropertyValues().addPropertyValue("serviceName", "OrderService");
ac.registerBeanDefinition("orderService", serviceFactoryDef);
ac.registerBeanDefinition("accessor", new RootBeanDefinition(ServiceAccessor.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
try {
ac.refresh();
OrderService orderService = (OrderService) ac.getBean("client", OrderService.class);
assertTrue(orderService instanceof BindingProvider);
((BindingProvider) orderService).getRequestContext();
String order = orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
ServiceAccessor serviceAccessor = (ServiceAccessor) ac.getBean("accessor", ServiceAccessor.class);
order = serviceAccessor.orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
serviceAccessor.orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
}
catch (BeanCreationException ex) {
if ("exporter".equals(ex.getBeanName()) && ex.getRootCause() instanceof ClassNotFoundException) {
// ignore - probably running on JDK < 1.6 without the JAX-WS impl present
}
else {
throw ex;
}
}
finally {
ac.close();
}
}
public static class ServiceAccessor {
@WebServiceRef
public OrderService orderService;
public OrderService myService;
@WebServiceRef(value=OrderServiceService.class, wsdlLocation = "http://localhost:9999/OrderService?wsdl")
public void setMyService(OrderService myService) {
this.myService = myService;
}
}
@WebServiceClient(targetNamespace = "http://jaxws.remoting.springframework.org/", name="OrderService")
public static class OrderServiceService extends Service {
public OrderServiceService() throws MalformedURLException {
super(new URL("http://localhost:9999/OrderService?wsdl"),
new QName("http://jaxws.remoting.springframework.org/", "OrderService"));
}
public OrderServiceService(URL wsdlDocumentLocation, QName serviceName) {
super(wsdlDocumentLocation, serviceName);
}
}
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.jaxws;
import javax.xml.ws.WebFault;
/**
* @author Juergen Hoeller
*/
@WebFault
public class OrderNotFoundException extends Exception {
private String faultInfo;
public OrderNotFoundException(String message) {
super(message);
}
public OrderNotFoundException(String message, String faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
public String getFaultInfo() {
return this.faultInfo;
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.jaxws;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
/**
* @author Juergen Hoeller
*/
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface OrderService {
String getOrder(int id) throws OrderNotFoundException;
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.jaxws;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import org.springframework.util.Assert;
/**
* @author Juergen Hoeller
*/
@WebService(serviceName="OrderService", portName="OrderService", endpointInterface = "org.springframework.remoting.jaxws.OrderService")
public class OrderServiceImpl implements OrderService {
@Resource
private WebServiceContext webServiceContext;
public String getOrder(int id) throws OrderNotFoundException {
Assert.notNull(this.webServiceContext, "WebServiceContext has not been injected");
if (id == 0) {
throw new OrderNotFoundException("Order 0 not found");
}
return "order " + id;
}
}

View File

@@ -1,452 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.rmi;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.rmi.ConnectException;
import java.rmi.ConnectIOException;
import java.rmi.MarshalException;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.StubNotFoundException;
import java.rmi.UnknownHostException;
import java.rmi.UnmarshalException;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.remoting.RemoteProxyFailureException;
import org.springframework.remoting.support.RemoteInvocation;
/**
* @author Juergen Hoeller
* @since 16.05.2003
*/
public class RmiSupportTests extends TestCase {
public void testRmiProxyFactoryBean() throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IRemoteBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals(RemoteBean.name, "myName");
assertEquals(1, factory.counter);
}
public void testRmiProxyFactoryBeanWithRemoteException() throws Exception {
doTestRmiProxyFactoryBeanWithException(RemoteException.class);
}
public void testRmiProxyFactoryBeanWithConnectException() throws Exception {
doTestRmiProxyFactoryBeanWithException(ConnectException.class);
}
public void testRmiProxyFactoryBeanWithConnectIOException() throws Exception {
doTestRmiProxyFactoryBeanWithException(ConnectIOException.class);
}
public void testRmiProxyFactoryBeanWithUnknownHostException() throws Exception {
doTestRmiProxyFactoryBeanWithException(UnknownHostException.class);
}
public void testRmiProxyFactoryBeanWithNoSuchObjectException() throws Exception {
doTestRmiProxyFactoryBeanWithException(NoSuchObjectException.class);
}
public void testRmiProxyFactoryBeanWithStubNotFoundException() throws Exception {
doTestRmiProxyFactoryBeanWithException(StubNotFoundException.class);
}
public void testRmiProxyFactoryBeanWithMarshalException() throws Exception {
doTestRmiProxyFactoryBeanWithException(MarshalException.class);
}
public void testRmiProxyFactoryBeanWithUnmarshalException() throws Exception {
doTestRmiProxyFactoryBeanWithException(UnmarshalException.class);
}
private void doTestRmiProxyFactoryBeanWithException(Class exceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IRemoteBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName(exceptionClass.getName());
fail("Should have thrown " + exceptionClass.getName());
}
catch (Exception ex) {
if (exceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertEquals(1, factory.counter);
}
public void testRmiProxyFactoryBeanWithConnectExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(ConnectException.class);
}
public void testRmiProxyFactoryBeanWithConnectIOExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(ConnectIOException.class);
}
public void testRmiProxyFactoryBeanWithUnknownHostExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(UnknownHostException.class);
}
public void testRmiProxyFactoryBeanWithNoSuchObjectExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(NoSuchObjectException.class);
}
public void testRmiProxyFactoryBeanWithStubNotFoundExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(StubNotFoundException.class);
}
private void doTestRmiProxyFactoryBeanWithExceptionAndRefresh(Class exceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IRemoteBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.setRefreshStubOnConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName(exceptionClass.getName());
fail("Should have thrown " + exceptionClass.getName());
}
catch (Exception ex) {
if (exceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertEquals(2, factory.counter);
}
public void testRmiProxyFactoryBeanWithBusinessInterface() throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IBusinessBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
proxy.setName("myName");
assertEquals(RemoteBean.name, "myName");
assertEquals(1, factory.counter);
}
public void testRmiProxyFactoryBeanWithWrongBusinessInterface() throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IWrongBusinessBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IWrongBusinessBean);
IWrongBusinessBean proxy = (IWrongBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setOtherName("name");
fail("Should have thrown RemoteProxyFailureException");
}
catch (RemoteProxyFailureException ex) {
assertTrue(ex.getCause() instanceof NoSuchMethodException);
assertTrue(ex.getMessage().indexOf("setOtherName") != -1);
assertTrue(ex.getMessage().indexOf("IWrongBusinessBean") != -1);
}
assertEquals(1, factory.counter);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndRemoteException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
RemoteException.class, RemoteAccessException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
ConnectException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
ConnectIOException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
UnknownHostException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
NoSuchObjectException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundException() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
StubNotFoundException.class, RemoteConnectFailureException.class);
}
private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
Class rmiExceptionClass, Class springExceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IBusinessBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setName(rmiExceptionClass.getName());
fail("Should have thrown " + rmiExceptionClass.getName());
}
catch (Exception ex) {
if (springExceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertEquals(1, factory.counter);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndRemoteExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
RemoteException.class, RemoteAccessException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
ConnectException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
ConnectIOException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
UnknownHostException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
NoSuchObjectException.class, RemoteConnectFailureException.class);
}
public void testRmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundExceptionAndRefresh() throws Exception {
doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
StubNotFoundException.class, RemoteConnectFailureException.class);
}
private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
Class rmiExceptionClass, Class springExceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IBusinessBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.setRefreshStubOnConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setName(rmiExceptionClass.getName());
fail("Should have thrown " + rmiExceptionClass.getName());
}
catch (Exception ex) {
if (springExceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
if (RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass)) {
assertEquals(2, factory.counter);
}
else {
assertEquals(1, factory.counter);
}
}
public void testRmiClientInterceptorRequiresUrl() throws Exception{
RmiClientInterceptor client = new RmiClientInterceptor();
client.setServiceInterface(IRemoteBean.class);
try {
client.afterPropertiesSet();
fail("url isn't set, expected IllegalArgumentException");
}
catch(IllegalArgumentException e){
// expected
}
}
public void testRemoteInvocation() throws NoSuchMethodException {
// let's see if the remote invocation object works
final RemoteBean rb = new RemoteBean();
final Method setNameMethod = rb.getClass().getDeclaredMethod("setName", new Class[] {String.class});
MethodInvocation mi = new MethodInvocation() {
public Method getMethod() {
return setNameMethod;
}
public Object[] getArguments() {
return new Object[] {"bla"};
}
public Object proceed() throws Throwable {
throw new UnsupportedOperationException();
}
public Object getThis() {
return rb;
}
public AccessibleObject getStaticPart() {
return setNameMethod;
}
};
RemoteInvocation inv = new RemoteInvocation(mi);
assertEquals("setName", inv.getMethodName());
assertEquals("bla", inv.getArguments()[0]);
assertEquals(String.class, inv.getParameterTypes()[0]);
// this is a bit BS, but we need to test it
inv = new RemoteInvocation();
inv.setArguments(new Object[] { "bla" });
assertEquals("bla", inv.getArguments()[0]);
inv.setMethodName("setName");
assertEquals("setName", inv.getMethodName());
inv.setParameterTypes(new Class[] {String.class});
assertEquals(String.class, inv.getParameterTypes()[0]);
inv = new RemoteInvocation("setName", new Class[] {String.class}, new Object[] {"bla"});
assertEquals("bla", inv.getArguments()[0]);
assertEquals("setName", inv.getMethodName());
assertEquals(String.class, inv.getParameterTypes()[0]);
}
public void testRmiInvokerWithSpecialLocalMethods() throws Exception {
String serviceUrl = "rmi://localhost:1090/test";
RmiProxyFactoryBean factory = new RmiProxyFactoryBean() {
protected Remote lookupStub() {
return new RmiInvocationHandler() {
public String getTargetInterfaceName() {
return null;
}
public Object invoke(RemoteInvocation invocation) throws RemoteException {
throw new RemoteException();
}
};
}
};
factory.setServiceInterface(IBusinessBean.class);
factory.setServiceUrl(serviceUrl);
factory.afterPropertiesSet();
IBusinessBean proxy = (IBusinessBean) factory.getObject();
// shouldn't go through to remote service
assertTrue(proxy.toString().indexOf("RMI invoker") != -1);
assertTrue(proxy.toString().indexOf(serviceUrl) != -1);
assertEquals(proxy.hashCode(), proxy.hashCode());
assertTrue(proxy.equals(proxy));
// should go through
try {
proxy.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
private static class CountingRmiProxyFactoryBean extends RmiProxyFactoryBean {
private int counter = 0;
protected Remote lookupStub() {
counter++;
return new RemoteBean();
}
}
public static interface IBusinessBean {
public void setName(String name);
}
public static interface IWrongBusinessBean {
public void setOtherName(String name);
}
public static interface IRemoteBean extends Remote {
public void setName(String name) throws RemoteException;
}
public static class RemoteBean implements IRemoteBean {
private static String name;
public void setName(String nam) throws RemoteException {
if (nam != null && nam.endsWith("Exception")) {
RemoteException rex = null;
try {
Class exClass = Class.forName(nam);
Constructor ctor = exClass.getConstructor(new Class[] {String.class});
rex = (RemoteException) ctor.newInstance(new Object[] {"myMessage"});
}
catch (Exception ex) {
throw new RemoteException("Illegal exception class name: " + nam, ex);
}
throw rex;
}
name = nam;
}
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.remoting.support;
import junit.framework.TestCase;
/**
* @author Rick Evans
*/
public class RemoteInvocationUtilsTests extends TestCase {
public void testFillInClientStackTraceIfPossibleSunnyDay() throws Exception {
try {
throw new IllegalStateException("Mmm");
}
catch (Exception ex) {
int originalStackTraceLngth = ex.getStackTrace().length;
RemoteInvocationUtils.fillInClientStackTraceIfPossible(ex);
assertTrue("Stack trace not being filled in",
ex.getStackTrace().length > originalStackTraceLngth);
}
}
public void testFillInClientStackTraceIfPossibleWithNullThrowable() throws Exception {
// just want to ensure that it doesn't bomb
RemoteInvocationUtils.fillInClientStackTraceIfPossible(null);
}
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling;
/**
* @author Juergen Hoeller
* @since 09.10.2004
*/
public class TestMethodInvokingTask {
public int counter = 0;
private Object lock = new Object();
public void doSomething() {
this.counter++;
}
public void doWait() {
this.counter++;
// wait until stop is called
synchronized (this.lock) {
try {
this.lock.wait();
}
catch (InterruptedException e) {
// fall through
}
}
}
public void stop() {
synchronized(this.lock) {
this.lock.notify();
}
}
}

View File

@@ -1,281 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.backportconcurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import junit.framework.AssertionFailedError;
import org.easymock.MockControl;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.task.NoOpRunnable;
import edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler;
import edu.emory.mathcs.backport.java.util.concurrent.ScheduledExecutorService;
import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ScheduledExecutorFactoryBeanTests {
@Test
public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception {
try {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setPoolSize(-1);
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.afterPropertiesSet();
fail("Pool size less than zero");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdownNow();
mockScheduledExecutorService.setReturnValue(null);
mockScheduledExecutorService.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
return executor;
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
}
@Test
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdown();
mockScheduledExecutorService.setVoidCallable();
mockScheduledExecutorService.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
return executor;
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setWaitForTasksToCompleteOnShutdown(true);
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
}
@Test
public void testOneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new ScheduledExecutorTask(runnable)
});
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
factory.destroy();
mockRunnable.verify();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setFixedRate(true);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{task});
factory.afterPropertiesSet();
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setFixedRate(true);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{task});
factory.setContinueScheduledExecutionAfterException(true);
factory.afterPropertiesSet();
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setDelay(3000); // nice long wait...
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[] {task});
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setDelay(3000); // nice long wait...
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[] {task});
factory.setContinueScheduledExecutionAfterException(true);
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
}
@Test
public void testSettingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
assertNotNull("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in.");
return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler);
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setThreadFactory(null); // the null must not propagate
factory.afterPropertiesSet();
factory.destroy();
}
@Test
public void testSettingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
assertNotNull("Bah; the setRejectedExecutionHandler(..) method must use a default RejectedExecutionHandler if a null arg is passed in.");
return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler);
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setRejectedExecutionHandler(null); // the null must not propagate
factory.afterPropertiesSet();
factory.destroy();
}
@Test
public void testObjectTypeReportsCorrectType() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertEquals(ScheduledExecutorService.class, factory.getObjectType());
}
private static void pauseToLetTaskStart(int seconds) {
try {
Thread.sleep(seconds * 1000);
}
catch (InterruptedException ignored) {
}
}
private static class NoOpScheduledExecutorTask extends ScheduledExecutorTask {
public NoOpScheduledExecutorTask() {
super(new NoOpRunnable());
}
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.concurrent;
import junit.framework.TestCase;
import org.springframework.core.task.NoOpRunnable;
/**
* @author Rick Evans
*/
public class ConcurrentTaskExecutorTests extends TestCase {
public void testZeroArgCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
// must not throw a NullPointerException
executor.execute(new NoOpRunnable());
}
public void testPassingNullExecutorToCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(null);
// must not throw a NullPointerException
executor.execute(new NoOpRunnable());
}
public void testPassingNullExecutorToSetterResultsInDefaultTaskExecutorBeingUsed() throws Exception {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
executor.setConcurrentExecutor(null);
// must not throw a NullPointerException
executor.execute(new NoOpRunnable());
}
}

View File

@@ -1,282 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import junit.framework.AssertionFailedError;
import org.easymock.MockControl;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.task.NoOpRunnable;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ScheduledExecutorFactoryBeanTests {
@Test
public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception {
try {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setPoolSize(-1);
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.afterPropertiesSet();
fail("Pool size less than zero");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdownNow();
mockScheduledExecutorService.setReturnValue(null);
mockScheduledExecutorService.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
return executor;
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
}
@Test
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdown();
mockScheduledExecutorService.setVoidCallable();
mockScheduledExecutorService.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
return executor;
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setWaitForTasksToCompleteOnShutdown(true);
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
}
@Test
public void testOneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new ScheduledExecutorTask(runnable)
});
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
factory.destroy();
mockRunnable.verify();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setFixedRate(true);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{task});
factory.afterPropertiesSet();
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setFixedRate(true);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{task});
factory.setContinueScheduledExecutionAfterException(true);
factory.afterPropertiesSet();
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setDelay(3000); // nice long wait...
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[] {task});
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
task.setDelay(3000); // nice long wait...
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[] {task});
factory.setContinueScheduledExecutionAfterException(true);
factory.afterPropertiesSet();
pauseToLetTaskStart(1);
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
}
@Test
public void testSettingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
assertNotNull("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in.");
return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler);
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setThreadFactory(null); // the null must not propagate
factory.afterPropertiesSet();
factory.destroy();
}
@Test
public void testSettingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
assertNotNull("Bah; the setRejectedExecutionHandler(..) method must use a default RejectedExecutionHandler if a null arg is passed in.");
return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler);
}
};
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.setRejectedExecutionHandler(null); // the null must not propagate
factory.afterPropertiesSet();
factory.destroy();
}
@Test
public void testObjectTypeReportsCorrectType() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertEquals(ScheduledExecutorService.class, factory.getObjectType());
}
private static void pauseToLetTaskStart(int seconds) {
try {
Thread.sleep(seconds * 1000);
}
catch (InterruptedException ignored) {
}
}
private static class NoOpScheduledExecutorTask extends ScheduledExecutorTask {
public NoOpScheduledExecutorTask() {
super(new NoOpRunnable());
}
}
}

View File

@@ -1,189 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.timer;
import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
import java.util.Timer;
/**
* Unit tests for the {@link TimerTaskExecutor} class.
*
* @author Rick Evans
*/
public final class TimerTaskExecutorTests extends TestCase {
public void testExecuteChokesWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteChokesWithNullTask() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(null);
}
}.runTest();
}
public void testExecuteChokesWithNegativeDelay() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.setDelay(-10);
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteReallyDoesScheduleTheSuppliedTask() throws Exception {
final Object monitor = new Object();
RunAwareRunnable task = new RunAwareRunnable(monitor);
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(task);
synchronized (monitor) {
monitor.wait(5000);
}
assertTrue("Supplied task (a Runnable) is not being invoked.", task.isRunWasCalled());
}
public void testCtorWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new TimerTaskExecutor(null);
}
}.runTest();
}
public void testCreateTimerMethodIsCalledIfNoTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.afterPropertiesSet();
assertTrue("If no Timer is set explicitly, then the protected createTimer() " +
"method must be called to create the Timer (it obviously isn't being called).",
executor.isCreateTimerWasCalled());
}
public void testCreateTimerMethodIsNotCalledIfTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.setTimer(new Timer());
executor.afterPropertiesSet();
assertFalse("If a Timer is set explicitly, then the protected createTimer() " +
"method must not be called to create the Timer (it obviously is being called, in error).",
executor.isCreateTimerWasCalled());
}
public void testThatTheDestroyCallbackCancelsTheTimerIfNoTimerIsExplicitlySupplied() throws Exception {
final CancelAwareTimer timer = new CancelAwareTimer();
TimerTaskExecutor executor = new TimerTaskExecutor() {
protected Timer createTimer() {
return timer;
}
};
executor.afterPropertiesSet();
executor.destroy();
assertTrue("When the Timer used is created by the TimerTaskExecutor because " +
"no Timer was set explicitly, then the destroy() callback must cancel() said Timer (it obviously isn't doing this).",
timer.isCancelWasCalled());
}
public void testThatTheDestroyCallbackDoesNotCancelTheTimerIfTheTimerWasSuppliedExplictly() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
CancelAwareTimer timer = new CancelAwareTimer();
executor.setTimer(timer);
executor.afterPropertiesSet();
executor.destroy();
assertFalse("When the Timer used is not created by the TimerTaskExecutor because " +
"it Timer was set explicitly, then the destroy() callback must NOT cancel() said Timer (it obviously is, in error).",
timer.isCancelWasCalled());
}
private final static class CreationAwareTimerTaskExecutor extends TimerTaskExecutor {
private boolean createTimerWasCalled = false;
public boolean isCreateTimerWasCalled() {
return this.createTimerWasCalled;
}
protected Timer createTimer() {
this.createTimerWasCalled = true;
return super.createTimer();
}
}
private static class CancelAwareTimer extends Timer {
private boolean cancelWasCalled;
public boolean isCancelWasCalled() {
return this.cancelWasCalled;
}
public void cancel() {
this.cancelWasCalled = true;
super.cancel();
}
}
private static class RunAwareRunnable implements Runnable {
private boolean runWasCalled;
private final Object monitor;
public RunAwareRunnable(Object monitor) {
this.monitor = monitor;
}
public boolean isRunWasCalled() {
return this.runWasCalled;
}
public void run() {
this.runWasCalled = true;
synchronized (monitor) {
monitor.notifyAll();
}
}
}
private static final class NoOpRunnable implements Runnable {
public void run() {
// explicit no-op
}
}
}