Rename modules {org.springframework.*=>spring-*}

This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.

Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example

    $ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history up until the renaming event, where

    $ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history for all changes to the file, before and after the
renaming.

See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
Chris Beams
2012-01-20 22:51:02 +01:00
parent b6cb514d38
commit 02a4473c62
5671 changed files with 20 additions and 32 deletions

View File

@@ -0,0 +1,35 @@
/*
* 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.beans;
import org.springframework.core.enums.ShortCodedLabeledEnum;
/**
* @author Rob Harrop
*/
public class Colour extends ShortCodedLabeledEnum {
public static final Colour RED = new Colour(0, "RED");
public static final Colour BLUE = new Colour(1, "BLUE");
public static final Colour GREEN = new Colour(2, "GREEN");
public static final Colour PURPLE = new Colour(3, "PURPLE");
private Colour(int code, String label) {
super(code, label);
}
}

View File

@@ -0,0 +1,23 @@
/*
* 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.beans;
public interface INestedTestBean {
public String getCompany();
}

View File

@@ -0,0 +1,24 @@
/*
* 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.beans;
public interface IOther {
void absquatulate();
}

View File

@@ -0,0 +1,71 @@
/*
* 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.beans;
import java.io.IOException;
/**
* Interface used for {@link org.springframework.beans.TestBean}.
*
* <p>Two methods are the same as on Person, but if this
* extends person it breaks quite a few tests..
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
String getName();
void setName(String name);
ITestBean getSpouse();
void setSpouse(ITestBean spouse);
ITestBean[] getSpouses();
String[] getStringArray();
void setStringArray(String[] stringArray);
/**
* Throws a given (non-null) exception.
*/
void exceptional(Throwable t) throws Throwable;
Object returnsThis();
INestedTestBean getDoctor();
INestedTestBean getLawyer();
IndexedTestBean getNestedIndexedBean();
/**
* Increment the age by one.
* @return the previous age
*/
int haveBirthday();
void unreliableFileOperation() throws IOException;
}

View File

@@ -0,0 +1,145 @@
/*
* 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.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Juergen Hoeller
* @since 11.11.2003
*/
public class IndexedTestBean {
private TestBean[] array;
private Collection collection;
private List list;
private Set set;
private SortedSet sortedSet;
private Map map;
private SortedMap sortedMap;
public IndexedTestBean() {
this(true);
}
public IndexedTestBean(boolean populate) {
if (populate) {
populate();
}
}
public void populate() {
TestBean tb0 = new TestBean("name0", 0);
TestBean tb1 = new TestBean("name1", 0);
TestBean tb2 = new TestBean("name2", 0);
TestBean tb3 = new TestBean("name3", 0);
TestBean tb4 = new TestBean("name4", 0);
TestBean tb5 = new TestBean("name5", 0);
TestBean tb6 = new TestBean("name6", 0);
TestBean tb7 = new TestBean("name7", 0);
TestBean tbX = new TestBean("nameX", 0);
TestBean tbY = new TestBean("nameY", 0);
this.array = new TestBean[] {tb0, tb1};
this.list = new ArrayList();
this.list.add(tb2);
this.list.add(tb3);
this.set = new TreeSet();
this.set.add(tb6);
this.set.add(tb7);
this.map = new HashMap();
this.map.put("key1", tb4);
this.map.put("key2", tb5);
this.map.put("key.3", tb5);
List list = new ArrayList();
list.add(tbX);
list.add(tbY);
this.map.put("key4", list);
}
public TestBean[] getArray() {
return array;
}
public void setArray(TestBean[] array) {
this.array = array;
}
public Collection getCollection() {
return collection;
}
public void setCollection(Collection collection) {
this.collection = collection;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
public SortedSet getSortedSet() {
return sortedSet;
}
public void setSortedSet(SortedSet sortedSet) {
this.sortedSet = sortedSet;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public SortedMap getSortedMap() {
return sortedMap;
}
public void setSortedMap(SortedMap sortedMap) {
this.sortedMap = sortedMap;
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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.beans;
/**
* Simple nested test bean used for testing bean factories, AOP framework etc.
*
* @author Trevor D. Cook
* @since 30.09.2003
*/
public class NestedTestBean implements INestedTestBean {
private String company = "";
public NestedTestBean() {
}
public NestedTestBean(String company) {
setCompany(company);
}
public void setCompany(String company) {
this.company = (company != null ? company : "");
}
public String getCompany() {
return company;
}
public boolean equals(Object obj) {
if (!(obj instanceof NestedTestBean)) {
return false;
}
NestedTestBean ntb = (NestedTestBean) obj;
return this.company.equals(ntb.company);
}
public int hashCode() {
return this.company.hashCode();
}
public String toString() {
return "NestedTestBean: " + this.company;
}
}

View File

@@ -0,0 +1,437 @@
/*
* 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.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.util.ObjectUtils;
/**
* Simple test bean used for testing bean factories, the AOP framework etc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 15 April 2001
*/
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
private String beanName;
private String country;
private BeanFactory beanFactory;
private boolean postProcessed;
private String name;
private String sex;
private int age;
private boolean jedi;
private ITestBean[] spouses;
private String touchy;
private String[] stringArray;
private Integer[] someIntegerArray;
private Date date = new Date();
private Float myFloat = new Float(0.0);
private Collection friends = new LinkedList();
private Set someSet = new HashSet();
private Map someMap = new HashMap();
private List someList = new ArrayList();
private Properties someProperties = new Properties();
private INestedTestBean doctor = new NestedTestBean();
private INestedTestBean lawyer = new NestedTestBean();
private IndexedTestBean nestedIndexedBean;
private boolean destroyed;
private Number someNumber;
private Colour favouriteColour;
private Boolean someBoolean;
private List otherColours;
private List pets;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean(ITestBean spouse, Properties someProperties) {
this.spouses = new ITestBean[] {spouse};
this.someProperties = someProperties;
}
public TestBean(List someList) {
this.someList = someList;
}
public TestBean(Set someSet) {
this.someSet = someSet;
}
public TestBean(Map someMap) {
this.someMap = someMap;
}
public TestBean(Properties someProperties) {
this.someProperties = someProperties;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
if (this.name == null) {
this.name = sex;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
public ITestBean getSpouse() {
return (spouses != null ? spouses[0] : null);
}
public void setSpouse(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public ITestBean[] getSpouses() {
return spouses;
}
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
throw new Exception("Can't contain a .");
}
if (touchy.indexOf(',') != -1) {
throw new NumberFormatException("Number format exception: contains a ,");
}
this.touchy = touchy;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection getFriends() {
return friends;
}
public void setFriends(Collection friends) {
this.friends = friends;
}
public Set getSomeSet() {
return someSet;
}
public void setSomeSet(Set someSet) {
this.someSet = someSet;
}
public Map getSomeMap() {
return someMap;
}
public void setSomeMap(Map someMap) {
this.someMap = someMap;
}
public List getSomeList() {
return someList;
}
public void setSomeList(List someList) {
this.someList = someList;
}
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
public INestedTestBean getDoctor() {
return doctor;
}
public void setDoctor(INestedTestBean doctor) {
this.doctor = doctor;
}
public INestedTestBean getLawyer() {
return lawyer;
}
public void setLawyer(INestedTestBean lawyer) {
this.lawyer = lawyer;
}
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List getOtherColours() {
return otherColours;
}
public void setOtherColours(List otherColours) {
this.otherColours = otherColours;
}
public List getPets() {
return pets;
}
public void setPets(List pets) {
this.pets = pets;
}
/**
* @see ITestBean#exceptional(Throwable)
*/
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see ITestBean#returnsThis()
*/
public Object returnsThis() {
return this;
}
/**
* @see IOther#absquatulate()
*/
public void absquatulate() {
}
public int haveBirthday() {
return age++;
}
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() {
return destroyed;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof TestBean)) {
return false;
}
TestBean tb2 = (TestBean) other;
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
}
public int hashCode() {
return this.age;
}
public int compareTo(Object other) {
if (this.name != null && other instanceof TestBean) {
return this.name.compareTo(((TestBean) other).getName());
}
else {
return 1;
}
}
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,27 @@
/*
* 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.core.task;
/**
* @author Juergen Hoeller
*/
public class StubTaskExecutor implements TaskExecutor {
public void execute(Runnable task) {
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.jca;
import javax.resource.ResourceException;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.InvalidPropertyException;
import javax.resource.spi.ResourceAdapter;
/**
* @author Juergen Hoeller
*/
public class StubActivationSpec implements ActivationSpec {
public void validate() throws InvalidPropertyException {
}
public ResourceAdapter getResourceAdapter() {
return null;
}
public void setResourceAdapter(ResourceAdapter resourceAdapter) throws ResourceException {
}
}

View File

@@ -0,0 +1,48 @@
/*
* 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.jca;
import javax.resource.ResourceException;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterInternalException;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.transaction.xa.XAResource;
/**
* @author Juergen Hoeller
*/
public class StubResourceAdapter implements ResourceAdapter {
public void start(BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
}
public void stop() {
}
public void endpointActivation(MessageEndpointFactory messageEndpointFactory, ActivationSpec activationSpec) throws ResourceException {
}
public void endpointDeactivation(MessageEndpointFactory messageEndpointFactory, ActivationSpec activationSpec) {
}
public XAResource[] getXAResources(ActivationSpec[] activationSpecs) throws ResourceException {
return null;
}
}

View File

@@ -0,0 +1,38 @@
/*
* 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.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
/**
* A stub implementation of the JMS ConnectionFactory for testing.
*
* @author Mark Fisher
*/
public class StubConnectionFactory implements ConnectionFactory {
public Connection createConnection() throws JMSException {
return null;
}
public Connection createConnection(String username, String password) throws JMSException {
return null;
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.jms;
import javax.jms.Queue;
/**
* Stub implementation of the {@link javax.jms.Queue} interface.
*
* @author Rick Evans
*/
public class StubQueue implements Queue {
public static final String DEFAULT_QUEUE_NAME = "banjo";
private String queueName = DEFAULT_QUEUE_NAME;
public StubQueue() {
}
public StubQueue(String queueName) {
this.queueName = queueName;
}
public String getQueueName() {
return this.queueName;
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.jms;
import javax.jms.Topic;
/**
* Stub implementation of the {@link Topic} interface.
*
* @author Rick Evans
*/
public class StubTopic implements Topic {
public static final String DEFAULT_TOPIC_NAME = "banjo";
private String topicName = DEFAULT_TOPIC_NAME;
public StubTopic() {
}
public StubTopic(String topicName) {
this.topicName = topicName;
}
public String getTopicName() {
return this.topicName;
}
}

View File

@@ -0,0 +1,283 @@
/*
* Copyright 2002-2010 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.jms.config;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.ComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.parsing.EmptyReaderEventListener;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.Phased;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jca.endpoint.GenericMessageEndpointManager;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager;
import org.springframework.util.ErrorHandler;
/**
* @author Mark Fisher
* @author Juergen Hoeller
* @author Christian Dupuis
*/
public class JmsNamespaceHandlerTests extends TestCase {
private static final String DEFAULT_CONNECTION_FACTORY = "connectionFactory";
private static final String EXPLICIT_CONNECTION_FACTORY = "testConnectionFactory";
private ToolingTestApplicationContext context;
protected void setUp() throws Exception {
this.context = new ToolingTestApplicationContext("jmsNamespaceHandlerTests.xml", getClass());
}
protected void tearDown() throws Exception {
this.context.close();
}
public void testBeansCreated() {
Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class);
assertEquals("Context should contain 3 JMS listener containers", 3, containers.size());
containers = context.getBeansOfType(GenericMessageEndpointManager.class);
assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size());
}
public void testContainerConfiguration() throws Exception {
Map<String, DefaultMessageListenerContainer> containers = context.getBeansOfType(DefaultMessageListenerContainer.class);
ConnectionFactory defaultConnectionFactory = context.getBean(DEFAULT_CONNECTION_FACTORY, ConnectionFactory.class);
ConnectionFactory explicitConnectionFactory = context.getBean(EXPLICIT_CONNECTION_FACTORY, ConnectionFactory.class);
int defaultConnectionFactoryCount = 0;
int explicitConnectionFactoryCount = 0;
for (DefaultMessageListenerContainer container : containers.values()) {
if (container.getConnectionFactory().equals(defaultConnectionFactory)) {
defaultConnectionFactoryCount++;
assertEquals(2, container.getConcurrentConsumers());
assertEquals(3, container.getMaxConcurrentConsumers());
}
else if (container.getConnectionFactory().equals(explicitConnectionFactory)) {
explicitConnectionFactoryCount++;
assertEquals(1, container.getConcurrentConsumers());
assertEquals(2, container.getMaxConcurrentConsumers());
}
}
assertEquals("1 container should have the default connectionFactory", 1, defaultConnectionFactoryCount);
assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount);
}
public void testListeners() throws Exception {
TestBean testBean1 = context.getBean("testBean1", TestBean.class);
TestBean testBean2 = context.getBean("testBean2", TestBean.class);
TestMessageListener testBean3 = context.getBean("testBean3", TestMessageListener.class);
assertNull(testBean1.getName());
assertNull(testBean2.getName());
assertNull(testBean3.message);
MockControl control1 = MockControl.createControl(TextMessage.class);
TextMessage message1 = (TextMessage) control1.getMock();
control1.expectAndReturn(message1.getText(), "Test1");
control1.replay();
MessageListener listener1 = getListener("listener1");
listener1.onMessage(message1);
assertEquals("Test1", testBean1.getName());
control1.verify();
MockControl control2 = MockControl.createControl(TextMessage.class);
TextMessage message2 = (TextMessage) control2.getMock();
control2.expectAndReturn(message2.getText(), "Test2");
control2.replay();
MessageListener listener2 = getListener("listener2");
listener2.onMessage(message2);
assertEquals("Test2", testBean2.getName());
control2.verify();
MockControl control3 = MockControl.createControl(TextMessage.class);
TextMessage message3 = (TextMessage) control3.getMock();
control3.replay();
MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0");
listener3.onMessage(message3);
assertSame(message3, testBean3.message);
control3.verify();
}
public void testErrorHandlers() {
ErrorHandler expected = this.context.getBean("testErrorHandler", ErrorHandler.class);
ErrorHandler errorHandler1 = getErrorHandler("listener1");
ErrorHandler errorHandler2 = getErrorHandler("listener2");
ErrorHandler defaultErrorHandler = getErrorHandler(DefaultMessageListenerContainer.class.getName() + "#0");
assertSame(expected, errorHandler1);
assertSame(expected, errorHandler2);
assertNull(defaultErrorHandler);
}
public void testPhases() {
int phase1 = getPhase("listener1");
int phase2 = getPhase("listener2");
int phase3 = getPhase("listener3");
int phase4 = getPhase("listener4");
int defaultPhase = getPhase(DefaultMessageListenerContainer.class.getName() + "#0");
assertEquals(99, phase1);
assertEquals(99, phase2);
assertEquals(77, phase3);
assertEquals(77, phase4);
assertEquals(Integer.MAX_VALUE, defaultPhase);
}
private MessageListener getListener(String containerBeanName) {
DefaultMessageListenerContainer container = this.context.getBean(containerBeanName, DefaultMessageListenerContainer.class);
return (MessageListener) container.getMessageListener();
}
private ErrorHandler getErrorHandler(String containerBeanName) {
DefaultMessageListenerContainer container = this.context.getBean(containerBeanName, DefaultMessageListenerContainer.class);
return (ErrorHandler) new DirectFieldAccessor(container).getPropertyValue("errorHandler");
}
public int getPhase(String containerBeanName) {
Object container = this.context.getBean(containerBeanName);
if (!(container instanceof Phased)) {
throw new IllegalStateException("Container '" + containerBeanName + "' does not implement Phased.");
}
return ((Phased) container).getPhase();
}
public void testComponentRegistration() {
assertTrue("Parser should have registered a component named 'listener1'", context.containsComponentDefinition("listener1"));
assertTrue("Parser should have registered a component named 'listener2'", context.containsComponentDefinition("listener2"));
assertTrue("Parser should have registered a component named 'listener3'", context.containsComponentDefinition("listener3"));
assertTrue("Parser should have registered a component named '" + DefaultMessageListenerContainer.class.getName() + "#0'",
context.containsComponentDefinition(DefaultMessageListenerContainer.class.getName() + "#0"));
assertTrue("Parser should have registered a component named '" + JmsMessageEndpointManager.class.getName() + "#0'",
context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0"));
}
public void testSourceExtraction() {
Iterator iterator = context.getRegisteredComponents();
while (iterator.hasNext()) {
ComponentDefinition compDef = (ComponentDefinition) iterator.next();
assertNotNull("CompositeComponentDefinition '" + compDef.getName()+ "' has no source attachment", compDef.getSource());
validateComponentDefinition(compDef);
}
}
private void validateComponentDefinition(ComponentDefinition compDef) {
BeanDefinition[] beanDefs = compDef.getBeanDefinitions();
for (BeanDefinition beanDef : beanDefs) {
assertNotNull("BeanDefinition has no source attachment", beanDef.getSource());
}
}
public static class TestMessageListener implements MessageListener {
public Message message;
public void onMessage(Message message) {
this.message = message;
}
}
/**
* Internal extension that registers a {@link ReaderEventListener} to store
* registered {@link ComponentDefinition}s.
*/
private static class ToolingTestApplicationContext extends ClassPathXmlApplicationContext {
private Set<ComponentDefinition> registeredComponents;
public ToolingTestApplicationContext(String path, Class clazz) {
super(path, clazz);
}
protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
this.registeredComponents = new HashSet<ComponentDefinition>();
beanDefinitionReader.setEventListener(new StoringReaderEventListener(this.registeredComponents));
beanDefinitionReader.setSourceExtractor(new PassThroughSourceExtractor());
}
public boolean containsComponentDefinition(String name) {
for (ComponentDefinition cd : this.registeredComponents) {
if (cd instanceof CompositeComponentDefinition) {
ComponentDefinition[] innerCds = ((CompositeComponentDefinition) cd).getNestedComponents();
for (ComponentDefinition innerCd : innerCds) {
if (innerCd.getName().equals(name)) {
return true;
}
}
}
else {
if (cd.getName().equals(name)) {
return true;
}
}
}
return false;
}
public Iterator<ComponentDefinition> getRegisteredComponents() {
return this.registeredComponents.iterator();
}
}
private static class StoringReaderEventListener extends EmptyReaderEventListener {
protected final Set<ComponentDefinition> registeredComponents;
public StoringReaderEventListener(Set<ComponentDefinition> registeredComponents) {
this.registeredComponents = registeredComponents;
}
public void componentRegistered(ComponentDefinition componentDefinition) {
this.registeredComponents.add(componentDefinition);
}
}
static class TestErrorHandler implements ErrorHandler {
public void handleError(Throwable t) {
}
}
}

View File

@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">
<jms:listener-container connection-factory="testConnectionFactory" task-executor="testTaskExecutor"
destination-resolver="testDestinationResolver" message-converter="testMessageConverter"
transaction-manager="testTransactionManager" error-handler="testErrorHandler" concurrency="1-2" phase="99">
<jms:listener id="listener1" destination="testDestination" ref="testBean1" method="setName"/>
<jms:listener id="listener2" destination="testDestination" ref="testBean2" method="setName" response-destination="responseDestination"/>
</jms:listener-container>
<!-- TODO: remove the task-executor reference once issue with blocking on stop is resolved -->
<jms:listener-container task-executor="testTaskExecutor" concurrency="${concurrency}">
<jms:listener destination="testDestination" ref="testBean3"/>
</jms:listener-container>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="concurrency">2-3</prop>
</props>
</property>
</bean>
<jms:jca-listener-container resource-adapter="testResourceAdapter" activation-spec-factory="testActivationSpecFactory"
message-converter="testMessageConverter" phase="77">
<jms:listener id="listener3" destination="testDestination" ref="testBean1" method="setName"/>
<jms:listener id="listener4" destination="testDestination" ref="testBean2" method="setName" response-destination="responseDestination"/>
</jms:jca-listener-container>
<jms:jca-listener-container activation-spec-factory="testActivationSpecFactory">
<jms:listener destination="testDestination" ref="testBean3"/>
</jms:jca-listener-container>
<!-- the default ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.StubConnectionFactory"/>
<bean id="testConnectionFactory" class="org.springframework.jms.StubConnectionFactory"/>
<!-- the default ResourceAdapter -->
<bean id="resourceAdapter" class="org.springframework.jca.StubResourceAdapter"/>
<bean id="testResourceAdapter" class="org.springframework.jca.StubResourceAdapter"/>
<bean id="testTaskExecutor" class="org.springframework.core.task.StubTaskExecutor"/>
<bean id="testActivationSpecFactory" class="org.springframework.jms.listener.endpoint.StubJmsActivationSpecFactory"/>
<bean id="testDestinationResolver" class="org.springframework.jms.support.destination.DynamicDestinationResolver"/>
<bean id="testMessageConverter" class="org.springframework.jms.support.converter.SimpleMessageConverter102"/>
<bean id="testTransactionManager" class="org.springframework.transaction.CallCountingTransactionManager"/>
<bean id="testErrorHandler" class="org.springframework.jms.config.JmsNamespaceHandlerTests$TestErrorHandler"/>
<bean id="testBean1" class="org.springframework.beans.TestBean"/>
<bean id="testBean2" class="org.springframework.beans.TestBean"/>
<bean id="testBean3" class="org.springframework.jms.config.JmsNamespaceHandlerTests$TestMessageListener"/>
<!-- TODO: remove this once issue with blocking on stop is resolved -->
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
<property name="timeoutPerShutdownPhase" value="0"/>
</bean>
</beans>

View File

@@ -0,0 +1,505 @@
/*
* 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.StubQueue;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.JmsTemplate102;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.SessionCallback;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* @author Juergen Hoeller
* @since 26.07.2004
*/
public class JmsTransactionManagerTests extends TestCase {
public void testTransactionCommit() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionRollback() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.rollback();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.rollback(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testParticipatingTransactionWithCommit() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testParticipatingTransactionWithRollbackOnly() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.rollback();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
status.setRollbackOnly();
}
});
try {
tm.commit(ts);
fail("Should have thrown UnexpectedRollbackException");
}
catch (UnexpectedRollbackException ex) {
// expected
}
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testSuspendedTransaction() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
MockControl session2Control = MockControl.createControl(Session.class);
final Session session2 = (Session) session2Control.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 2);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
con.createSession(false, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session2, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
session2.close();
session2Control.setVoidCallable(1);
con.close();
conControl.setVoidCallable(2);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess != session);
return null;
}
});
}
});
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionSuspension() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
MockControl session2Control = MockControl.createControl(Session.class);
final Session session2 = (Session) session2Control.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 2);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session2, 1);
session.commit();
sessionControl.setVoidCallable(1);
session2.commit();
session2Control.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
session2.close();
session2Control.setVoidCallable(1);
con.close();
conControl.setVoidCallable(2);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess != session);
return null;
}
});
}
});
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommitWithMessageProducer() throws JMSException {
Destination dest = new StubQueue();
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl producerControl = MockControl.createControl(MessageProducer.class);
MessageProducer producer = (MessageProducer) producerControl.getMock();
MockControl messageControl = MockControl.createControl(Message.class);
final Message message = (Message) messageControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.createProducer(dest);
sessionControl.setReturnValue(producer, 1);
producer.send(message);
producerControl.setVoidCallable(1);
session.getTransacted();
sessionControl.setReturnValue(true, 1);
session.commit();
sessionControl.setVoidCallable(1);
producer.close();
producerControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
producerControl.replay();
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.send(dest, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return message;
}
});
tm.commit(ts);
producerControl.verify();
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommit102WithQueue() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) sessionControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager102(cf, false);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate102(cf, false);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommit102WithTopic() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(TopicSession.class);
final TopicSession session = (TopicSession) sessionControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager102(cf, true);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate102(cf, true);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
protected void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
}

View File

@@ -0,0 +1,647 @@
/*
* Copyright 2002-2011 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
/**
* @author Juergen Hoeller
* @since 26.07.2004
*/
public class SingleConnectionFactoryTests extends TestCase {
public void testWithConnection() throws JMSException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
Connection con1 = scf.createConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start(); // should be ignored
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithQueueConnection() throws JMSException {
MockControl conControl = MockControl.createControl(QueueConnection.class);
Connection con = (QueueConnection) conControl.getMock();
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithTopicConnection() throws JMSException {
MockControl conControl = MockControl.createControl(TopicConnection.class);
Connection con = (TopicConnection) conControl.getMock();
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
TopicConnection con1 = scf.createTopicConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithConnectionFactory() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createQueueConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createQueueConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createTopicConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createTopicConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndClientId() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.setClientID("myId");
conControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setClientId("myId");
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndExceptionListener() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ExceptionListener listener = new ChainedExceptionListener();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.setExceptionListener(listener);
conControl.setVoidCallable(1);
con.getExceptionListener();
conControl.setReturnValue(listener, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setExceptionListener(listener);
Connection con1 = scf.createConnection();
assertEquals(listener, con1.getExceptionListener());
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndReconnectOnException() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
TestConnection con = new TestConnection();
cf.createConnection();
cfControl.setReturnValue(con, 2);
cfControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setReconnectOnException(true);
Connection con1 = scf.createConnection();
assertNull(con1.getExceptionListener());
con1.start();
con.getExceptionListener().onException(new JMSException(""));
Connection con2 = scf.createConnection();
con2.start();
scf.destroy(); // should trigger actual close
cfControl.verify();
assertEquals(2, con.getStartCount());
assertEquals(2, con.getCloseCount());
}
public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
TestConnection con = new TestConnection();
TestExceptionListener listener = new TestExceptionListener();
cf.createConnection();
cfControl.setReturnValue(con, 2);
cfControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setExceptionListener(listener);
scf.setReconnectOnException(true);
Connection con1 = scf.createConnection();
assertSame(listener, con1.getExceptionListener());
con1.start();
con.getExceptionListener().onException(new JMSException(""));
Connection con2 = scf.createConnection();
con2.start();
scf.destroy(); // should trigger actual close
cfControl.verify();
assertEquals(2, con.getStartCount());
assertEquals(2, con.getCloseCount());
assertEquals(1, listener.getCount());
}
public void testConnectionFactory102WithQueue() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testConnectionFactory102WithTopic() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory102(cf, true);
TopicConnection con1 = scf.createTopicConnection();
con1.start();
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testCachingConnectionFactory() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(Session.class);
Session txSession = (Session) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(Session.class);
Session nonTxSession = (Session) nonTxSessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 1);
txSession.commit();
txSessionControl.setVoidCallable(1);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1.close(); // should lead to rollback
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
Session session2 = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.commit();
session2.close(); // should be ignored
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(QueueSession.class);
QueueSession txSession = (QueueSession) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(QueueSession.class);
QueueSession nonTxSession = (QueueSession) nonTxSessionControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 1);
txSession.rollback();
txSessionControl.setVoidCallable(1);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createQueueConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.rollback();
session1.close(); // should be ignored
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should lead to rollback
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(TopicSession.class);
TopicSession txSession = (TopicSession) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(TopicSession.class);
TopicSession nonTxSession = (TopicSession) nonTxSessionControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 2);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(1);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createTopicConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1.close(); // should lead to rollback
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should be ignored
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
}

View File

@@ -0,0 +1,92 @@
/*
* 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionConsumer;
import javax.jms.ConnectionMetaData;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.ServerSessionPool;
import javax.jms.Session;
import javax.jms.Topic;
/**
* @author Juergen Hoeller
*/
public class TestConnection implements Connection {
private ExceptionListener exceptionListener;
private int startCount;
private int closeCount;
public Session createSession(boolean b, int i) throws JMSException {
return null;
}
public String getClientID() throws JMSException {
return null;
}
public void setClientID(String paramName) throws JMSException {
}
public ConnectionMetaData getMetaData() throws JMSException {
return null;
}
public ExceptionListener getExceptionListener() throws JMSException {
return exceptionListener;
}
public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
this.exceptionListener = exceptionListener;
}
public void start() throws JMSException {
this.startCount++;
}
public void stop() throws JMSException {
}
public void close() throws JMSException {
this.closeCount++;
}
public ConnectionConsumer createConnectionConsumer(Destination destination, String paramName, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String paramName, String paramName1, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
public int getStartCount() {
return startCount;
}
public int getCloseCount() {
return closeCount;
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.jms.connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
/**
* @author Juergen Hoeller
*/
public class TestExceptionListener implements ExceptionListener {
private int count = 0;
public void onException(JMSException ex) {
this.count++;
}
public int getCount() {
return count;
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplate102JtaTests extends JmsTemplate102Tests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
/*
* 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplate102TransactedTests extends JmsTemplate102Tests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return true;
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplateJtaTests extends JmsTemplateTests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return false;
}
}

View File

@@ -0,0 +1,847 @@
/*
* Copyright 2002-2009 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.jms.core;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.NamingException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.InvalidClientIDException;
import org.springframework.jms.InvalidDestinationException;
import org.springframework.jms.InvalidSelectorException;
import org.springframework.jms.JmsException;
import org.springframework.jms.JmsSecurityException;
import org.springframework.jms.MessageEOFException;
import org.springframework.jms.MessageFormatException;
import org.springframework.jms.MessageNotReadableException;
import org.springframework.jms.MessageNotWriteableException;
import org.springframework.jms.ResourceAllocationException;
import org.springframework.jms.TransactionInProgressException;
import org.springframework.jms.TransactionRolledBackException;
import org.springframework.jms.UncategorizedJmsException;
import org.springframework.jms.connection.ConnectionFactoryUtils;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy;
import org.springframework.jms.support.JmsUtils;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import org.springframework.jndi.JndiTemplate;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Unit tests for the JmsTemplate implemented using JMS 1.1.
*
* @author Andre Biryukov
* @author Mark Pollack
*/
public class JmsTemplateTests extends TestCase {
private Context mockJndiContext;
private MockControl mockJndiControl;
private MockControl connectionFactoryControl;
private ConnectionFactory mockConnectionFactory;
private MockControl connectionControl;
private Connection mockConnection;
private MockControl sessionControl;
private Session mockSession;
private MockControl queueControl;
private Destination mockQueue;
private int deliveryMode = DeliveryMode.PERSISTENT;
private int priority = 9;
private int timeToLive = 10000;
/**
* Create the mock objects for testing.
*/
protected void setUp() throws Exception {
mockJndiControl = MockControl.createControl(Context.class);
mockJndiContext = (Context) this.mockJndiControl.getMock();
createMockforDestination();
mockJndiContext.close();
mockJndiControl.replay();
}
private void createMockforDestination() throws JMSException, NamingException {
connectionFactoryControl = MockControl.createControl(ConnectionFactory.class);
mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock();
connectionControl = MockControl.createControl(Connection.class);
mockConnection = (Connection) connectionControl.getMock();
sessionControl = MockControl.createControl(Session.class);
mockSession = (Session) sessionControl.getMock();
queueControl = MockControl.createControl(Queue.class);
mockQueue = (Queue) queueControl.getMock();
mockConnectionFactory.createConnection();
connectionFactoryControl.setReturnValue(mockConnection);
connectionFactoryControl.replay();
mockConnection.createSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE);
connectionControl.setReturnValue(mockSession);
mockSession.getTransacted();
sessionControl.setReturnValue(useTransactedSession());
mockJndiContext.lookup("testDestination");
mockJndiControl.setReturnValue(mockQueue);
}
private JmsTemplate createTemplate() {
JmsTemplate template = new JmsTemplate();
JndiDestinationResolver destMan = new JndiDestinationResolver();
destMan.setJndiTemplate(new JndiTemplate() {
protected Context createInitialContext() {
return mockJndiContext;
}
});
template.setDestinationResolver(destMan);
template.setSessionTransacted(useTransactedTemplate());
return template;
}
protected boolean useTransactedSession() {
return false;
}
protected boolean useTransactedTemplate() {
return false;
}
public void testExceptionStackTrace() {
JMSException jmsEx = new JMSException("could not connect");
Exception innerEx = new Exception("host not found");
jmsEx.setLinkedException(innerEx);
JmsException springJmsEx = JmsUtils.convertJmsAccessException(jmsEx);
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
springJmsEx.printStackTrace(out);
String trace = sw.toString();
assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0);
}
public void testProducerCallback() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
mockSession.createProducer(null);
sessionControl.setReturnValue(mockMessageProducer);
mockMessageProducer.getPriority();
messageProducerControl.setReturnValue(4);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.execute(new ProducerCallback() {
public Object doInJms(Session session, MessageProducer producer) throws JMSException {
boolean b = session.getTransacted();
int i = producer.getPriority();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
public void testProducerCallbackWithIdAndTimestampDisabled() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageIdEnabled(false);
template.setMessageTimestampEnabled(false);
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
mockSession.createProducer(null);
sessionControl.setReturnValue(mockMessageProducer);
mockMessageProducer.setDisableMessageID(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.setDisableMessageTimestamp(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.getPriority();
messageProducerControl.setReturnValue(4);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.execute(new ProducerCallback() {
public Object doInJms(Session session, MessageProducer producer) throws JMSException {
boolean b = session.getTransacted();
int i = producer.getPriority();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
/**
* Test the method execute(SessionCallback action).
*/
public void testSessionCallback() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
sessionControl.replay();
connectionControl.replay();
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
public void testSessionCallbackWithinSynchronizedTransaction() throws Exception {
SingleConnectionFactory scf = new SingleConnectionFactory(mockConnectionFactory);
JmsTemplate template = createTemplate();
template.setConnectionFactory(scf);
mockConnection.start();
connectionControl.setVoidCallable(1);
// We're gonna call getTransacted 3 times, i.e. 2 more times.
mockSession.getTransacted();
sessionControl.setReturnValue(useTransactedSession(), 2);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.stop();
connectionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
sessionControl.replay();
connectionControl.replay();
TransactionSynchronizationManager.initSynchronization();
try {
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, null, false));
assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false));
TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf);
Connection tac = tacf.createConnection();
Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE);
boolean b = tas.getTransacted();
tas.close();
tac.close();
List synchs = TransactionSynchronizationManager.getSynchronizations();
assertEquals(1, synchs.size());
TransactionSynchronization synch = (TransactionSynchronization) synchs.get(0);
synch.beforeCommit(false);
synch.beforeCompletion();
synch.afterCommit();
synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
finally {
TransactionSynchronizationManager.clearSynchronization();
scf.destroy();
}
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
/**
* Test sending to a destination using the method
* send(Destination d, MessageCreator messageCreator)
*/
public void testSendDestination() throws Exception {
doTestSendDestination(true, false, true, false);
}
/**
* Test seding to a destination using the method
* send(String d, MessageCreator messageCreator)
*/
public void testSendDestinationName() throws Exception {
doTestSendDestination(false, false, true, false);
}
/**
* Test sending to a destination using the method
* send(Destination d, MessageCreator messageCreator) using QOS parameters.
*/
public void testSendDestinationWithQOS() throws Exception {
doTestSendDestination(true, false, false, true);
}
/**
* Test sending to a destination using the method
* send(String d, MessageCreator messageCreator) using QOS parameters.
*/
public void testSendDestinationNameWithQOS() throws Exception {
doTestSendDestination(false, false, false, true);
}
/**
* Test sending to the default destination.
*/
public void testSendDefaultDestination() throws Exception {
doTestSendDestination(true, true, true, true);
}
/**
* Test sending to the default destination name.
*/
public void testSendDefaultDestinationName() throws Exception {
doTestSendDestination(false, true, true, true);
}
/**
* Test sending to the default destination using explicit QOS parameters.
*/
public void testSendDefaultDestinationWithQOS() throws Exception {
doTestSendDestination(true, true, false, false);
}
/**
* Test sending to the default destination name using explicit QOS parameters.
*/
public void testSendDefaultDestinationNameWithQOS() throws Exception {
doTestSendDestination(false, true, false, false);
}
/**
* Common method for testing a send method that uses the MessageCreator
* callback but with different QOS options.
* @param ignoreQOS test using default QOS options.
*/
private void doTestSendDestination(
boolean explicitDestination, boolean useDefaultDestination,
boolean ignoreQOS, boolean disableIdAndTimestamp) throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
String destinationName = "testDestination";
if (useDefaultDestination) {
if (explicitDestination) {
template.setDefaultDestination(mockQueue);
}
else {
template.setDefaultDestinationName(destinationName);
}
}
if (disableIdAndTimestamp) {
template.setMessageIdEnabled(false);
template.setMessageTimestampEnabled(false);
}
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("just testing");
sessionControl.setReturnValue(mockMessage);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
if (disableIdAndTimestamp) {
mockMessageProducer.setDisableMessageID(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.setDisableMessageTimestamp(true);
messageProducerControl.setVoidCallable(1);
}
if (ignoreQOS) {
mockMessageProducer.send(mockMessage);
}
else {
template.setExplicitQosEnabled(true);
template.setDeliveryMode(deliveryMode);
template.setPriority(priority);
template.setTimeToLive(timeToLive);
mockMessageProducer.send(mockMessage, deliveryMode, priority, timeToLive);
}
messageProducerControl.setVoidCallable(1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
if (useDefaultDestination) {
template.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
else {
if (explicitDestination) {
template.send(mockQueue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
else {
template.send(destinationName, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
messageProducerControl.verify();
}
public void testConverter() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageConverter(new SimpleMessageConverter());
String s = "Hello world";
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("Hello world");
sessionControl.setReturnValue(mockMessage);
mockMessageProducer.send(mockMessage);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.convertAndSend(mockQueue, s);
messageProducerControl.verify();
sessionControl.verify();
connectionControl.verify();
connectionFactoryControl.verify();
}
public void testReceiveDefaultDestination() throws Exception {
doTestReceive(true, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDefaultDestinationName() throws Exception {
doTestReceive(false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestination() throws Exception {
doTestReceive(true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestinationWithClientAcknowledge() throws Exception {
doTestReceive(true, false, false, true, false, false, 1000);
}
public void testReceiveDestinationName() throws Exception {
doTestReceive(false, false, false, false, false, true, 1000);
}
public void testReceiveDefaultDestinationWithSelector() throws Exception {
doTestReceive(true, true, false, false, true, true, 1000);
}
public void testReceiveDefaultDestinationNameWithSelector() throws Exception {
doTestReceive(false, true, false, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveDestinationWithSelector() throws Exception {
doTestReceive(true, false, false, false, true, false, 1000);
}
public void testReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception {
doTestReceive(true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestinationNameWithSelector() throws Exception {
doTestReceive(false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveAndConvertDefaultDestination() throws Exception {
doTestReceive(true, true, true, false, false, false, 1000);
}
public void testReceiveAndConvertDefaultDestinationName() throws Exception {
doTestReceive(false, true, true, false, false, false, 1000);
}
public void testReceiveAndConvertDestinationName() throws Exception {
doTestReceive(false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveAndConvertDestination() throws Exception {
doTestReceive(true, false, true, false, false, true, 1000);
}
public void testReceiveAndConvertDefaultDestinationWithSelector() throws Exception {
doTestReceive(true, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveAndConvertDestinationNameWithSelector() throws Exception {
doTestReceive(false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveAndConvertDestinationWithSelector() throws Exception {
doTestReceive(true, false, true, false, true, false, 1000);
}
private void doTestReceive(
boolean explicitDestination, boolean useDefaultDestination, boolean testConverter,
boolean clientAcknowledge, boolean messageSelector, boolean noLocal, long timeout)
throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
String destinationName = "testDestination";
if (useDefaultDestination) {
if (explicitDestination) {
template.setDefaultDestination(mockQueue);
}
else {
template.setDefaultDestinationName(destinationName);
}
}
if (noLocal) {
template.setPubSubNoLocal(true);
}
template.setReceiveTimeout(timeout);
mockConnection.start();
connectionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class);
MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock();
String selectorString = "selector";
mockSession.createConsumer(mockQueue, messageSelector ? selectorString : null);
sessionControl.setReturnValue(mockMessageConsumer);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
else if (!useTransactedSession()) {
mockSession.getAcknowledgeMode();
if (clientAcknowledge) {
sessionControl.setReturnValue(Session.CLIENT_ACKNOWLEDGE, 1);
}
else {
sessionControl.setReturnValue(Session.AUTO_ACKNOWLEDGE, 1);
}
}
mockSession.close();
sessionControl.setVoidCallable(1);
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
if (testConverter) {
mockMessage.getText();
messageControl.setReturnValue("Hello World!");
}
if (!useTransactedSession() && clientAcknowledge) {
mockMessage.acknowledge();
messageControl.setVoidCallable(1);
}
sessionControl.replay();
connectionControl.replay();
messageControl.replay();
if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) {
mockMessageConsumer.receiveNoWait();
}
else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) {
mockMessageConsumer.receive();
}
else {
mockMessageConsumer.receive(timeout);
}
messageConsumerControl.setReturnValue(mockMessage);
mockMessageConsumer.close();
messageConsumerControl.setVoidCallable(1);
messageConsumerControl.replay();
Message message = null;
String textFromMessage = null;
if (useDefaultDestination) {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(selectorString) :
template.receiveAndConvert());
}
else {
message = (messageSelector ? template.receiveSelected(selectorString) : template.receive());
}
}
else if (explicitDestination) {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(mockQueue, selectorString) :
template.receiveAndConvert(mockQueue));
}
else {
message = (messageSelector ? template.receiveSelected(mockQueue, selectorString) :
template.receive(mockQueue));
}
}
else {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(destinationName, selectorString) :
template.receiveAndConvert(destinationName));
}
else {
message = (messageSelector ? template.receiveSelected(destinationName, selectorString) :
template.receive(destinationName));
}
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
messageConsumerControl.verify();
messageControl.verify();
if (testConverter) {
assertEquals("Message text should be equal", "Hello World!", textFromMessage);
}
else {
assertEquals("Messages should refer to the same object", message, mockMessage);
}
}
public void testIllegalStateException() throws Exception {
doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class);
}
public void testInvalidClientIDException() throws Exception {
doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class);
}
public void testInvalidDestinationException() throws Exception {
doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class);
}
public void testInvalidSelectorException() throws Exception {
doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class);
}
public void testJmsSecurityException() throws Exception {
doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class);
}
public void testMessageEOFException() throws Exception {
doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class);
}
public void testMessageFormatException() throws Exception {
doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class);
}
public void testMessageNotReadableException() throws Exception {
doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class);
}
public void testMessageNotWriteableException() throws Exception {
doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class);
}
public void testResourceAllocationException() throws Exception {
doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class);
}
public void testTransactionInProgressException() throws Exception {
doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class);
}
public void testTransactionRolledBackException() throws Exception {
doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class);
}
public void testUncategorizedJmsException() throws Exception {
doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class);
}
protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageConverter(new SimpleMessageConverter());
String s = "Hello world";
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
sessionControl.reset();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("Hello world");
sessionControl.setReturnValue(mockMessage);
mockMessageProducer.send(mockMessage);
messageProducerControl.setThrowable(original, 1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
try {
template.convertAndSend(mockQueue, s);
fail("Should have thrown JmsException");
}
catch (JmsException wrappedEx) {
// expected
assertEquals(thrownExceptionClass, wrappedEx.getClass());
assertEquals(original, wrappedEx.getCause());
}
messageProducerControl.verify();
sessionControl.verify();
connectionControl.verify();
connectionFactoryControl.verify();
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplateTransactedTests extends JmsTemplateTests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return true;
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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.jms.core.support;
import java.util.ArrayList;
import java.util.List;
import javax.jms.ConnectionFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.core.JmsTemplate;
/**
* @author Mark Pollack
* @since 24.9.2004
*/
public class JmsGatewaySupportTests extends TestCase {
public void testJmsGatewaySupportWithConnectionFactory() throws Exception {
MockControl connectionFactoryControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock();
connectionFactoryControl.replay();
final List test = new ArrayList();
JmsGatewaySupport gateway = new JmsGatewaySupport() {
protected void initGateway() {
test.add("test");
}
};
gateway.setConnectionFactory(mockConnectionFactory);
gateway.afterPropertiesSet();
assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory());
assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory());
assertEquals("initGatway called", test.size(), 1);
connectionFactoryControl.verify();
}
public void testJmsGatewaySupportWithJmsTemplate() throws Exception {
JmsTemplate template = new JmsTemplate();
final List test = new ArrayList();
JmsGatewaySupport gateway = new JmsGatewaySupport() {
protected void initGateway() {
test.add("test");
}
};
gateway.setJmsTemplate(template);
gateway.afterPropertiesSet();
assertEquals("Correct JmsTemplate", template, gateway.getJmsTemplate());
assertEquals("initGateway called", test.size(), 1);
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.jms.listener;
import org.junit.Test;
/**
* Unit tests for the {@link AbstractMessageListenerContainer} class.
*
* @author Rick Evans
* @author Chris Beams
*/
public abstract class AbstractMessageListenerContainerTests {
protected abstract AbstractMessageListenerContainer getContainer();
@Test(expected=IllegalArgumentException.class)
public void testSettingMessageListenerToANullType() throws Exception {
getContainer().setMessageListener(null);
}
@Test(expected=IllegalArgumentException.class)
public void testSettingMessageListenerToAnUnsupportedType() throws Exception {
getContainer().setMessageListener("Bingo");
}
}

View File

@@ -0,0 +1,690 @@
/*
* Copyright 2002-2009 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.jms.listener;
import static org.junit.Assert.*;
import java.util.HashSet;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.easymock.EasyMock;
import org.easymock.MockControl;
import org.easymock.internal.AlwaysMatcher;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jms.StubQueue;
import org.springframework.util.ErrorHandler;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
* @author Mark Fisher
*/
public class SimpleMessageListenerContainerTests extends AbstractMessageListenerContainerTests {
private static final String DESTINATION_NAME = "foo";
private static final String EXCEPTION_MESSAGE = "This.Is.It";
private static final StubQueue QUEUE_DESTINATION = new StubQueue();
private SimpleMessageListenerContainer container;
@Before
public void setUp() throws Exception {
this.container = (SimpleMessageListenerContainer) getContainer();
}
protected AbstractMessageListenerContainer getContainer() {
return new SimpleMessageListenerContainer();
}
@Test
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
assertFalse("The [pubSubLocal] property of SimpleMessageListenerContainer " +
"must default to false. Change this test (and the " +
"attendant Javadoc) if you have changed the default.",
container.isPubSubNoLocal());
}
@Test(expected=IllegalArgumentException.class)
public void testSettingConcurrentConsumersToZeroIsNotAllowed() throws Exception {
container.setConcurrentConsumers(0);
container.afterPropertiesSet();
}
@Test(expected=IllegalArgumentException.class)
public void testSettingConcurrentConsumersToANegativeValueIsNotAllowed() throws Exception {
container.setConcurrentConsumers(-198);
container.afterPropertiesSet();
}
@Test
public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetToFalse() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.setAutoStartup(false);
this.container.afterPropertiesSet();
GenericApplicationContext context = new GenericApplicationContext();
context.getBeanFactory().registerSingleton("messageListenerContainer", this.container);
context.refresh();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testContextRefreshedEventStartsTheConnectionByDefault() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.afterPropertiesSet();
GenericApplicationContext context = new GenericApplicationContext();
context.getBeanFactory().registerSingleton("messageListenerContainer", this.container);
context.refresh();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
session.getAcknowledgeMode();
mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final HashSet failure = new HashSet();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener() {
public void onMessage(Message message, Session sess) {
try {
// Check correct Session passed into SessionAwareMessageListener.
assertSame(sess, session);
}
catch (Throwable ex) {
failure.add("MessageListener execution failed: " + ex);
}
}
});
this.container.afterPropertiesSet();
this.container.start();
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
messageConsumer.sendMessage(message);
if (!failure.isEmpty()) {
fail(failure.iterator().next().toString());
}
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testTaskExecutorCorrectlyInvokedWhenSpecified() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
session.getTransacted();
mockSession.setReturnValue(false);
session.getAcknowledgeMode();
mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final TestMessageListener listener = new TestMessageListener();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(listener);
this.container.setTaskExecutor(new TaskExecutor() {
public void execute(Runnable task) {
listener.executorInvoked = true;
assertFalse(listener.listenerInvoked);
task.run();
assertTrue(listener.listenerInvoked);
}
});
this.container.afterPropertiesSet();
this.container.start();
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
messageConsumer.sendMessage(message);
assertTrue(listener.executorInvoked);
assertTrue(listener.listenerInvoked);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testRegisteredExceptionListenerIsInvokedOnException() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final JMSException theException = new JMSException(EXCEPTION_MESSAGE);
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener() {
public void onMessage(Message message, Session session) throws JMSException {
throw theException;
}
});
MockControl mockExceptionListener = MockControl.createControl(ExceptionListener.class);
ExceptionListener exceptionListener = (ExceptionListener) mockExceptionListener.getMock();
exceptionListener.onException(theException);
mockExceptionListener.setVoidCallable();
mockExceptionListener.replay();
this.container.setExceptionListener(exceptionListener);
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockExceptionListener.verify();
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
Session session = EasyMock.createMock(Session.class);
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
EasyMock.expectLastCall().andReturn(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
EasyMock.expectLastCall().andReturn(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
EasyMock.expectLastCall().andReturn(false);
EasyMock.replay(session);
Connection connection = EasyMock.createMock(Connection.class);
connection.setExceptionListener(this.container);
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
EasyMock.expectLastCall().andReturn(session);
// and the connection is start()ed after the listener is registered...
connection.start();
EasyMock.replay(connection);
ConnectionFactory connectionFactory = EasyMock.createMock(ConnectionFactory.class);
connectionFactory.createConnection();
EasyMock.expectLastCall().andReturn(connection);
EasyMock.replay(connectionFactory);
final IllegalStateException theException = new IllegalStateException("intentional test failure");
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener() {
public void onMessage(Message message, Session session) throws JMSException {
throw theException;
}
});
ErrorHandler errorHandler = EasyMock.createMock(ErrorHandler.class);
errorHandler.handleError(theException);
EasyMock.expectLastCall();
EasyMock.replay(errorHandler);
this.container.setErrorHandler(errorHandler);
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
Message message = EasyMock.createMock(Message.class);
EasyMock.replay(message);
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
EasyMock.verify(errorHandler, message, session, connection, connectionFactory);
}
@Test
public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillDo_NOT_Propagate() throws Exception {
this.container.setSessionTransacted(true);
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(true);
// Session is rolled back 'cos it is transacted...
session.rollback();
mockSession.setVoidCallable();
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
@Test
public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
// closing down...
messageConsumer.close();
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// closing down...
session.close();
mockSession.setVoidCallable();
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
// closing down...
connection.close();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.afterPropertiesSet();
this.container.start();
this.container.destroy();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
private static class TestMessageListener implements MessageListener {
public boolean executorInvoked = false;
public boolean listenerInvoked = false;
public void onMessage(Message message) {
this.listenerInvoked = true;
}
}
private static class SimpleMessageConsumer implements MessageConsumer {
private MessageListener messageListener;
public void sendMessage(Message message) throws JMSException {
this.messageListener.onMessage(message);
}
public String getMessageSelector() throws JMSException {
throw new UnsupportedOperationException();
}
public MessageListener getMessageListener() throws JMSException {
return this.messageListener;
}
public void setMessageListener(MessageListener messageListener) throws JMSException {
this.messageListener = messageListener;
}
public Message receive() throws JMSException {
throw new UnsupportedOperationException();
}
public Message receive(long l) throws JMSException {
throw new UnsupportedOperationException();
}
public Message receiveNoWait() throws JMSException {
throw new UnsupportedOperationException();
}
public void close() throws JMSException {
throw new UnsupportedOperationException();
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.jms.listener.adapter;
import java.util.Map;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
* @author Juergen Hoeller
*/
public interface MessageContentsDelegate {
void handleMessage(CharSequence message);
void handleMessage(Map message);
void handleMessage(byte[] message);
void handleMessage(Number message);
void handleMessage(Object message);
}

View File

@@ -0,0 +1,39 @@
/*
* 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.jms.listener.adapter;
import javax.jms.BytesMessage;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface MessageDelegate {
void handleMessage(TextMessage message);
void handleMessage(MapMessage message);
void handleMessage(BytesMessage message);
void handleMessage(ObjectMessage message);
}

View File

@@ -0,0 +1,451 @@
/*
* 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.jms.listener.adapter;
import static org.junit.Assert.*;
import javax.jms.BytesMessage;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jms.support.converter.SimpleMessageConverter102;
/**
* Unit tests for the {@link MessageListenerAdapter102} class.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class MessageListenerAdapter102Tests {
private static final String TEXT = "The Runaways";
private static final String CORRELATION_ID = "100";
private static final String RESPONSE_TEXT = "Old Lace";
@Test
public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock();
// BytesMessage contents must be unwrapped...
bytesMessage.readBytes(null);
mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER);
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
mockBytesMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT.getBytes());
mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
adapter.onMessage(bytesMessage);
mockDelegate.verify();
mockBytesMessage.verify();
}
@Test
public void testWithMessageDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter102() throws Exception {
MessageListenerAdapter102 adapter = new MessageListenerAdapter102();
assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter());
assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter102]; if you've just changed it, then change this test to reflect your change.", adapter.getMessageConverter() instanceof SimpleMessageConverter102);
}
@Test
public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setReturnValue(TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForQueue() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
@Test
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForTopic() throws Exception {
MockControl mockDestination = MockControl.createControl(Topic.class);
Topic destination = (Topic) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockTopicPublisher = MockControl.createControl(TopicPublisher.class);
TopicPublisher topicPublisher = (TopicPublisher) mockTopicPublisher.getMock();
topicPublisher.publish(responseTextMessage);
mockTopicPublisher.setVoidCallable();
topicPublisher.close();
mockTopicPublisher.setVoidCallable();
mockTopicPublisher.replay();
MockControl mockSession = MockControl.createControl(TopicSession.class);
TopicSession session = (TopicSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createPublisher(destination);
mockSession.setReturnValue(topicPublisher);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockTopicPublisher.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(sentTextMessage, session);
fail("expected InvalidDestinationException");
} catch (InvalidDestinationException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setThrowable(new JMSException("Dow!"));
// ensure that regardless of a JMSException the producer is closed...
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(sentTextMessage, session);
fail("expected JMSException");
} catch (JMSException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
@Test
public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
mockSentTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setThrowable(new IllegalArgumentException("Dow!"));
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(sentTextMessage, session);
fail("expected ListenerExecutionFailedException");
} catch (ListenerExecutionFailedException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
}
}

View File

@@ -0,0 +1,677 @@
/*
* 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.jms.listener.adapter;
import static org.junit.Assert.*;
import java.io.Serializable;
import javax.jms.BytesMessage;
import javax.jms.IllegalStateException;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class MessageListenerAdapterTests {
private static final String TEXT = "I fancy a good cuppa right now";
private static final Integer NUMBER = new Integer(1);
private static final SerializableObject OBJECT = new SerializableObject();
private static final String CORRELATION_ID = "100";
private static final String RESPONSE_TEXT = "... wi' some full fat creamy milk. Top banana.";
@Test
public void testWithMessageContentsDelegateForTextMessage() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock();
// BytesMessage contents must be unwrapped...
bytesMessage.getBodyLength();
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
bytesMessage.readBytes(null);
mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER);
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
mockBytesMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT.getBytes());
mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(bytesMessage);
mockDelegate.verify();
mockBytesMessage.verify();
}
@Test
public void testWithMessageContentsDelegateForObjectMessage() throws Exception {
MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class);
ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock();
objectMessage.getObject();
mockObjectMessage.setReturnValue(NUMBER);
mockObjectMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(NUMBER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(objectMessage);
mockDelegate.verify();
mockObjectMessage.verify();
}
@Test
public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class);
ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock();
objectMessage.getObject();
mockObjectMessage.setReturnValue(OBJECT);
mockObjectMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(OBJECT);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(objectMessage);
mockDelegate.verify();
mockObjectMessage.verify();
}
@Test
public void testWithMessageDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testWhenTheAdapterItselfIsTheDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
adapter.onMessage(textMessage);
assertTrue(adapter.wasCalled());
mockTextMessage.verify();
}
@Test
public void testRainyDayWithNoApplicableHandlingMethods() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
adapter.setDefaultListenerMethod("walnutsRock");
adapter.onMessage(textMessage);
assertFalse(adapter.wasCalled());
mockTextMessage.verify();
}
@Test
public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception {
final IllegalArgumentException exception = new IllegalArgumentException();
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setThrowable(exception);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected void handleListenerException(Throwable ex) {
assertNotNull("The Throwable passed to the handleListenerException(..) method must never be null.", ex);
assertTrue("The Throwable passed to the handleListenerException(..) method must be of type [ListenerExecutionFailedException].",
ex instanceof ListenerExecutionFailedException);
ListenerExecutionFailedException lefx = (ListenerExecutionFailedException) ex;
Throwable cause = lefx.getCause();
assertNotNull("The cause of a ListenerExecutionFailedException must be preserved.", cause);
assertSame(exception, cause);
}
};
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter());
assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter]",
adapter.getMessageConverter() instanceof SimpleMessageConverter);
}
@Test
public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertSame(adapter, adapter.getDelegate());
}
@Test
public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertEquals(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD, adapter.getDefaultListenerMethod());
}
@Test
public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setReturnValue(TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
@Test
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(null);
sentTextMessage.getJMSMessageID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class);
MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock();
messageProducer.send(responseTextMessage);
mockMessageProducer.setVoidCallable();
messageProducer.close();
mockMessageProducer.setVoidCallable();
mockMessageProducer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(messageProducer);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockMessageProducer.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(sentTextMessage, session);
fail("expected InvalidDestinationException");
} catch(InvalidDestinationException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
}
@Test
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class);
MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock();
messageProducer.send(responseTextMessage);
mockMessageProducer.setThrowable(new JMSException("Dow!"));
// ensure that regardless of a JMSException the producer is closed...
messageProducer.close();
mockMessageProducer.setVoidCallable();
mockMessageProducer.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(messageProducer);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(sentTextMessage, session);
fail("expected JMSException");
} catch(JMSException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockMessageProducer.verify();
}
@Test
public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
mockMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(message);
mockDelegate.setThrowable(new IllegalArgumentException("Dow!"));
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
try {
adapter.onMessage(message, session);
fail("expected ListenerExecutionFailedException");
} catch(ListenerExecutionFailedException ex) { /* expected */ }
mockDelegate.verify();
mockMessage.verify();
mockSession.verify();
}
@Test
public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
message.getText();
mockMessage.setReturnValue(TEXT);
mockMessage.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter() {
protected void handleListenerException(Throwable ex) {
assertTrue(ex instanceof IllegalStateException);
}
};
adapter.setDefaultListenerMethod(null);
adapter.onMessage(message);
mockMessage.verify();
}
@Test
public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
message.getText();
mockMessage.setReturnValue(TEXT);
mockMessage.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter() {
protected void handleListenerException(Throwable ex) {
assertTrue(ex instanceof javax.jms.IllegalStateException);
}
protected String getListenerMethodName(Message originalMessage, Object extractedMessage) {
return null;
}
};
adapter.setDefaultListenerMethod(null);
adapter.onMessage(message);
mockMessage.verify();
}
@Test
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
mockSentTextMessage.replay();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setMessageConverter(null);
try {
adapter.onMessage(sentTextMessage, session);
fail("expected MessageConversionException");
} catch(MessageConversionException ex) { /* expected */ }
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
}
@Test
public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseMessage = MockControl.createControl(TextMessage.class);
TextMessage responseMessage = (TextMessage) mockResponseMessage.getMock();
responseMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseMessage.setVoidCallable();
mockResponseMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createProducer(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveJmsTextMessageReturningMessageDelegate.class);
ResponsiveJmsTextMessageReturningMessageDelegate delegate = (ResponsiveJmsTextMessageReturningMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(responseMessage);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setMessageConverter(null);
adapter.onMessage(sentTextMessage, session);
mockDestination.verify();
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
mockQueueSender.verify();
mockResponseMessage.verify();
}
private static class SerializableObject implements Serializable {
}
}

View File

@@ -0,0 +1,36 @@
/*
* 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.jms.listener.adapter;
import javax.jms.TextMessage;
import javax.jms.MapMessage;
import javax.jms.BytesMessage;
import javax.jms.ObjectMessage;
import java.util.Map;
import java.io.Serializable;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface ResponsiveJmsTextMessageReturningMessageDelegate {
TextMessage handleMessage(TextMessage message);
}

View File

@@ -0,0 +1,42 @@
/*
* 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.jms.listener.adapter;
import java.io.Serializable;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface ResponsiveMessageDelegate {
String handleMessage(TextMessage message);
Map handleMessage(MapMessage message);
byte[] handleMessage(BytesMessage message);
Serializable handleMessage(ObjectMessage message);
}

View File

@@ -0,0 +1,42 @@
/*
* 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.jms.listener.adapter;
/**
* Stub extension of the {@link MessageListenerAdapter} class for use in testing.
*
* @author Rick Evans
*/
public class StubMessageListenerAdapter extends MessageListenerAdapter {
private boolean wasCalled;
public boolean wasCalled() {
return this.wasCalled;
}
public void handleMessage(String message) {
this.wasCalled = true;
}
protected void handleListenerException(Throwable ex) {
System.out.println(ex);
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.jms.listener.adapter;
/**
* Stub extension of the {@link MessageListenerAdapter102} class for use in testing.
*
* @author Rick Evans
*/
public class StubMessageListenerAdapter102 extends MessageListenerAdapter102 {
private boolean wasCalled;
public boolean wasCalled() {
return this.wasCalled;
}
public void handleMessage(String message) {
this.wasCalled = true;
}
protected void handleListenerException(Throwable ex) {
System.out.println(ex);
}
}

View File

@@ -0,0 +1,168 @@
/*
* 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.jms.listener.endpoint;
import javax.jms.Destination;
import javax.jms.Session;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jca.StubResourceAdapter;
import org.springframework.jms.StubQueue;
import org.springframework.jms.support.destination.DestinationResolver;
/**
* @author Agim Emruli
* @author Juergen Hoeller
*/
public class DefaultJmsActivationSpecFactoryTests extends TestCase {
private JmsActivationSpecConfig activationSpecConfig;
protected void setUp() throws Exception {
activationSpecConfig = new JmsActivationSpecConfig();
activationSpecConfig.setMaxConcurrency(5);
activationSpecConfig.setPrefetchSize(3);
activationSpecConfig.setAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
activationSpecConfig.setClientId("clientid");
activationSpecConfig.setDestinationName("destinationname");
activationSpecConfig.setDurableSubscriptionName("durableSubscriptionName");
activationSpecConfig.setMessageSelector("selector");
}
public void testActiveMQResourceAdapterSetup() {
activationSpecConfig.setAcknowledgeMode(Session.SESSION_TRANSACTED);
JmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory();
StubActiveMQActivationSpec spec = (StubActiveMQActivationSpec) activationSpecFactory.createActivationSpec(
new StubActiveMQResourceAdapter(), activationSpecConfig);
assertEquals(5, spec.getMaxSessions());
assertEquals(3, spec.getMaxMessagesPerSessions());
assertTrue(spec.isUseRAManagedTransaction());
}
public void testWebSphereResourceAdapterSetup() throws Exception {
Destination destination = new StubQueue();
MockControl control = MockControl.createControl(DestinationResolver.class);
DestinationResolver destinationResolver = (DestinationResolver) control.getMock();
destinationResolver.resolveDestinationName(null, "destinationname", false);
control.setReturnValue(destination);
control.replay();
DefaultJmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory();
activationSpecFactory.setDestinationResolver(destinationResolver);
StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory
.createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig);
control.verify();
assertEquals(destination, spec.getDestination());
assertEquals(5, spec.getMaxConcurrency());
assertEquals(3, spec.getMaxBatchSize());
}
private static class StubActiveMQResourceAdapter extends StubResourceAdapter {
}
private static class StubWebSphereResourceAdapterImpl extends StubResourceAdapter {
}
private static class StubActiveMQActivationSpec extends StubJmsActivationSpec {
private int maxSessions;
private int maxMessagesPerSessions;
private String destination;
private boolean useRAManagedTransaction;
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public void setMaxMessagesPerSessions(int maxMessagesPerSessions) {
this.maxMessagesPerSessions = maxMessagesPerSessions;
}
public int getMaxSessions() {
return maxSessions;
}
public int getMaxMessagesPerSessions() {
return maxMessagesPerSessions;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public boolean isUseRAManagedTransaction() {
return useRAManagedTransaction;
}
public void setUseRAManagedTransaction(boolean useRAManagedTransaction) {
this.useRAManagedTransaction = useRAManagedTransaction;
}
}
private static class StubWebSphereActivationSpecImpl extends StubJmsActivationSpec {
private Destination destination;
private int maxConcurrency;
private int maxBatchSize;
public void setDestination(Destination destination) {
this.destination = destination;
}
public Destination getDestination() {
return destination;
}
public int getMaxConcurrency() {
return maxConcurrency;
}
public void setMaxConcurrency(int maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
public int getMaxBatchSize() {
return maxBatchSize;
}
public void setMaxBatchSize(int maxBatchSize) {
this.maxBatchSize = maxBatchSize;
}
}
}

View File

@@ -0,0 +1,94 @@
/*
* 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.jms.listener.endpoint;
import javax.jms.Destination;
import org.springframework.jca.StubActivationSpec;
/**
* StubActivationSpec which implements all required and optional properties (see
* specification Appendix B.2) except the destination attribute. Because this
* can be a string but also an {@link Destination} object, which is configured
* as an administrated object.
*
* @author Agim Emruli
*/
public class StubJmsActivationSpec extends StubActivationSpec {
private String destinationType;
private String subscriptionDurability;
private String subscriptionName;
private String clientId;
private String messageSelector;
private String acknowledgeMode;
public String getDestinationType() {
return destinationType;
}
public void setDestinationType(String destinationType) {
this.destinationType = destinationType;
}
public String getSubscriptionDurability() {
return subscriptionDurability;
}
public void setSubscriptionDurability(String subscriptionDurability) {
this.subscriptionDurability = subscriptionDurability;
}
public String getSubscriptionName() {
return subscriptionName;
}
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getMessageSelector() {
return messageSelector;
}
public void setMessageSelector(String messageSelector) {
this.messageSelector = messageSelector;
}
public String getAcknowledgeMode() {
return acknowledgeMode;
}
public void setAcknowledgeMode(String acknowledgeMode) {
this.acknowledgeMode = acknowledgeMode;
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.jms.listener.endpoint;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.ResourceAdapter;
import org.springframework.jca.StubActivationSpec;
/**
* @author Juergen Hoeller
*/
public class StubJmsActivationSpecFactory implements JmsActivationSpecFactory {
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
return new StubActivationSpec();
}
}

View File

@@ -0,0 +1,413 @@
/*
* Copyright 2002-2011 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.jms.remoting;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Enumeration;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
/**
* @author Juergen Hoeller
*/
public class JmsInvokerTests extends TestCase {
private MockControl connectionFactoryControl;
private QueueConnectionFactory mockConnectionFactory;
private MockControl connectionControl;
private QueueConnection mockConnection;
private MockControl sessionControl;
private QueueSession mockSession;
private MockControl queueControl;
private Queue mockQueue;
protected void setUp() throws Exception {
connectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class);
mockConnectionFactory = (QueueConnectionFactory) connectionFactoryControl.getMock();
connectionControl = MockControl.createControl(QueueConnection.class);
mockConnection = (QueueConnection) connectionControl.getMock();
sessionControl = MockControl.createControl(QueueSession.class);
mockSession = (QueueSession) sessionControl.getMock();
queueControl = MockControl.createControl(Queue.class);
mockQueue = (Queue) queueControl.getMock();
mockConnectionFactory.createConnection();
connectionFactoryControl.setReturnValue(mockConnection, 8);
mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
connectionControl.setReturnValue(mockSession, 8);
mockConnection.start();
connectionControl.setVoidCallable(8);
connectionFactoryControl.replay();
connectionControl.replay();
}
public void testJmsInvokerProxyFactoryBeanAndServiceExporter() throws Throwable {
sessionControl.replay();
doTestJmsInvokerProxyFactoryBeanAndServiceExporter(false);
}
public void testJmsInvokerProxyFactoryBeanAndServiceExporterWithDynamicQueue() throws Throwable {
mockSession.createQueue("myQueue");
sessionControl.setReturnValue(mockQueue, 8);
sessionControl.replay();
doTestJmsInvokerProxyFactoryBeanAndServiceExporter(true);
}
private void doTestJmsInvokerProxyFactoryBeanAndServiceExporter(boolean dynamicQueue) throws Throwable {
TestBean target = new TestBean("myname", 99);
final JmsInvokerServiceExporter exporter = new JmsInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setMessageConverter(new MockSimpleMessageConverter());
exporter.afterPropertiesSet();
JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() {
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
MockControl exporterSessionControl = MockControl.createControl(Session.class);
Session mockExporterSession = (Session) exporterSessionControl.getMock();
ResponseStoringProducer mockProducer = new ResponseStoringProducer();
mockExporterSession.createProducer(requestMessage.getJMSReplyTo());
exporterSessionControl.setReturnValue(mockProducer);
exporterSessionControl.replay();
exporter.onMessage(requestMessage, mockExporterSession);
exporterSessionControl.verify();
assertTrue(mockProducer.closed);
return mockProducer.response;
}
};
pfb.setServiceInterface(ITestBean.class);
pfb.setConnectionFactory(this.mockConnectionFactory);
if (dynamicQueue) {
pfb.setQueueName("myQueue");
}
else {
pfb.setQueue(this.mockQueue);
}
pfb.setMessageConverter(new MockSimpleMessageConverter());
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
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
private static class ResponseStoringProducer implements MessageProducer {
public Message response;
public boolean closed = false;
public void setDisableMessageID(boolean b) throws JMSException {
}
public boolean getDisableMessageID() throws JMSException {
return false;
}
public void setDisableMessageTimestamp(boolean b) throws JMSException {
}
public boolean getDisableMessageTimestamp() throws JMSException {
return false;
}
public void setDeliveryMode(int i) throws JMSException {
}
public int getDeliveryMode() throws JMSException {
return 0;
}
public void setPriority(int i) throws JMSException {
}
public int getPriority() throws JMSException {
return 0;
}
public void setTimeToLive(long l) throws JMSException {
}
public long getTimeToLive() throws JMSException {
return 0;
}
public Destination getDestination() throws JMSException {
return null;
}
public void close() throws JMSException {
this.closed = true;
}
public void send(Message message) throws JMSException {
this.response = message;
}
public void send(Message message, int i, int i1, long l) throws JMSException {
}
public void send(Destination destination, Message message) throws JMSException {
}
public void send(Destination destination, Message message, int i, int i1, long l) throws JMSException {
}
}
private static class MockObjectMessage implements ObjectMessage {
private Serializable serializable;
private Destination replyTo;
public MockObjectMessage(Serializable serializable) {
this.serializable = serializable;
}
public void setObject(Serializable serializable) throws JMSException {
this.serializable = serializable;
}
public Serializable getObject() throws JMSException {
return serializable;
}
public String getJMSMessageID() throws JMSException {
return null;
}
public void setJMSMessageID(String string) throws JMSException {
}
public long getJMSTimestamp() throws JMSException {
return 0;
}
public void setJMSTimestamp(long l) throws JMSException {
}
public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
return new byte[0];
}
public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException {
}
public void setJMSCorrelationID(String string) throws JMSException {
}
public String getJMSCorrelationID() throws JMSException {
return null;
}
public Destination getJMSReplyTo() throws JMSException {
return replyTo;
}
public void setJMSReplyTo(Destination destination) throws JMSException {
this.replyTo = destination;
}
public Destination getJMSDestination() throws JMSException {
return null;
}
public void setJMSDestination(Destination destination) throws JMSException {
}
public int getJMSDeliveryMode() throws JMSException {
return 0;
}
public void setJMSDeliveryMode(int i) throws JMSException {
}
public boolean getJMSRedelivered() throws JMSException {
return false;
}
public void setJMSRedelivered(boolean b) throws JMSException {
}
public String getJMSType() throws JMSException {
return null;
}
public void setJMSType(String string) throws JMSException {
}
public long getJMSExpiration() throws JMSException {
return 0;
}
public void setJMSExpiration(long l) throws JMSException {
}
public int getJMSPriority() throws JMSException {
return 0;
}
public void setJMSPriority(int i) throws JMSException {
}
public void clearProperties() throws JMSException {
}
public boolean propertyExists(String string) throws JMSException {
return false;
}
public boolean getBooleanProperty(String string) throws JMSException {
return false;
}
public byte getByteProperty(String string) throws JMSException {
return 0;
}
public short getShortProperty(String string) throws JMSException {
return 0;
}
public int getIntProperty(String string) throws JMSException {
return 0;
}
public long getLongProperty(String string) throws JMSException {
return 0;
}
public float getFloatProperty(String string) throws JMSException {
return 0;
}
public double getDoubleProperty(String string) throws JMSException {
return 0;
}
public String getStringProperty(String string) throws JMSException {
return null;
}
public Object getObjectProperty(String string) throws JMSException {
return null;
}
public Enumeration getPropertyNames() throws JMSException {
return null;
}
public void setBooleanProperty(String string, boolean b) throws JMSException {
}
public void setByteProperty(String string, byte b) throws JMSException {
}
public void setShortProperty(String string, short i) throws JMSException {
}
public void setIntProperty(String string, int i) throws JMSException {
}
public void setLongProperty(String string, long l) throws JMSException {
}
public void setFloatProperty(String string, float v) throws JMSException {
}
public void setDoubleProperty(String string, double v) throws JMSException {
}
public void setStringProperty(String string, String string1) throws JMSException {
}
public void setObjectProperty(String string, Object object) throws JMSException {
}
public void acknowledge() throws JMSException {
}
public void clearBody() throws JMSException {
}
}
private static class MockSimpleMessageConverter extends SimpleMessageConverter {
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
return new MockObjectMessage((Serializable) object);
}
}
}

View File

@@ -0,0 +1,70 @@
/*
* 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.jms.support;
import static org.junit.Assert.*;
import javax.jms.Session;
import org.junit.Test;
/**
* Unit tests for the {@link JmsAccessor} class.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class JmsAccessorTests {
@Test(expected=IllegalArgumentException.class)
public void testChokesIfConnectionFactoryIsNotSupplied() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
accessor.afterPropertiesSet();
}
@Test
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertFalse("The [sessionTransacted] property of JmsAccessor must default to " +
"false. Change this test (and the attendant Javadoc) if you have " +
"changed the default.",
accessor.isSessionTransacted());
}
@Test
public void testAcknowledgeModeReallyDoesDefaultToAutoAcknowledge() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertEquals("The [sessionAcknowledgeMode] property of JmsAccessor must default to " +
"[Session.AUTO_ACKNOWLEDGE]. Change this test (and the attendant " +
"Javadoc) if you have changed the default.",
Session.AUTO_ACKNOWLEDGE,
accessor.getSessionAcknowledgeMode());
}
@Test(expected=IllegalArgumentException.class)
public void testSetAcknowledgeModeNameChokesIfBadAckModeIsSupplied() throws Exception {
new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!");
}
/**
* Crummy, stub, do-nothing subclass of the JmsAccessor class for use in testing.
*/
private static final class StubJmsAccessor extends JmsAccessor {
}
}

View File

@@ -0,0 +1,76 @@
/*
* 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.jms.support;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.springframework.jms.support.converter.SimpleMessageConverter102;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Arrays;
/**
* Unit tests for the {@link SimpleMessageConverter102} class.
*
* @author Juergen Hoeller
* @author Rick Evans
*/
public final class SimpleMessageConverter102Tests extends TestCase {
public void testByteArrayConversion102() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = new byte[5000];
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter102 converter = new SimpleMessageConverter102();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
}

View File

@@ -0,0 +1,267 @@
/*
* 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.jms.support;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
/**
* Unit tests for the {@link SimpleMessageConverter} class.
*
* @author Juergen Hoeller
* @author Rick Evans
* @since 18.09.2004
*/
public final class SimpleMessageConverterTests {
@Test
public void testStringConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage message = (TextMessage) messageControl.getMock();
String content = "test";
session.createTextMessage(content);
sessionControl.setReturnValue(message, 1);
message.getText();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
@Test
public void testByteArrayConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = "test".getBytes();
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.getBodyLength();
messageControl.setReturnValue(content.length, 1);
message.readBytes(new byte[content.length]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(content.length, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
@Test
public void testMapConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
Map content = new HashMap();
content.put("key1", "value1");
content.put("key2", "value2");
session.createMapMessage();
sessionControl.setReturnValue(message, 1);
message.setObject("key1", "value1");
messageControl.setVoidCallable(1);
message.setObject("key2", "value2");
messageControl.setVoidCallable(1);
message.getMapNames();
messageControl.setReturnValue(Collections.enumeration(content.keySet()));
message.getObject("key1");
messageControl.setReturnValue("value1", 1);
message.getObject("key2");
messageControl.setReturnValue("value2", 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
@Test
public void testSerializableConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
Integer content = new Integer(5);
session.createObjectMessage(content);
sessionControl.setReturnValue(message, 1);
message.getObject();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
@Test(expected=MessageConversionException.class)
public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception {
new SimpleMessageConverter().toMessage(null, null);
}
@Test(expected=MessageConversionException.class)
public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception {
new SimpleMessageConverter().toMessage(new Object(), null);
}
@Test
public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(message, session);
assertSame(message, msg);
sessionControl.verify();
messageControl.verify();
}
@Test
public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl messageControl = MockControl.createControl(Message.class);
Message message = (Message) messageControl.getMock();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Object msg = converter.fromMessage(message);
assertSame(message, msg);
messageControl.verify();
}
@Test
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(new Integer(1), "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
try {
converter.toMessage(content, session);
fail("expected MessageConversionException");
} catch (MessageConversionException ex) { /* expected */ }
sessionControl.verify();
}
@Test
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(null, "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
try {
converter.toMessage(content, session);
fail("expected MessageConversionException");
} catch (MessageConversionException ex) { /* expected */ }
sessionControl.verify();
}
}

View File

@@ -0,0 +1,177 @@
/*
* Copyright 2002-2011 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.jms.support.converter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
* @author Dave Syer
*/
public class MappingJacksonMessageConverterTests {
private MappingJacksonMessageConverter converter;
private Session sessionMock;
@Before
public void setUp() throws Exception {
sessionMock = createMock(Session.class);
converter = new MappingJacksonMessageConverter();
converter.setEncodingPropertyName("__encoding__");
converter.setTypeIdPropertyName("__typeid__");
}
@Test
public void toBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Object toBeMarshalled = new Object();
expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock);
bytesMessageMock.setStringProperty("__encoding__", "UTF-8");
bytesMessageMock.setStringProperty("__typeid__", Object.class.getName());
bytesMessageMock.writeBytes(isA(byte[].class));
replay(sessionMock, bytesMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(sessionMock, bytesMessageMock);
}
@Test
public void fromBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo",
"bar");
final byte[] bytes = "{\"foo\":\"bar\"}".getBytes();
Capture<byte[]> captured = new Capture<byte[]>() {
@Override
public void setValue(byte[] value) {
super.setValue(value);
System.arraycopy(bytes, 0, value, 0, bytes.length);
}
};
expect(
bytesMessageMock.getStringProperty("__typeid__"))
.andReturn(Object.class.getName());
expect(
bytesMessageMock.propertyExists("__encoding__"))
.andReturn(false);
expect(bytesMessageMock.getBodyLength()).andReturn(
new Long(bytes.length));
expect(bytesMessageMock.readBytes(EasyMock.capture(captured)))
.andReturn(bytes.length);
replay(sessionMock, bytesMessageMock);
Object result = converter.fromMessage(bytesMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(sessionMock, bytesMessageMock);
}
@Test
public void toTextMessageWithObject() throws Exception {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = createMock(TextMessage.class);
Object toBeMarshalled = new Object();
textMessageMock.setStringProperty("__typeid__", Object.class.getName());
expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock);
replay(sessionMock, textMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(sessionMock, textMessageMock);
}
@Test
public void toTextMessageWithMap() throws Exception {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = createMock(TextMessage.class);
Map<String, String> toBeMarshalled = new HashMap<String, String>();
toBeMarshalled.put("foo", "bar");
textMessageMock.setStringProperty("__typeid__", HashMap.class.getName());
expect(sessionMock.createTextMessage(isA(String.class))).andReturn(
textMessageMock);
replay(sessionMock, textMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(sessionMock, textMessageMock);
}
@Test
public void fromTextMessageAsObject() throws Exception {
TextMessage textMessageMock = createMock(TextMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo",
"bar");
String text = "{\"foo\":\"bar\"}";
expect(
textMessageMock.getStringProperty("__typeid__"))
.andReturn(Object.class.getName());
expect(textMessageMock.getText()).andReturn(text);
replay(sessionMock, textMessageMock);
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(sessionMock, textMessageMock);
}
@Test
public void fromTextMessageAsMap() throws Exception {
TextMessage textMessageMock = createMock(TextMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo",
"bar");
String text = "{\"foo\":\"bar\"}";
expect(
textMessageMock.getStringProperty("__typeid__"))
.andReturn(HashMap.class.getName());
expect(textMessageMock.getText()).andReturn(text);
replay(sessionMock, textMessageMock);
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(sessionMock, textMessageMock);
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright 2002-2009 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.jms.support.converter;
import javax.jms.BytesMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
/**
* @author Arjen Poutsma
*/
public class MarshallingMessageConverterTests {
private MarshallingMessageConverter converter;
private Marshaller marshallerMock;
private Unmarshaller unmarshallerMock;
private Session sessionMock;
@Before
public void setUp() throws Exception {
marshallerMock = createMock(Marshaller.class);
unmarshallerMock = createMock(Unmarshaller.class);
sessionMock = createMock(Session.class);
converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock);
}
@Test
public void toBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Object toBeMarshalled = new Object();
expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock);
marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class));
bytesMessageMock.writeBytes(isA(byte[].class));
replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
}
@Test
public void fromBytesMessage() throws Exception {
BytesMessage bytesMessageMock = createMock(BytesMessage.class);
Object unmarshalled = new Object();
expect(bytesMessageMock.getBodyLength()).andReturn(10L);
expect(bytesMessageMock.readBytes(isA(byte[].class))).andReturn(0);
expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled);
replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
Object result = converter.fromMessage(bytesMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock);
}
@Test
public void toTextMessage() throws Exception {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = createMock(TextMessage.class);
Object toBeMarshalled = new Object();
expect(sessionMock.createTextMessage(isA(String.class))).andReturn(textMessageMock);
marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class));
replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
converter.toMessage(toBeMarshalled, sessionMock);
verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
}
@Test
public void fromTextMessage() throws Exception {
TextMessage textMessageMock = createMock(TextMessage.class);
Object unmarshalled = new Object();
String text = "foo";
expect(textMessageMock.getText()).andReturn(text);
expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled);
replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock);
}
}

View File

@@ -0,0 +1,108 @@
/*
* 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.jms.support.destination;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.StubQueue;
import org.springframework.jms.StubTopic;
/**
* @author Rick Evans
*/
public class DynamicDestinationResolverTests extends TestCase {
private static final String DESTINATION_NAME = "foo";
public void testResolveWithPubSubTopicSession() throws Exception {
Topic expectedDestination = new StubTopic();
MockControl mockSession = MockControl.createControl(TopicSession.class);
TopicSession session = (TopicSession) mockSession.getMock();
session.createTopic(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, true);
mockSession.verify();
}
public void testResolveWithPubSubVanillaSession() throws Exception {
Topic expectedDestination = new StubTopic();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTopic(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, true);
mockSession.verify();
}
public void testResolveWithPointToPointQueueSession() throws Exception {
Queue expectedDestination = new StubQueue();
MockControl mockSession = MockControl.createControl(QueueSession.class);
Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, false);
mockSession.verify();
}
public void testResolveWithPointToPointVanillaSession() throws Exception {
Queue expectedDestination = new StubQueue();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, false);
mockSession.verify();
}
private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException {
DynamicDestinationResolver resolver = new DynamicDestinationResolver();
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, isPubSub);
assertNotNull(destination);
assertSame(expectedDestination, destination);
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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.jms.support.destination;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import javax.jms.ConnectionFactory;
import org.junit.Test;
/**
* @author Rick Evans
* @author Chris Beams
*/
public class JmsDestinationAccessorTests {
@Test
public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exception {
ConnectionFactory connectionFactory = createMock(ConnectionFactory.class);
replay(connectionFactory);
try {
JmsDestinationAccessor accessor = new StubJmsDestinationAccessor();
accessor.setConnectionFactory(connectionFactory);
accessor.setDestinationResolver(null);
accessor.afterPropertiesSet();
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException ex) { /* expected */ }
verify(connectionFactory);
}
@Test
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsDestinationAccessor accessor = new StubJmsDestinationAccessor();
assertFalse("The [pubSubDomain] property of JmsDestinationAccessor must default to " +
"false (i.e. Queues are used by default). Change this test (and the " +
"attendant Javadoc) if you have changed the default.",
accessor.isPubSubDomain());
}
private static class StubJmsDestinationAccessor extends JmsDestinationAccessor {
}
}

View File

@@ -0,0 +1,160 @@
/*
* 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.jms.support.destination;
import static org.junit.Assert.*;
import javax.jms.Destination;
import javax.jms.Session;
import javax.naming.NamingException;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jms.StubTopic;
/**
* @author Rick Evans
* @author Chris Beams
*/
public class JndiDestinationResolverTests {
private static final String DESTINATION_NAME = "foo";
private static final Destination DESTINATION = new StubTopic();
@Test
public void testHitsCacheSecondTimeThrough() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver();
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
mockSession.verify();
}
@Test
public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
CountingCannedJndiDestinationResolver resolver
= new CountingCannedJndiDestinationResolver();
resolver.setCache(false);
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
assertEquals(1, resolver.getCallCount());
destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
assertEquals(2, resolver.getCallCount());
mockSession.verify();
}
@Test
public void testDelegatesToFallbackIfNotResolvedInJndi() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class);
DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock();
dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, true);
mockDestinationResolver.setReturnValue(DESTINATION);
mockDestinationResolver.replay();
JndiDestinationResolver resolver = new JndiDestinationResolver() {
protected Object lookup(String jndiName, Class requiredClass) throws NamingException {
throw new NamingException();
}
};
resolver.setFallbackToDynamicDestination(true);
resolver.setDynamicDestinationResolver(dynamicResolver);
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
mockSession.verify();
mockDestinationResolver.verify();
}
@Test
public void testDoesNotDelegateToFallbackIfNotResolvedInJndi() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class);
DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock();
mockDestinationResolver.replay();
final JndiDestinationResolver resolver = new JndiDestinationResolver() {
protected Object lookup(String jndiName, Class requiredClass) throws NamingException {
throw new NamingException();
}
};
resolver.setDynamicDestinationResolver(dynamicResolver);
try {
resolver.resolveDestinationName(session, DESTINATION_NAME, true);
fail("expected DestinationResolutionException");
} catch (DestinationResolutionException ex) { /* expected */ }
mockSession.verify();
mockDestinationResolver.verify();
}
private static class OneTimeLookupJndiDestinationResolver extends JndiDestinationResolver {
private boolean called;
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
if (called) {
fail("Must not be delegating to lookup(..), must be resolving from cache.");
}
assertEquals(DESTINATION_NAME, jndiName);
called = true;
return DESTINATION;
}
}
private static class CountingCannedJndiDestinationResolver extends JndiDestinationResolver {
private int callCount;
public int getCallCount() {
return this.callCount;
}
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
++this.callCount;
return DESTINATION;
}
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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.transaction;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class CallCountingTransactionManager extends AbstractPlatformTransactionManager {
public TransactionDefinition lastDefinition;
public int begun;
public int commits;
public int rollbacks;
public int inflight;
protected Object doGetTransaction() {
return new Object();
}
protected void doBegin(Object transaction, TransactionDefinition definition) {
this.lastDefinition = definition;
++begun;
++inflight;
}
protected void doCommit(DefaultTransactionStatus status) {
++commits;
--inflight;
}
protected void doRollback(DefaultTransactionStatus status) {
++rollbacks;
--inflight;
}
public void clear() {
begun = commits = rollbacks = inflight = 0;
}
}