Now using properties for loading defaults in (Soap)MessageDispatcherServlet. Necessary because of a tangle between the transport and server packages.

This commit is contained in:
Arjen Poutsma
2007-01-22 16:03:13 +00:00
parent 460a22cdc0
commit ef0dd4e6ea
11 changed files with 454 additions and 400 deletions

View File

@@ -17,18 +17,27 @@
package org.springframework.ws.server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.ws.NoEndpointFoundException;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.MessageEndpointAdapter;
import org.springframework.ws.server.endpoint.PayloadEndpointAdapter;
import org.springframework.ws.transport.WebServiceMessageReceiver;
import org.springframework.ws.transport.support.DefaultStrategiesHelper;
/**
* Central dispatcher for use withing Spring-WS. Dispatches Web service messages to registered endoints.
@@ -50,7 +59,7 @@ import org.springframework.ws.transport.WebServiceMessageReceiver;
* @see EndpointExceptionResolver
* @see org.springframework.web.servlet.DispatcherServlet
*/
public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAware {
public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAware, ApplicationContextAware {
/**
* Log category to use when no mapped endpoint is found for a request.
@@ -67,6 +76,8 @@ public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAwa
*/
protected final Log logger = LogFactory.getLog(getClass());
private final DefaultStrategiesHelper defaultStrategiesHelper;
/**
* The registered bean name for this dispatcher.
*/
@@ -91,7 +102,8 @@ public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAwa
* Initializes a new instance of the <code>MessageDispatcher</code>.
*/
public MessageDispatcher() {
initDefaultStrategies();
Resource resource = new ClassPathResource(ClassUtils.getShortName(getClass()) + ".properties", getClass());
defaultStrategiesHelper = new DefaultStrategiesHelper(resource);
}
/**
@@ -140,6 +152,12 @@ public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAwa
this.beanName = beanName;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
initEndpointAdapters(applicationContext);
initEndpointExceptionResolvers(applicationContext);
initEndpointMappings(applicationContext);
}
public void receive(MessageContext messageContext) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("MessageDispatcher with name '" + beanName + "' received request [" +
@@ -260,21 +278,6 @@ public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAwa
return true;
}
/**
* Initialize the default implementations for the dispatcher's strategies: <code>MessageEndpointAdapter</code> and
* <code>PayloadEndpointAdapter</code>.
*
* @see #setEndpointAdapters(java.util.List)
* @see org.springframework.ws.server.endpoint.MessageEndpointAdapter
* @see org.springframework.ws.server.endpoint.PayloadEndpointAdapter
*/
protected void initDefaultStrategies() {
List defaultEndpointAdapters = new ArrayList();
defaultEndpointAdapters.add(new MessageEndpointAdapter());
defaultEndpointAdapters.add(new PayloadEndpointAdapter());
setEndpointAdapters(defaultEndpointAdapters);
}
/**
* Determine an error <code>SOAPMessage</code> respone via the registered <code>EndpointExceptionResolvers</code>.
* Most likely, the response contains a <code>SOAPFault</code>. If no suitable resolver was found, the exception is
@@ -323,4 +326,76 @@ public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAwa
}
}
}
/**
* Initialize the <code>EndpointAdapters</code> used by this class. If no adapter beans are explictely set by using
* the <code>endpointAdapters</code> property, we use the default strategies.
*
* @see #setEndpointAdapters(java.util.List)
*/
private void initEndpointAdapters(ApplicationContext applicationContext) throws BeansException {
if (endpointAdapters == null) {
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointAdapters = new ArrayList(matchingBeans.values());
Collections.sort(endpointAdapters, new OrderComparator());
}
else {
endpointAdapters =
defaultStrategiesHelper.getDefaultStrategies(EndpointAdapter.class, applicationContext);
if (logger.isInfoEnabled() && !endpointAdapters.isEmpty()) {
logger.info("No EndpointAdapters found, using defaults");
}
}
}
}
/**
* Initialize the <code>EndpointExceptionResolver</code> used by this class. If no resolver beans are explictely set
* by using the <code>endpointExceptionResolvers</code> property, we use the default strategies.
*
* @see #setEndpointExceptionResolvers(java.util.List)
*/
private void initEndpointExceptionResolvers(ApplicationContext applicationContext) throws BeansException {
if (endpointExceptionResolvers == null) {
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointExceptionResolvers = new ArrayList(matchingBeans.values());
Collections.sort(endpointExceptionResolvers, new OrderComparator());
}
else {
endpointExceptionResolvers = defaultStrategiesHelper
.getDefaultStrategies(EndpointExceptionResolver.class, applicationContext);
if (logger.isInfoEnabled() && !endpointExceptionResolvers.isEmpty()) {
logger.info("No EndpointExceptionResolvers found, using defaults");
}
}
}
}
/**
* Initialize the <code>EndpointMappings</code> used by this class. If no mapping beans are explictely set by using
* the <code>endpointMappings</code> property, we use the default strategies.
*
* @see #setEndpointMappings(java.util.List)
*/
private void initEndpointMappings(ApplicationContext applicationContext) throws BeansException {
if (endpointMappings == null) {
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointMappings = new ArrayList(matchingBeans.values());
Collections.sort(endpointMappings, new OrderComparator());
}
else {
endpointMappings = defaultStrategiesHelper
.getDefaultStrategies(EndpointMapping.class, applicationContext);
if (logger.isInfoEnabled() && !endpointMappings.isEmpty()) {
logger.info("No EndpointMappings found, using defaults");
}
}
}
}
}

View File

@@ -17,7 +17,6 @@
package org.springframework.ws.soap.server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@@ -36,7 +35,6 @@ import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.SoapVersion;
import org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver;
import org.springframework.ws.soap.soap12.Soap12Header;
/**
@@ -76,19 +74,6 @@ public class SoapMessageDispatcher extends MessageDispatcher {
this.mustUnderstandFaultLocale = mustUnderstandFaultLocale;
}
/**
* Initialize the default implementations for the dispatcher's strategies, in addition to the strategies defined in
* the base class: a <code>SimpleSoapExceptionResolver</code> as exception resolver.
*
* @see org.springframework.ws.server.MessageDispatcher#initDefaultStrategies()
* @see #setEndpointExceptionResolvers(java.util.List)
* @see org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver
*/
protected void initDefaultStrategies() {
super.initDefaultStrategies();
setEndpointExceptionResolvers(Collections.singletonList(new SimpleSoapExceptionResolver()));
}
/**
* Process the <code>MustUnderstand</code> headers in the incoming SOAP request message. Iterates over all SOAP
* headers which should be understood, and determines whether these are supported. Generates a SOAP MustUnderstand

View File

@@ -1,33 +1,22 @@
package org.springframework.ws.transport.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.util.WebUtils;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.server.EndpointAdapter;
import org.springframework.ws.server.EndpointExceptionResolver;
import org.springframework.ws.server.EndpointMapping;
import org.springframework.ws.server.MessageDispatcher;
import org.springframework.ws.transport.WebServiceMessageReceiver;
import org.springframework.ws.transport.support.DefaultStrategiesHelper;
import org.springframework.ws.wsdl.WsdlDefinition;
/**
@@ -51,40 +40,15 @@ import org.springframework.ws.wsdl.WsdlDefinition;
*/
public class MessageDispatcherServlet extends FrameworkServlet {
/**
* Well-known name for the <code>EndpointAdapter</code> object in the bean factory for this namespace. Only used
* when <code>detectAllEndpointAdapters</code> is turned off.
*
* @see #setDetectAllEndpointAdapters(boolean)
* @see org.springframework.ws.server.EndpointAdapter
*/
public static final String ENDPOINT_ADAPTER_BEAN_NAME = "endpointAdapter";
/**
* Well-known name for the <code>EndpointExceptionResolver</code> object in the bean factory for this namespace.
* Only used when "detectAllEndpointExceptionResolvers" is turned off.
*
* @see #setDetectAllEndpointExceptionResolvers
*/
public static final String ENDPOINT_EXCEPTION_RESOLVER_BEAN_NAME = "endpointExceptionResolver";
/**
* Well-known name for the <code>EndpointMapping</code> object in the bean factory for this namespace. Only used
* when "detectAllEndpointMappings" is turned off.
*
* @see #setDetectAllEndpointMappings
*/
public static final String ENDPOINT_MAPPING_BEAN_NAME = "endpointMapping";
/**
* Well-known name for the <code>WebServiceMessageFactory</code> object in the bean factory for this namespace.
*/
public static final String WEB_SERVICE_MESSAGE_FACTORY_BEAN_NAME = "messageFactory";
/**
* Well-known name for the <code>MessageDispatcher</code> object in the bean factory for this namespace.
* Well-known name for the <code>WebServiceMessageReceiver</code> object in the bean factory for this namespace.
*/
public static final String MESSAGE_DISPATCHER_BEAN_NAME = "messageDispatcher";
public static final String MESSAGE_RECEIVER_BEAN_NAME = "messageReceiver";
/**
* Name of the class path resource (relative to the MessageDispatcherServlet class) that defines
@@ -97,27 +61,7 @@ public class MessageDispatcherServlet extends FrameworkServlet {
*/
private static final String WSDL_SUFFIX_NAME = ".wsdl";
private static final Properties defaultStrategies = new Properties();
/**
* Detect all <code>EndpointAdapter</code>s or just expect "endpointAdapter" bean?
*/
private boolean detectAllEndpointAdapters = true;
/**
* Detect all <code>EndpointExceptionResolver</code>s or just expect "endpointExceptionResolver" bean?
*/
private boolean detectAllEndpointExceptionResolvers = true;
/**
* Detect all <code>EndpointMapping</code>s or just expect "endpointMapping" bean?
*/
private boolean detectAllEndpointMappings = true;
/**
* Detect all <code>WsdlDefinition</code>s?
*/
private boolean detectAllWsdlDefinitions = true;
private final DefaultStrategiesHelper defaultStrategiesHelper;
/**
* The <code>WebServiceMessageReceiverHandlerAdapter</code> used by this servlet.
@@ -131,104 +75,46 @@ public class MessageDispatcherServlet extends FrameworkServlet {
private WsdlDefinitionHandlerAdapter wsdlDefinitionHandlerAdapter = new WsdlDefinitionHandlerAdapter();
/**
* The <code>MessageDispatcher</code> used by this servlet.
* The <code>WebServiceMessageReceiver</code> used by this servlet.
*/
private MessageDispatcher messageDispatcher;
private WebServiceMessageReceiver messageReceiver;
/**
* Keys are beans names, values are <code>WsdlDefinition</code>s.
* Keys are bean names, values are <code>WsdlDefinition</code>s.
*/
private Map wsdlDefinitions;
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, MessageDispatcherServlet.class);
InputStream is = resource.getInputStream();
try {
defaultStrategies.load(is);
}
finally {
is.close();
}
}
catch (IOException ex) {
throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());
}
}
/**
* Public constructor, necessary for some Web application servers.
*/
public MessageDispatcherServlet() {
defaultStrategiesHelper = new DefaultStrategiesHelper(
new ClassPathResource(DEFAULT_STRATEGIES_PATH, MessageDispatcherServlet.class));
}
/**
* Returns the <code>MessageDispatcher</code> used by this servlet.
* Returns the <code>WebServiceMessageReceiver</code> used by this servlet.
*/
protected MessageDispatcher getMessageDispatcher() {
return messageDispatcher;
}
/**
* Set whether to detect all <code>EndpointAdapter</code> beans in this servlet's context. Else, just a single bean
* with name "endpointAdapter" will be expected.
* <p/>
* Default is <code>true</code>. Turn this off if you want this servlet to use a single adapter, despite multiple
* adapter beans being defined in the context.
*
* @see org.springframework.ws.server.EndpointAdapter
*/
public void setDetectAllEndpointAdapters(boolean detectAllEndpointAdapters) {
this.detectAllEndpointAdapters = detectAllEndpointAdapters;
}
/**
* Set whether to detect all <code>EndpointExceptionResolver</code> beans in this servlet's context. Else, just a
* single bean with name "endpointExceptionResolver" will be expected.
* <p/>
* Default is <code>true</code>. Turn this off if you want this servlet to use a single exception resolver, despite
* multiple resolver beans being defined in the context.
*
* @see org.springframework.ws.server.EndpointExceptionResolver
*/
public void setDetectAllEndpointExceptionResolvers(boolean detectAllEndpointExceptionResolvers) {
this.detectAllEndpointExceptionResolvers = detectAllEndpointExceptionResolvers;
}
/**
* Set whether to detect all <code>EndpointMapping</code> beans in this servlet's context. Else, just a single bean
* with name "endpointMapping" will be expected.
* <p/>
* Default is <code>true</code>. Turn this off if you want this servlet to use a single mapping, despite multiple
* mapping beans being defined in the context.
*
* @see org.springframework.ws.server.EndpointMapping
*/
public void setDetectAllEndpointMappings(boolean detectAllEndpointMappings) {
this.detectAllEndpointMappings = detectAllEndpointMappings;
}
/**
* Set whether to detect all <code>WsdlDefinition</code> beans in this servlet's context.
* <p/>
* Default is <code>true</code>.
*
* @see org.springframework.ws.wsdl.WsdlDefinition
*/
public void setDetectAllWsdlDefinitions(boolean detectAllWsdlDefinitions) {
this.detectAllWsdlDefinitions = detectAllWsdlDefinitions;
}
protected long getLastModified(HttpServletRequest req) {
return messageReceiverHandlerAdapter.getLastModified(req, messageDispatcher);
protected WebServiceMessageReceiver getMessageReceiver() {
return messageReceiver;
}
protected void initFrameworkServlet() throws ServletException, BeansException {
initWebServiceMessageFactory();
initMessageDispatcher();
initMessageReceiver();
initWsdlDefinitions();
}
protected long getLastModified(HttpServletRequest httpServletRequest) {
WsdlDefinition definition = getWsdlDefinition(httpServletRequest);
if (definition != null) {
return wsdlDefinitionHandlerAdapter.getLastModified(httpServletRequest, definition);
}
else {
return messageReceiverHandlerAdapter.getLastModified(httpServletRequest, messageReceiver);
}
}
protected void doService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
WsdlDefinition definition = getWsdlDefinition(httpServletRequest);
@@ -236,7 +122,7 @@ public class MessageDispatcherServlet extends FrameworkServlet {
wsdlDefinitionHandlerAdapter.handle(httpServletRequest, httpServletResponse, definition);
}
else {
messageReceiverHandlerAdapter.handle(httpServletRequest, httpServletResponse, messageDispatcher);
messageReceiverHandlerAdapter.handle(httpServletRequest, httpServletResponse, messageReceiver);
}
}
@@ -248,9 +134,8 @@ public class MessageDispatcherServlet extends FrameworkServlet {
*
* @param request the <code>HttpServletRequest</code>
* @return a definition, or <code>null</code>
* @throws Exception in case of errors
*/
protected WsdlDefinition getWsdlDefinition(HttpServletRequest request) throws Exception {
protected WsdlDefinition getWsdlDefinition(HttpServletRequest request) {
if ("GET".equals(request.getMethod()) && request.getRequestURI().endsWith(WSDL_SUFFIX_NAME)) {
String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI());
return (WsdlDefinition) wsdlDefinitions.get(fileName);
@@ -260,153 +145,6 @@ public class MessageDispatcherServlet extends FrameworkServlet {
}
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p/>
* The default implementation uses the "MessageDispatcherServlet.properties" file (in the same package as the
* MessageDispatcherServlet class) to determine the class names. It instantiates the strategy objects and satisifies
* ApplicationContextAware if necessary.
*
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
* @throws BeansException if initialization failed
* @see #DEFAULT_STRATEGIES_PATH
*/
protected List getDefaultStrategies(Class strategyInterface) throws BeansException {
String key = strategyInterface.getName();
try {
List strategies = null;
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
strategies = new ArrayList(classNames.length);
for (int i = 0; i < classNames.length; i++) {
Class clazz = Class.forName(classNames[i], true, getClass().getClassLoader());
Object strategy = BeanUtils.instantiateClass(clazz);
if (strategy instanceof ApplicationContextAware) {
((ApplicationContextAware) strategy).setApplicationContext(getWebApplicationContext());
}
strategies.add(strategy);
}
}
else {
strategies = Collections.EMPTY_LIST;
}
return strategies;
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class for interface [" + key + "]", ex);
}
}
/**
* Return the default strategy object for the given strategy interface.
* <p/>
* Default implementation delegates to <code>getDefaultStrategies</code>, expecting a single object in the list.
*
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @throws BeansException if initialization failed
* @see #getDefaultStrategies
*/
protected Object getDefaultStrategy(Class strategyInterface) throws BeansException {
List strategies = getDefaultStrategies(strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"MessageDispatcherServlet needs exactly 1 strategy for [" + strategyInterface.getName() + "]");
}
return strategies.get(0);
}
/**
* Initialize the <code>EndpointAdapters</code> used by this class. If no adapter beans are defined in the bean
* factory for this namespace, we default to the strategies in <code>MessageDispatcher</code>.
*
* @see org.springframework.ws.server.MessageDispatcher#initDefaultStrategies()
*/
private void initEndpointAdapters() throws BeansException {
if (detectAllEndpointAdapters) {
// Find all EndpointAdapters in the ApplicationContext, including ancestor contexts.
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(getWebApplicationContext(), EndpointAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
List endpointAdapters = new ArrayList(matchingBeans.values());
// We keep EndpointAdapters in sorted order.
Collections.sort(endpointAdapters, new OrderComparator());
messageDispatcher.setEndpointAdapters(endpointAdapters);
}
}
else {
try {
Object endointAdapter =
getWebApplicationContext().getBean(ENDPOINT_ADAPTER_BEAN_NAME, EndpointAdapter.class);
messageDispatcher.setEndpointAdapters(Collections.singletonList(endointAdapter));
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll use the default adapters of MessageDispatcher
}
}
}
/**
* Initialize the <code>EndpointExceptionResolver</code> used by this class. If no bean is defined with the given
* name in the BeanFactory for this namespace, we default to the strategies in <code>MessageDispatcher</code>.
*/
private void initEndpointExceptionResolvers() throws BeansException {
if (detectAllEndpointExceptionResolvers) {
// Find all EndpointExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(getWebApplicationContext(),
EndpointExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
List endpointExceptionResolvers = new ArrayList(matchingBeans.values());
// We keep EndpointExceptionResolvers in sorted order.
Collections.sort(endpointExceptionResolvers, new OrderComparator());
messageDispatcher.setEndpointExceptionResolvers(endpointExceptionResolvers);
}
}
else {
try {
Object endpointExceptionResolver = getWebApplicationContext()
.getBean(ENDPOINT_EXCEPTION_RESOLVER_BEAN_NAME, EndpointExceptionResolver.class);
messageDispatcher.setEndpointExceptionResolvers(Collections.singletonList(endpointExceptionResolver));
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll use the default adapters of MessageDispatcher
}
}
}
/**
* Initialize the <code>EndpointMappings</code> used by this class. If no mapping beans are defined in the
* BeanFactory for this namespace, we default to the strategies in <code>MessageDispatcher</code>.
*
* @see org.springframework.ws.server.MessageDispatcher#initDefaultStrategies()
*/
private void initEndpointMappings() throws BeansException {
if (detectAllEndpointMappings) {
// Find all EndpointMappings in the ApplicationContext, including ancestor contexts.
Map matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(getWebApplicationContext(), EndpointMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
List endpointMappings = new ArrayList(matchingBeans.values());
// We keep EndpointMappings in sorted order.
Collections.sort(endpointMappings, new OrderComparator());
messageDispatcher.setEndpointMappings(endpointMappings);
}
}
else {
try {
Object endpointMapping =
getWebApplicationContext().getBean(ENDPOINT_MAPPING_BEAN_NAME, EndpointMapping.class);
messageDispatcher.setEndpointMappings(Collections.singletonList(endpointMapping));
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll use the default adapters of MessageDispatcher
}
}
}
private void initWebServiceMessageFactory() throws BeansException {
WebServiceMessageFactory messageFactory;
try {
@@ -414,7 +152,8 @@ public class MessageDispatcherServlet extends FrameworkServlet {
.getBean(WEB_SERVICE_MESSAGE_FACTORY_BEAN_NAME, WebServiceMessageFactory.class);
}
catch (NoSuchBeanDefinitionException ignored) {
messageFactory = (WebServiceMessageFactory) getDefaultStrategy(WebServiceMessageFactory.class);
messageFactory = (WebServiceMessageFactory) defaultStrategiesHelper
.getDefaultStrategy(WebServiceMessageFactory.class, getWebApplicationContext());
if (logger.isInfoEnabled()) {
logger.info("Unable to locate WebServiceMessageFactory with name '" +
WEB_SERVICE_MESSAGE_FACTORY_BEAN_NAME + "': using default [" + messageFactory + "]");
@@ -432,31 +171,27 @@ public class MessageDispatcherServlet extends FrameworkServlet {
messageReceiverHandlerAdapter.setMessageFactory(messageFactory);
}
private void initMessageDispatcher() {
private void initMessageReceiver() {
try {
messageDispatcher = (MessageDispatcher) getWebApplicationContext()
.getBean(MESSAGE_DISPATCHER_BEAN_NAME, MessageDispatcher.class);
messageReceiver = (WebServiceMessageReceiver) getWebApplicationContext()
.getBean(MESSAGE_RECEIVER_BEAN_NAME, WebServiceMessageReceiver.class);
}
catch (NoSuchBeanDefinitionException ex) {
messageDispatcher = (MessageDispatcher) getDefaultStrategy(MessageDispatcher.class);
messageDispatcher.setBeanName(getServletName());
if (logger.isInfoEnabled()) {
logger.info("Unable to locate MessageDispatcher with name '" + MESSAGE_DISPATCHER_BEAN_NAME +
"': using default [" + messageDispatcher + "]");
messageReceiver = (WebServiceMessageReceiver) defaultStrategiesHelper
.getDefaultStrategy(WebServiceMessageReceiver.class, getWebApplicationContext());
if (messageReceiver instanceof BeanNameAware) {
((BeanNameAware) messageReceiver).setBeanName(getServletName());
}
if (logger.isInfoEnabled()) {
logger.info("Unable to locate MessageDispatcher with name '" + MESSAGE_RECEIVER_BEAN_NAME +
"': using default [" + messageReceiver + "]");
}
// We only autodetect the following strategies when a message dispatcher has not been defined in
// the application context
initEndpointMappings();
initEndpointAdapters();
initEndpointExceptionResolvers();
}
}
private void initWsdlDefinitions() {
if (detectAllWsdlDefinitions) {
// Find all WsdlDefinitions in the ApplicationContext, incuding ancestor contexts.
wsdlDefinitions = BeanFactoryUtils
.beansOfTypeIncludingAncestors(getWebApplicationContext(), WsdlDefinition.class, true, false);
}
// Find all WsdlDefinitions in the ApplicationContext, incuding ancestor contexts.
wsdlDefinitions = BeanFactoryUtils
.beansOfTypeIncludingAncestors(getWebApplicationContext(), WsdlDefinition.class, true, false);
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright 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.ws.transport.support;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Helper class for for loading default implementations of an interface. Encapsulates a properties object, which
* contains strategy interface names as keys, and comma-separated class names as values.
*
* @author Arjen Poutsma
*/
public class DefaultStrategiesHelper {
/**
* Keys are strategy interface names, values are implementation class names.
*/
private Properties defaultStrategies = new Properties();
/**
* Initializes a new instance of the <code>DefaultStrategiesHelper</code> based on the given set of properties.
*/
public DefaultStrategiesHelper(Properties defaultStrategies) {
Assert.notNull(defaultStrategies, "defaultStrategies must not be null");
this.defaultStrategies = defaultStrategies;
}
/**
* Initializes a new instance of the <code>DefaultStrategiesHelper</code> based on the given resource.
*/
public DefaultStrategiesHelper(Resource resource) {
try {
InputStream is = resource.getInputStream();
defaultStrategies = new Properties();
try {
defaultStrategies.load(is);
}
finally {
is.close();
}
}
catch (IOException ex) {
throw new IllegalStateException("Could not load '" + resource + "': " + ex.getMessage());
}
}
/**
* Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the given
* <code>Properties</code> object. It instantiates the strategy objects and satisifies
* <code>ApplicationContextAware</code> with the supplied context if necessary.
*
* @param strategyInterface the strategy interface
* @param applicationContext used to satisfy strategies that are application context aware
* @return a list of corresponding strategy objects
* @throws BeansException if initialization failed
*/
public List getDefaultStrategies(Class strategyInterface, ApplicationContext applicationContext)
throws BeanInitializationException {
String key = strategyInterface.getName();
try {
List result = null;
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
result = new ArrayList(classNames.length);
for (int i = 0; i < classNames.length; i++) {
Class clazz = ClassUtils.forName(classNames[i]);
Object strategy = BeanUtils.instantiateClass(clazz);
if (strategy instanceof ApplicationContextAware) {
((ApplicationContextAware) strategy).setApplicationContext(applicationContext);
}
result.add(strategy);
}
}
else {
result = Collections.EMPTY_LIST;
}
return result;
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException("Could not find default strategy class for interface [" + key + "]",
ex);
}
}
/**
* Return the default strategy object for the given strategy interface. <p>Delegates to
* <code>getDefaultStrategies</code>, expecting a single object in the list.
*
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @throws BeansException if initialization failed
* @see #getDefaultStrategies
*/
public Object getDefaultStrategy(Class strategyInterface, ApplicationContext applicationContext)
throws BeanInitializationException {
List result = getDefaultStrategies(strategyInterface, applicationContext);
if (result.size() != 1) {
throw new BeanInitializationException(
"DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
}
return result.get(0);
}
}

View File

@@ -0,0 +1,6 @@
# Default implementation classes for MessageDispatcher's strategy interfaces.
# Used as fallback when no matching beans are found in the application context.
# Not meant to be customized by application developers.
org.springframework.ws.server.EndpointAdapter=org.springframework.ws.server.endpoint.MessageEndpointAdapter,\
org.springframework.ws.server.endpoint.PayloadEndpointAdapter

View File

@@ -0,0 +1,7 @@
# Default implementation classes for MessageDispatcher's strategy interfaces.
# Used as fallback when no matching beans are found in the application context.
# Not meant to be customized by application developers.
org.springframework.ws.server.EndpointAdapter=org.springframework.ws.server.endpoint.MessageEndpointAdapter,\
org.springframework.ws.server.endpoint.PayloadEndpointAdapter
org.springframework.ws.server.EndpointExceptionResolver=org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver

View File

@@ -2,6 +2,6 @@
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.
org.springframework.ws.server.MessageDispatcher=org.springframework.ws.soap.server.SoapMessageDispatcher
org.springframework.ws.transport.WebServiceMessageReceiver=org.springframework.ws.soap.server.SoapMessageDispatcher
org.springframework.ws.WebServiceMessageFactory=org.springframework.ws.soap.saaj.SaajSoapMessageFactory

View File

@@ -20,10 +20,15 @@ import java.util.Collections;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.ws.MockWebServiceMessage;
import org.springframework.ws.NoEndpointFoundException;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.PayloadEndpointAdapter;
import org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping;
import org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver;
public class MessageDispatcherTest extends TestCase {
@@ -94,17 +99,22 @@ public class MessageDispatcherTest extends TestCase {
factoryControl.verify();
}
public void testProcessEndpointExceptionReturnsResponse() throws Exception {
final Object endpoint = new Object();
public void testResolveException() throws Exception {
final Exception ex = new Exception();
EndpointMapping endpointMapping = new EndpointMapping() {
public EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception {
throw ex;
}
};
dispatcher.setEndpointMappings(Collections.singletonList(endpointMapping));
EndpointExceptionResolver resolver = new EndpointExceptionResolver() {
public boolean resolveException(MessageContext givenMessageContext,
Object givenEndpoint,
Exception givenException) {
assertEquals("Invalid message context", messageContext, givenMessageContext);
assertEquals("Invalid endpoint", endpoint, givenEndpoint);
assertNull("Invalid endpoint", givenEndpoint);
assertEquals("Invalid exception", ex, givenException);
givenMessageContext.getResponse();
return true;
@@ -115,7 +125,7 @@ public class MessageDispatcherTest extends TestCase {
factoryControl.expectAndReturn(factoryMock.createWebServiceMessage(), new MockWebServiceMessage());
factoryControl.replay();
dispatcher.processEndpointException(messageContext, endpoint, ex);
dispatcher.dispatch(messageContext);
assertNotNull("processEndpointException sets no response", messageContext.getResponse());
factoryControl.verify();
}
@@ -297,4 +307,37 @@ public class MessageDispatcherTest extends TestCase {
factoryControl.verify();
}
public void testNoEndpointFound() throws Exception {
dispatcher.setEndpointMappings(Collections.EMPTY_LIST);
try {
dispatcher.receive(messageContext);
fail("NoEndpointFoundException expected");
}
catch (NoEndpointFoundException ex) {
// expected
}
}
public void testDetectStrategies() throws Exception {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("mapping", PayloadRootQNameEndpointMapping.class);
applicationContext.registerSingleton("adapter", PayloadEndpointAdapter.class);
applicationContext.registerSingleton("resolver", SimpleSoapExceptionResolver.class);
dispatcher.setApplicationContext(applicationContext);
assertEquals("Invalid amount of mappings detected", 1, dispatcher.getEndpointMappings().size());
assertTrue("Invalid mappings detected",
dispatcher.getEndpointMappings().get(0) instanceof PayloadRootQNameEndpointMapping);
assertEquals("Invalid amount of adapters detected", 1, dispatcher.getEndpointAdapters().size());
assertTrue("Invalid mappings detected",
dispatcher.getEndpointAdapters().get(0) instanceof PayloadEndpointAdapter);
assertEquals("Invalid amount of resolvers detected", 1, dispatcher.getEndpointExceptionResolvers().size());
assertTrue("Invalid mappings detected",
dispatcher.getEndpointExceptionResolvers().get(0) instanceof SimpleSoapExceptionResolver);
}
public void testDefaultStrategies() throws Exception {
StaticApplicationContext applicationContext = new StaticApplicationContext();
dispatcher.setApplicationContext(applicationContext);
}
}

View File

@@ -41,39 +41,17 @@ public class MessageDispatcherServletTest extends XMLTestCase {
assertTrue("Invalid strategy", expectedClass.isAssignableFrom(strategy.getClass()));
}
public void testBeanNameStrategies() throws ServletException {
servlet.setDetectAllEndpointAdapters(false);
servlet.setDetectAllEndpointMappings(false);
servlet.setDetectAllEndpointExceptionResolvers(false);
servlet.setContextClass(BeanNameWebApplicationContext.class);
servlet.init(config);
MessageDispatcher messageDispatcher = servlet.getMessageDispatcher();
assertNotNull("No messageDispatcher created", messageDispatcher);
assertStrategies(PayloadRootQNameEndpointMapping.class, messageDispatcher.getEndpointMappings());
assertStrategies(PayloadEndpointAdapter.class, messageDispatcher.getEndpointAdapters());
assertStrategies(SimpleSoapExceptionResolver.class, messageDispatcher.getEndpointExceptionResolvers());
}
public void testConfiguredMessageDispatcher() throws ServletException {
servlet.setContextClass(MessageDispatcherWebApplicationContext.class);
servlet.init(config);
MessageDispatcher messageDispatcher = servlet.getMessageDispatcher();
assertNotNull("No messageDispatcher created", messageDispatcher);
assertNull("Default strategies loaded", messageDispatcher.getEndpointMappings());
assertNull("Default strategies loaded", messageDispatcher.getEndpointExceptionResolvers());
}
public void testDefaultStrategies() throws ServletException {
servlet.setContextClass(StaticWebApplicationContext.class);
servlet.init(config);
MessageDispatcher messageDispatcher = servlet.getMessageDispatcher();
MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver();
assertNotNull("No messageDispatcher created", messageDispatcher);
}
public void testDetectedStrategies() throws ServletException {
servlet.setContextClass(DetectWebApplicationContext.class);
servlet.init(config);
MessageDispatcher messageDispatcher = servlet.getMessageDispatcher();
MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver();
assertNotNull("No messageDispatcher created", messageDispatcher);
assertStrategies(PayloadRootQNameEndpointMapping.class, messageDispatcher.getEndpointMappings());
assertStrategies(PayloadEndpointAdapter.class, messageDispatcher.getEndpointAdapters());
@@ -105,31 +83,6 @@ public class MessageDispatcherServletTest extends XMLTestCase {
}
}
private static class BeanNameWebApplicationContext extends StaticWebApplicationContext {
public void refresh() throws BeansException, IllegalStateException {
registerSingleton(MessageDispatcherServlet.ENDPOINT_MAPPING_BEAN_NAME,
PayloadRootQNameEndpointMapping.class);
registerSingleton(MessageDispatcherServlet.ENDPOINT_ADAPTER_BEAN_NAME, PayloadEndpointAdapter.class);
registerSingleton(MessageDispatcherServlet.ENDPOINT_EXCEPTION_RESOLVER_BEAN_NAME,
SimpleSoapExceptionResolver.class);
super.refresh();
}
}
private static class MessageDispatcherWebApplicationContext extends StaticWebApplicationContext {
public void refresh() throws BeansException, IllegalStateException {
registerSingleton(MessageDispatcherServlet.MESSAGE_DISPATCHER_BEAN_NAME, MessageDispatcher.class);
registerSingleton(MessageDispatcherServlet.ENDPOINT_MAPPING_BEAN_NAME,
PayloadRootQNameEndpointMapping.class);
registerSingleton(MessageDispatcherServlet.ENDPOINT_ADAPTER_BEAN_NAME, PayloadEndpointAdapter.class);
registerSingleton(MessageDispatcherServlet.ENDPOINT_EXCEPTION_RESOLVER_BEAN_NAME,
SimpleSoapExceptionResolver.class);
super.refresh();
}
}
private static class WsdlDefinitionWebApplicationContext extends StaticWebApplicationContext {
public void refresh() throws BeansException, IllegalStateException {

View File

@@ -0,0 +1,114 @@
/*
* Copyright 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.ws.transport.support;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class DefaultStrategiesHelperTest extends TestCase {
public void testGetDefaultStrategies() throws Exception {
Properties strategies = new Properties();
strategies.put(Strategy.class.getName(),
StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName());
DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies);
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("strategy1", StrategyImpl.class);
applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class);
List result = helper.getDefaultStrategies(Strategy.class, applicationContext);
assertNotNull("No result", result);
assertEquals("Invalid amount of strategies", 2, result.size());
assertTrue("Result not a Strategy implementation", result.get(0) instanceof Strategy);
assertTrue("Result not a Strategy implementation", result.get(1) instanceof Strategy);
assertTrue("Result not a StrategyImpl implementation", result.get(0) instanceof StrategyImpl);
assertTrue("Result not a StrategyImpl implementation", result.get(1) instanceof ContextAwareStrategyImpl);
ContextAwareStrategyImpl impl = (ContextAwareStrategyImpl) result.get(1);
assertNotNull("No application context injected", impl.getApplicationContext());
}
public void testGetDefaultStrategy() throws Exception {
Properties strategies = new Properties();
strategies.put(Strategy.class.getName(), StrategyImpl.class.getName());
DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies);
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("strategy1", StrategyImpl.class);
applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class);
Object result = helper.getDefaultStrategy(Strategy.class, applicationContext);
assertNotNull("No result", result);
assertTrue("Result not a Strategy implementation", result instanceof Strategy);
assertTrue("Result not a StrategyImpl implementation", result instanceof StrategyImpl);
}
public void testGetDefaultStrategyMoreThanOne() throws Exception {
Properties strategies = new Properties();
strategies.put(Strategy.class.getName(),
StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName());
DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies);
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("strategy1", StrategyImpl.class);
applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class);
try {
helper.getDefaultStrategy(Strategy.class, applicationContext);
fail("Expected BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
}
}
public void testResourceConstructor() throws Exception {
Resource resource = new ClassPathResource("strategies.properties", getClass());
new DefaultStrategiesHelper(resource);
}
public interface Strategy {
}
private static class StrategyImpl implements Strategy {
}
private static class ContextAwareStrategyImpl implements Strategy, ApplicationContextAware {
private ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
}

View File

@@ -0,0 +1 @@
org.springframework.ws.transport.support.DefaultStrategiesHelperTest$Strategy=org.springframework.ws.transport.support.DefaultStrategiesHelperTest$StrategyImpl,org.springframework.ws.transport.support.DefaultStrategiesHelperTest$ContextAwareStrategyImpl