Deleted the sandbox in the 1.0 branch

This commit is contained in:
Arjen Poutsma
2007-12-06 20:00:01 +00:00
parent fd5adfa9a6
commit e2e95b19ea
92 changed files with 0 additions and 7199 deletions

View File

@@ -1,55 +0,0 @@
<?xml version="1.0"?>
<project name="spring-ws-airline-sample-saaj-client" default="build"
xmlns:artifact="urn:maven-artifact-ant">
<property name="bin.dir" value="bin"/>
<property name="src.dir" value="src"/>
<target name="init">
<typedef resource="org/apache/maven/artifact/ant/antlib.xml" uri="urn:maven-artifact-ant">
<classpath>
<pathelement location="${basedir}/../maven-artifact-ant-2.0.4-dep.jar"/>
</classpath>
</typedef>
<artifact:remoteRepository id="java.net" url="https://maven-repository.dev.java.net/nonav/repository"
layout="legacy"/>
<artifact:dependencies pathId="compile.classpath">
<remoteRepository refid="java.net"/>
<dependency groupId="javax.xml.soap" artifactId="saaj-api" version="1.3"/>
<dependency groupId="javax.jms" artifactId="jms" version="1.1"/>
<dependency groupId="activemq" artifactId="activemq" version="2.1"/>
<dependency groupId="geronimo-spec" artifactId="geronimo-spec-j2ee-management" version="1.0-rc4"/>
<dependency groupId="concurrent" artifactId="concurrent" version="1.3.4"/>
<dependency groupId="commons-logging" artifactId="commons-logging" version="1.1"/>
</artifact:dependencies>
<artifact:dependencies pathId="runtime.classpath">
<remoteRepository refid="java.net"/>
<dependency groupId="com.sun.xml.messaging.saaj" artifactId="saaj-impl" version="1.3"/>
</artifact:dependencies>
</target>
<target name="build" depends="init">
<mkdir dir="${bin.dir}"/>
<javac srcdir="${src.dir}" destdir="${bin.dir}" debug="true">
<classpath refid="compile.classpath"/>
</javac>
</target>
<target name="clean">
<delete dir="${bin.dir}"/>
</target>
<target name="run" depends="build">
<java classname="org.springframework.ws.samples.airline.client.jms.GetFlights" fork="true" failonerror="true">
<classpath refid="compile.classpath"/>
<classpath refid="runtime.classpath"/>
<classpath location="${bin.dir}"/>
</java>
</target>
</project>

View File

@@ -1,13 +0,0 @@
SPRING WEB SERVICES
This directory contains a client for the Airline Web Service that uses JMS: Java Message Service. The client can be run
from the provided ant file, by calling "ant run".
NOTE that the client uses ActiveMQ 2.1, and needs to be changed for other versions of ActiveMQ, or other JMS providers.
Also note that ActiveMQ needs to be running before this sample is started.
SAJA Client Sample table of contents
---------------------------------------------------
* src - The source files for the client
* build.xml - Ant build file with a 'build' and a 'run' target

View File

@@ -1,195 +0,0 @@
/*
* Copyright 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.ws.samples.airline.client.jms;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.codehaus.activemq.ActiveMQConnection;
import org.codehaus.activemq.ActiveMQConnectionFactory;
/**
* @author Arjen Poutsma
*/
public class GetFlights implements MessageListener {
public static final String NAMESPACE_URI = "http://www.springframework.org/spring-ws/samples/airline/schemas";
public static final String PREFIX = "airline";
private static final String CORRELATION_ID = "correlationId";
private static final String REQUEST_TOPIC = "org.springframework.ws.samples.airline.RequestTopic";
private static final String RESPONSE_TOPIC = "org.springframework.ws.samples.airline.ResponseTopic";
private TopicConnection connection;
private MessageFactory messageFactory;
private Topic responseTopic;
private TopicSession session;
private TransformerFactory transfomerFactory;
public GetFlights(TopicConnectionFactory connectionFactory) throws SOAPException, JMSException {
messageFactory = MessageFactory.newInstance();
transfomerFactory = TransformerFactory.newInstance();
connection = connectionFactory.createTopicConnection();
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
responseTopic = session.createTopic(RESPONSE_TOPIC);
TopicSubscriber subscriber = session.createSubscriber(responseTopic);
subscriber.setMessageListener(this);
connection.start();
}
public void onMessage(Message message) {
try {
System.out.println("Received message");
BytesMessage bytesMessage = (BytesMessage) message;
byte[] buf = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(buf);
ByteArrayInputStream is = new ByteArrayInputStream(buf);
SOAPMessage saajMessage = messageFactory.createMessage(new MimeHeaders(), is);
writeGetFlightsResponse(saajMessage);
System.exit(0);
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
public void close() {
if (session != null) {
try {
session.close();
}
catch (JMSException ex) {
ex.printStackTrace(System.err);
}
}
if (connection != null) {
try {
connection.close();
}
catch (JMSException ex) {
ex.printStackTrace(System.err);
}
}
}
private SOAPMessage createGetFlightsRequest() throws SOAPException {
SOAPMessage message = messageFactory.createMessage();
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
Name getFlightsRequestName = envelope.createName("GetFlightsRequest", PREFIX, NAMESPACE_URI);
SOAPBodyElement getFlightsRequestElement = message.getSOAPBody().addBodyElement(getFlightsRequestName);
Name fromName = envelope.createName("from", PREFIX, NAMESPACE_URI);
SOAPElement fromElement = getFlightsRequestElement.addChildElement(fromName);
fromElement.setValue("AMS");
Name toName = envelope.createName("to", PREFIX, NAMESPACE_URI);
SOAPElement toElement = getFlightsRequestElement.addChildElement(toName);
toElement.setValue("VCE");
Name departureDateName = envelope.createName("departureDate", PREFIX, NAMESPACE_URI);
SOAPElement departureDateElement = getFlightsRequestElement.addChildElement(departureDateName);
departureDateElement.setValue("2006-01-31");
return message;
}
public void getFlights() throws SOAPException, IOException, TransformerException, JMSException {
SOAPMessage request = createGetFlightsRequest();
Topic requestTopic = session.createTopic(REQUEST_TOPIC);
TopicPublisher publisher = session.createPublisher(requestTopic);
BytesMessage message = session.createBytesMessage();
message.setJMSCorrelationID(CORRELATION_ID);
message.setJMSReplyTo(responseTopic);
ByteArrayOutputStream os = new ByteArrayOutputStream();
request.writeTo(os);
os.flush();
message.writeBytes(os.toByteArray());
publisher.publish(message);
System.out.println("Written GetFlights request to " + requestTopic);
}
private void writeGetFlightsResponse(SOAPMessage message) throws SOAPException, TransformerException {
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
Name getFlightsResponseName = envelope.createName("GetFlightsResponse", PREFIX, NAMESPACE_URI);
SOAPBodyElement getFlightsResponseElement =
(SOAPBodyElement) message.getSOAPBody().getChildElements(getFlightsResponseName).next();
Name flightName = envelope.createName("flight", PREFIX, NAMESPACE_URI);
Iterator iterator = getFlightsResponseElement.getChildElements(flightName);
Transformer transformer = transfomerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
int count = 1;
while (iterator.hasNext()) {
System.out.println("Flight " + count);
System.out.println("--------");
SOAPElement flightElement = (SOAPElement) iterator.next();
DOMSource source = new DOMSource(flightElement);
transformer.transform(source, new StreamResult(System.out));
}
}
public static void main(String[] args) throws Exception {
String url = ActiveMQConnection.DEFAULT_URL;
if (args.length > 0) {
url = args[0];
}
TopicConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
GetFlights getFlights = null;
try {
getFlights = new GetFlights(connectionFactory);
getFlights.getFlights();
while (true) {
// keep running until we receive a response message in onMessage
}
}
finally {
if (getFlights != null) {
getFlights.close();
}
}
}
}

View File

@@ -1,152 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>spring-ws</artifactId>
<groupId>org.springframework.ws</groupId>
<version>1.0.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-ws-sandbox</artifactId>
<packaging>jar</packaging>
<name>Spring WS Sandbox</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<stylesheetfile>${basedir}/../src/main/javadoc/javadoc.css</stylesheetfile>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<!-- Spring-WS dependencies -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-remoting</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jmx</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- JEE dependencies -->
<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>saaj-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb</artifactId>
<version>2.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.1</version>
<exclusions>
<exclusion>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Other dependencies -->
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>4.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.1.1.0</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.0.1</version>
<scope>test</scope>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>easymock</groupId>
<artifactId>easymock</artifactId>
<version>1.2_Java1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,268 +0,0 @@
/*
* 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.oxm.support;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageEOFException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.util.Assert;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
/**
* Spring JMS {@link MessageConverter} that uses a {@link Marshaller} and {@link Unmarshaller}. Marshals an object to a
* {@link BytesMessage}, or to a {@link TextMessage} if the {@link #setMarshalToTextMessage(boolean)
* marshalToTextMessage} is <code>true</code>. Unmarshals from a {@link TextMessage} or {@link BytesMessage} to an
* object.
*
* @author Arjen Poutsma
*/
public class MarshallingMessageConverter implements MessageConverter, InitializingBean {
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private boolean marshalToTextMessage = false;
/**
* Constructs a new <code>MarshallingMessageConverter</code> with no {@link Marshaller} set. The marshaller must be
* set after construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingMessageConverter() {
}
/**
* Constructs a new <code>MarshallingMessageConverter</code> with the given {@link Marshaller} set. If the given
* {@link Marshaller} also implements the {@link Unmarshaller} interface, it is used for both marshalling and
* unmarshalling. Otherwise, an exception is thrown.
* <p/>
* Note that all {@link Marshaller} implementations in Spring-WS also implement the {@link Unmarshaller} interface,
* so that you can safely use this constructor.
*
* @param marshaller object used as marshaller and unmarshaller
* @throws IllegalArgumentException when <code>marshaller</code> does not implement the {@link Unmarshaller}
* interface
*/
public MarshallingMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
if (!(marshaller instanceof Unmarshaller)) {
throw new IllegalArgumentException("Marshaller [" + marshaller + "] does not implement the Unmarshaller " +
"interface. Please set an Unmarshaller explicitely by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor.");
}
else {
this.marshaller = marshaller;
this.unmarshaller = (Unmarshaller) marshaller;
}
}
/**
* Creates a new <code>MarshallingMessageConverter</code> with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
this.marshaller = marshaller;
this.unmarshaller = unmarshaller;
}
/**
* Indicates whether {@link #toMessage(Object,Session)} should marshal to a {@link TextMessage} or a {@link
* BytesMessage}. The default is <code>false</code>, i.e. this converter marshals to a {@link BytesMessage}.
*/
public void setMarshalToTextMessage(boolean marshalToTextMessage) {
this.marshalToTextMessage = marshalToTextMessage;
}
/** Sets the {@link Marshaller} to be used by this message converter. */
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Sets the {@link Marshaller} to be used by this message converter. */
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(marshaller, "Property 'marshaller' is required");
Assert.notNull(unmarshaller, "Property 'unmarshaller' is required");
}
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
Result result;
Message message;
if (marshalToTextMessage) {
message = session.createTextMessage();
result = new StringResult();
}
else {
message = session.createBytesMessage();
result = new StreamResult(new BytesMessageOutputStream((BytesMessage) message));
}
try {
marshaller.marshal(object, result);
if (marshalToTextMessage) {
((TextMessage) message).setText(result.toString());
}
return message;
}
catch (MessageConversionException ex) {
handleMessageConversionException(ex);
throw ex;
}
catch (IOException ex) {
throw new MessageConversionException("Could not marshal message [" + message + "]", ex);
}
}
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
Source source;
if (message instanceof TextMessage) {
source = new StringSource(((TextMessage) message).getText());
}
else if (message instanceof BytesMessage) {
source = new StreamSource(new BytesMessageInputStream((BytesMessage) message));
}
else {
throw new MessageConversionException(
"MarshallingMessageConverter only supports TextMessages and BytesMessages");
}
try {
return unmarshaller.unmarshal(source);
}
catch (MessageConversionException ex) {
handleMessageConversionException(ex);
throw ex;
}
catch (IOException ex) {
throw new MessageConversionException("Could not unmarshal message [" + message + "]", ex);
}
}
private void handleMessageConversionException(MessageConversionException ex) throws JMSException {
if (ex.getCause() instanceof JMSException) {
throw (JMSException) ex.getCause();
}
else {
throw ex;
}
}
/** Input stream that wraps a {@link BytesMessage}. */
private static class BytesMessageInputStream extends InputStream {
private BytesMessage message;
BytesMessageInputStream(BytesMessage message) {
this.message = message;
}
public int read(byte b[]) throws IOException {
try {
return message.readBytes(b);
}
catch (JMSException ex) {
throw new MessageConversionException("Could not read byte array", ex);
}
}
public int read(byte b[], int off, int len) throws IOException {
if (off == 0) {
try {
return message.readBytes(b, len);
}
catch (JMSException ex) {
throw new MessageConversionException("Could not read byte array", ex);
}
}
else {
return super.read(b, off, len);
}
}
public int read() throws IOException {
try {
return message.readByte();
}
catch (MessageEOFException ex) {
return -1;
}
catch (JMSException ex) {
throw new MessageConversionException("Could not read byte", ex);
}
}
}
/** Output stream that wraps a {@link BytesMessage}. */
private static class BytesMessageOutputStream extends OutputStream {
private BytesMessage message;
BytesMessageOutputStream(BytesMessage message) {
this.message = message;
}
public void write(byte b[]) throws IOException {
try {
message.writeBytes(b);
}
catch (JMSException ex) {
throw new MessageConversionException("Could not write byte array", ex);
}
}
public void write(byte b[], int off, int len) throws IOException {
try {
message.writeBytes(b, off, len);
}
catch (JMSException ex) {
throw new MessageConversionException("Could not write byte array", ex);
}
}
public void write(int b) throws IOException {
try {
message.writeByte((byte) b);
}
catch (JMSException ex) {
throw new MessageConversionException("Could not write byte", ex);
}
}
}
}

View File

@@ -1,130 +0,0 @@
/*
* 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.oxm.support;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import org.springframework.beans.BeansException;
import org.springframework.oxm.Marshaller;
import org.springframework.util.Assert;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Spring-MVC {@link View} that allows for response context to be rendered as the result of marshalling by a {@link
* Marshaller}.
* <p/>
* The Object to be marshalled is supplied as a parameter in the model and then {@link #locateToBeMarshalled(Map)
* detected} during response rendering. Users can either specify a specific entry in the model via the {@link
* #setModelKey(String) sourceKey} property or have Spring locate the Source object.
*
* @author Arjen Poutsma
*/
public class MarshallingView extends AbstractUrlBasedView {
/** Default content type. Overridable as bean property. */
public static final String DEFAULT_CONTENT_TYPE = "text/xml";
private Marshaller marshaller;
private String modelKey;
/**
* Constructs a new <code>MarshallingView</code> with no {@link Marshaller} set. The marshaller must be set after
* construction by invoking {@link #setMarshaller(Marshaller)}.
*/
public MarshallingView() {
setContentType(DEFAULT_CONTENT_TYPE);
}
/** Constructs a new <code>MarshallingView</code> with the given {@link Marshaller} set. */
public MarshallingView(Marshaller marshaller) {
Assert.notNull(marshaller, "'marshaller' must not be null");
setContentType(DEFAULT_CONTENT_TYPE);
this.marshaller = marshaller;
}
/** Sets the {@link Marshaller} to be used by this view. */
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/**
* Set the name of the model key that represents the object to be marshalled. If not specified, the model map will
* be searched for a supported value type.
*
* @see Marshaller#supports(Class)
*/
public void setModelKey(String modelKey) {
this.modelKey = modelKey;
}
protected void initApplicationContext() throws BeansException {
Assert.notNull(marshaller, "Property 'marshaller' is required");
}
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object toBeMarshalled = locateToBeMarshalled(model);
if (toBeMarshalled == null) {
throw new IllegalArgumentException("Unable to locate object to be marshalled in model: " + model);
}
marshaller.marshal(toBeMarshalled, createResult(response));
}
/**
* Create the TrAX {@link Result} used to marshal to.
* <p/>
* The default implementation creates a {@link StreamResult} wrapping the supplied HttpServletResponse's {@link
* HttpServletResponse#getOutputStream() OutputStream}.
*
* @param response current HTTP response
* @return the Result to marshal to
* @throws Exception if the Result cannot be built
*/
protected Result createResult(HttpServletResponse response) throws Exception {
return new StreamResult(response.getOutputStream());
}
/**
* Locates the object to be marshalled. The default implementation first attempts to look under the configured
* {@link #setModelKey(String) model key}, if any, before attempting to locate an object of {@link
* Marshaller#supports(Class) supported type}.
*
* @param model the model Map
* @return the Object to be marshalled (or <code>null</code> if none found)
* @throws Exception if an error occured during locating the source
* @see #setModelKey(String)
*/
protected Object locateToBeMarshalled(Map model) {
if (this.modelKey != null) {
return model.get(this.modelKey);
}
for (Iterator iterator = model.values().iterator(); iterator.hasNext();) {
Object o = iterator.next();
if (this.marshaller.supports(o.getClass())) {
return o;
}
}
return null;
}
}

View File

@@ -1,7 +0,0 @@
<html>
<body>
Provides generic support classes for using Spring's O/X Mapping integration within various scenario's. Includes the
MarshallingView for use withing Spring Web MVC, the MarshallingMessageConverter for use within Spring's JMS support.
</body>
</html>

View File

@@ -1,81 +0,0 @@
/*
* 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.jaxws;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.EndpointAdapter;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.xml.transform.TransformerObjectSupport;
/**
* Adapter to use a JAX-WS {@link Provider} as the endpoint for a <code>EndpointInvocationChain</code>. Supports both
* message and payload providers.
*
* @author Arjen Poutsma
*/
public class JaxWsProviderEndpointAdapter extends TransformerObjectSupport implements EndpointAdapter {
public boolean supports(Object endpoint) {
return endpoint.getClass().getAnnotation(WebServiceProvider.class) != null && endpoint instanceof Provider;
}
public void invoke(MessageContext messageContext, Object endpoint) throws Exception {
ServiceMode serviceMode = endpoint.getClass().getAnnotation(ServiceMode.class);
if (serviceMode == null || Service.Mode.PAYLOAD.equals(serviceMode.value())) {
invokeSourceProvider(messageContext, (Provider<Source>) endpoint);
}
else if (Service.Mode.MESSAGE.equals(serviceMode.value())) {
Provider<SOAPMessage> provider = (Provider<SOAPMessage>) endpoint;
invokeMessageProvider(messageContext, provider);
}
}
private void invokeSourceProvider(MessageContext messageContext, Provider<Source> provider)
throws TransformerException {
Source requestSource = messageContext.getRequest().getPayloadSource();
Source responseSource = provider.invoke(requestSource);
if (responseSource != null) {
WebServiceMessage response = messageContext.getResponse();
Transformer transformer = createTransformer();
transformer.transform(responseSource, response.getPayloadResult());
}
}
private void invokeMessageProvider(MessageContext messageContext, Provider<SOAPMessage> provider) {
if (!(messageContext.getRequest() instanceof SaajSoapMessage)) {
throw new IllegalArgumentException("JaxWsProviderEndpointAdapter requires a SaajSoapMessage. " +
"Use a SaajSoapMessageFactory to create the SOAP messages.");
}
SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest();
SOAPMessage saajRequest = request.getSaajMessage();
SOAPMessage saajResponse = provider.invoke(saajRequest);
if (saajResponse != null) {
SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse();
response.setSaajMessage(saajResponse);
}
}
}

View File

@@ -1,184 +0,0 @@
/*
* 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.soap.addressing;
import java.util.Iterator;
import javax.xml.transform.TransformerException;
import org.springframework.core.JdkVersion;
import org.springframework.util.Assert;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.server.EndpointInvocationChain;
import org.springframework.ws.server.EndpointMapping;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.addressing.messageid.MessageIdStrategy;
import org.springframework.ws.soap.addressing.messageid.UidMessageIdStrategy;
import org.springframework.ws.soap.addressing.messageid.UuidMessageIdStrategy;
import org.springframework.ws.soap.server.SoapEndpointInvocationChain;
import org.springframework.ws.soap.server.SoapEndpointMapping;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.xml.transform.TransformerObjectSupport;
/**
* Abstract base class for {@link EndpointMapping} implementations that implement WS-Addressing.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public abstract class AbstractWsAddressingMapping extends TransformerObjectSupport implements SoapEndpointMapping {
private String[] actorsOrRoles;
private boolean isUltimateReceiver = true;
private MessageIdStrategy messageIdStrategy;
private WebServiceMessageSender[] messageSenders;
private WsAddressingVersion[] versions;
private EndpointInterceptor[] preInterceptors;
private EndpointInterceptor[] postInterceptors;
/** Protected constructor. Initializes the default settings. */
protected AbstractWsAddressingMapping() {
this.versions = new WsAddressingVersion[]{new WsAddressing200408(), new WsAddressing200605()};
if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) {
messageIdStrategy = new UuidMessageIdStrategy();
}
else {
messageIdStrategy = new UidMessageIdStrategy();
}
}
public final void setActorOrRole(String actorOrRole) {
Assert.notNull(actorOrRole, "actorOrRole must not be null");
actorsOrRoles = new String[]{actorOrRole};
}
public final void setActorsOrRoles(String[] actorsOrRoles) {
Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty");
this.actorsOrRoles = actorsOrRoles;
}
public final void setUltimateReceiver(boolean ultimateReceiver) {
this.isUltimateReceiver = ultimateReceiver;
}
/**
* Set additional interceptors to be applied before the implicit WS-Addressing interceptor, e.g.
* <code>XwsSecurityInterceptor</code>.
*/
public final void setPreInterceptors(EndpointInterceptor[] preInterceptors) {
this.preInterceptors = preInterceptors;
}
/**
* Set additional interceptors to be applied after the implicit WS-Addressing interceptor, e.g.
* <code>PayloadLoggingInterceptor</code>.
*/
public final void setPostInterceptors(EndpointInterceptor[] postInterceptors) {
this.postInterceptors = postInterceptors;
}
/**
* Sets the message id provider used for creating WS-Addressing MessageIds.
* <p/>
* By default, the {@link UuidMessageIdStrategy} is used on Java 5 and higher, and the {@link UidMessageIdStrategy}
* on Java 1.4 and lower.
*/
public final void setMessageIdProvider(MessageIdStrategy messageIdStrategy) {
this.messageIdStrategy = messageIdStrategy;
}
public final void setMessageSenders(WebServiceMessageSender[] messageSenders) {
this.messageSenders = messageSenders;
}
/**
* Sets the WS-Addressing versions to be supported by this mapping.
* <p/>
* By default, this array is set to support {@link WsAddressing200408 the August 2004} and the {@link
* WsAddressing200605 May 2006} versions of the specification.
*/
public final void setVersions(WsAddressingVersion[] versions) {
this.versions = versions;
}
public final EndpointInvocationChain getEndpoint(MessageContext messageContext) throws TransformerException {
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(),
"WsAddressingMapping requires a SoapMessage request");
SoapMessage request = (SoapMessage) messageContext.getRequest();
for (int i = 0; i < versions.length; i++) {
if (supports(versions[i], request)) {
MessageAddressingProperties requestMap = versions[i].getMessageAddressingProperties(request);
if (requestMap == null) {
return null;
}
Object endpoint = getEndpointInternal(requestMap);
if (endpoint == null) {
return null;
}
return new SoapEndpointInvocationChain(endpoint, getAllEndpointInterceptors(versions[i]), actorsOrRoles,
isUltimateReceiver);
}
}
return null;
}
private boolean supports(WsAddressingVersion version, SoapMessage request) {
SoapHeader header = request.getSoapHeader();
if (header != null) {
for (Iterator iterator = header.examineAllHeaderElements(); iterator.hasNext();) {
SoapHeaderElement headerElement = (SoapHeaderElement) iterator.next();
if (version.understands(headerElement)) {
return true;
}
}
}
return false;
}
private EndpointInterceptor[] getAllEndpointInterceptors(WsAddressingVersion version) {
if (preInterceptors == null) {
preInterceptors = new EndpointInterceptor[0];
}
if (postInterceptors == null) {
postInterceptors = new EndpointInterceptor[0];
}
EndpointInterceptor[] interceptors =
new EndpointInterceptor[preInterceptors.length + postInterceptors.length + 1];
System.arraycopy(preInterceptors, 0, interceptors, 0, preInterceptors.length);
interceptors[preInterceptors.length] = new WsAddressingInterceptor(version, messageIdStrategy, messageSenders);
System.arraycopy(postInterceptors, 0, interceptors, preInterceptors.length + 1, postInterceptors.length);
return interceptors;
}
/**
* Lookup an endpoint for the given {@link MessageAddressingProperties}, returning <code>null</code> if no specific
* one is found. This template method is called by {@link #getEndpoint(MessageContext)}.
*
* @param map the message addressing properties
* @return the endpoint, or <code>null</code>
*/
protected abstract Object getEndpointInternal(MessageAddressingProperties map);
}

View File

@@ -1,324 +0,0 @@
/*
* 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.soap.addressing;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import org.springframework.util.StringUtils;
import org.springframework.ws.soap.SoapFault;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.soap11.Soap11Body;
import org.springframework.ws.soap.soap12.Soap12Body;
import org.springframework.ws.soap.soap12.Soap12Fault;
import org.springframework.xml.namespace.QNameUtils;
import org.springframework.xml.transform.TransformerObjectSupport;
import org.springframework.xml.xpath.XPathExpression;
import org.springframework.xml.xpath.XPathExpressionFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Abstract base class for {@link WsAddressingVersion} implementations. Uses {@link XPathExpression}s to retrieve
* addressing information.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public abstract class AbstractWsAddressingVersion extends TransformerObjectSupport implements WsAddressingVersion {
private final XPathExpression toExpression;
private final XPathExpression actionExpression;
private final XPathExpression messageIdExpression;
private final XPathExpression fromExpression;
private final XPathExpression replyToExpression;
private final XPathExpression faultToExpression;
private final XPathExpression addressExpression;
private final XPathExpression referencePropertiesExpression;
private final XPathExpression referenceParametersExpression;
protected AbstractWsAddressingVersion() {
Properties namespaces = new Properties();
namespaces.setProperty(getNamespacePrefix(), getNamespaceUri());
toExpression = createNormalizedExpression(getToName(), namespaces);
actionExpression = createNormalizedExpression(getActionName(), namespaces);
messageIdExpression = createNormalizedExpression(getMessageIdName(), namespaces);
fromExpression = createExpression(getFromName(), namespaces);
replyToExpression = createExpression(getReplyToName(), namespaces);
faultToExpression = createExpression(getFaultToName(), namespaces);
addressExpression = createNormalizedExpression(getAddressName(), namespaces);
if (getReferencePropertiesName() != null) {
referencePropertiesExpression = createChildrenExpression(getReferencePropertiesName(), namespaces);
}
else {
referencePropertiesExpression = null;
}
if (getReferenceParametersName() != null) {
referenceParametersExpression = createChildrenExpression(getReferenceParametersName(), namespaces);
}
else {
referenceParametersExpression = null;
}
}
private XPathExpression createExpression(QName name, Properties namespaces) {
String expression = name.getPrefix() + ":" + name.getLocalPart();
return XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
private XPathExpression createNormalizedExpression(QName name, Properties namespaces) {
String expression = "normalize-space(" + name.getPrefix() + ":" + name.getLocalPart() + ")";
return XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
private XPathExpression createChildrenExpression(QName name, Properties namespaces) {
String expression = name.getPrefix() + ":" + name.getLocalPart() + "/*";
return XPathExpressionFactory.createXPathExpression(expression, namespaces);
}
public MessageAddressingProperties getMessageAddressingProperties(SoapMessage message) {
Element headerElement = getSoapHeaderElement(message);
String to = toExpression.evaluateAsString(headerElement);
EndpointReference from = getEndpointReference(fromExpression.evaluateAsNode(headerElement));
EndpointReference replyTo = getEndpointReference(replyToExpression.evaluateAsNode(headerElement));
EndpointReference faultTo = getEndpointReference(faultToExpression.evaluateAsNode(headerElement));
String action = actionExpression.evaluateAsString(headerElement);
String messageId = messageIdExpression.evaluateAsString(headerElement);
return new MessageAddressingProperties(to, from, replyTo, faultTo, action, messageId);
}
private Element getSoapHeaderElement(SoapMessage message) {
SoapHeader header = message.getSoapHeader();
if (header.getSource() instanceof DOMSource) {
DOMSource domSource = (DOMSource) header.getSource();
if (domSource.getNode() != null && domSource.getNode().getNodeType() == Node.ELEMENT_NODE) {
return (Element) domSource.getNode();
}
}
try {
DOMResult domResult = new DOMResult();
transform(header.getSource(), domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
catch (TransformerException ex) {
throw new WsAddressingException("Could not transform SoapHeader to Document", ex);
}
}
/** Given a ReplyTo, FaultTo, or From node, returns an endpoint reference. */
private EndpointReference getEndpointReference(Node node) {
if (node == null) {
return null;
}
String address = addressExpression.evaluateAsString(node);
if (!StringUtils.hasLength(address)) {
return null;
}
List referenceProperties = referencePropertiesExpression != null ?
referencePropertiesExpression.evaluateAsNodeList(node) : Collections.EMPTY_LIST;
List referenceParameters = referenceParametersExpression != null ?
referenceParametersExpression.evaluateAsNodeList(node) : Collections.EMPTY_LIST;
return new EndpointReference(address, referenceProperties, referenceParameters);
}
public final boolean understands(SoapHeaderElement headerElement) {
return getNamespaceUri().equals(headerElement.getName().getNamespaceURI());
}
public final void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) {
SoapHeader header = message.getSoapHeader();
SoapHeaderElement messageId = header.addHeaderElement(getMessageIdName());
messageId.setText(map.getMessageId());
SoapHeaderElement relatesTo = header.addHeaderElement(getRelatesToName());
relatesTo.setText(map.getRelatesTo());
SoapHeaderElement to = header.addHeaderElement(getToName());
to.setText(map.getTo());
to.setMustUnderstand(true);
try {
Transformer transformer = createTransformer();
for (Iterator iterator = map.getReferenceParameters().iterator(); iterator.hasNext();) {
Node node = (Node) iterator.next();
DOMSource source = new DOMSource(node);
transformer.transform(source, header.getResult());
}
for (Iterator iterator = map.getReferenceProperties().iterator(); iterator.hasNext();) {
Node node = (Node) iterator.next();
DOMSource source = new DOMSource(node);
transformer.transform(source, header.getResult());
}
}
catch (TransformerException ex) {
throw new WsAddressingException("Could not add reference properties/parameters to message", ex);
}
}
public final SoapFault addInvalidAddressingHeaderFault(SoapMessage message) {
return addAddressingFault(message, getInvalidAddressingHeaderFaultSubcode(),
getInvalidAddressingHeaderFaultReason());
}
public final SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message) {
return addAddressingFault(message, getMessageAddressingHeaderRequiredFaultSubcode(),
getMessageAddressingHeaderRequiredFaultReason());
}
private SoapFault addAddressingFault(SoapMessage message, QName subcode, String reason) {
if (message.getSoapBody() instanceof Soap11Body) {
Soap11Body soapBody = (Soap11Body) message.getSoapBody();
return soapBody.addFault(subcode, reason, Locale.ENGLISH);
}
else if (message.getSoapBody() instanceof Soap12Body) {
Soap12Body soapBody = (Soap12Body) message.getSoapBody();
Soap12Fault soapFault = (Soap12Fault) soapBody.addClientOrSenderFault(reason, Locale.ENGLISH);
soapFault.addFaultSubcode(subcode);
return soapFault;
}
return null;
}
/*
* Address URIs
*/
public final boolean hasAnonymousAddress(EndpointReference epr) {
String anonymous = getAnonymousUri();
return anonymous != null && anonymous.equals(epr.getAddress());
}
public final boolean hasNoneAddress(EndpointReference epr) {
String none = getNoneUri();
return none != null && none.equals(epr.getAddress());
}
/** Returns the prefix associated with the WS-Addressing namespace handled by this specification. */
protected String getNamespacePrefix() {
return "wsa";
}
/** Returns the WS-Addressing namespace handled by this specification. */
protected abstract String getNamespaceUri();
/*
* Message addressing properties
*/
/** Returns the qualified name of the <code>To</code> addressing header. */
protected QName getToName() {
return QNameUtils.createQName(getNamespaceUri(), "To", getNamespacePrefix());
}
/** Returns the qualified name of the <code>From</code> addressing header. */
protected QName getFromName() {
return QNameUtils.createQName(getNamespaceUri(), "From", getNamespacePrefix());
}
/** Returns the qualified name of the <code>ReplyTo</code> addressing header. */
protected QName getReplyToName() {
return QNameUtils.createQName(getNamespaceUri(), "ReplyTo", getNamespacePrefix());
}
/** Returns the qualified name of the <code>FaultTo</code> addressing header. */
protected QName getFaultToName() {
return QNameUtils.createQName(getNamespaceUri(), "FaultTo", getNamespacePrefix());
}
/** Returns the qualified name of the <code>Action</code> addressing header. */
protected QName getActionName() {
return QNameUtils.createQName(getNamespaceUri(), "Action", getNamespacePrefix());
}
/** Returns the qualified name of the <code>MessageID</code> addressing header. */
protected QName getMessageIdName() {
return QNameUtils.createQName(getNamespaceUri(), "MessageID", getNamespacePrefix());
}
/** Returns the qualified name of the <code>RelatesTo</code> addressing header. */
protected QName getRelatesToName() {
return QNameUtils.createQName(getNamespaceUri(), "RelatesTo", getNamespacePrefix());
}
/**
* Returns the qualified name of the <code>ReferenceProperties</code> in the endpoint reference. Returns
* <code>null</code> when reference properties are not supported by this version of the spec.
*/
protected QName getReferencePropertiesName() {
return QNameUtils.createQName(getNamespaceUri(), "ReferenceProperties", getNamespacePrefix());
}
/**
* Returns the qualified name of the <code>ReferenceParameters</code> in the endpoint reference. Returns
* <code>null</code> when reference parameters are not supported by this version of the spec.
*/
protected QName getReferenceParametersName() {
return QNameUtils.createQName(getNamespaceUri(), "ReferenceParameters", getNamespacePrefix());
}
/*
* Endpoint Reference
*/
/** The qualified name of the <code>Address</code> in <code>EndpointReference</code>. */
protected QName getAddressName() {
return QNameUtils.createQName(getNamespaceUri(), "Address", getNamespacePrefix());
}
/*
* Address URIs
*/
/** Returns the anonymous URI. */
protected abstract String getAnonymousUri();
/** Returns the none URI, or <code>null</code> if the spec does not define it. */
protected abstract String getNoneUri();
/*
* Faults
*/
/** Returns the qualified name of the fault subcode that indicates that a header is missing. */
protected abstract QName getMessageAddressingHeaderRequiredFaultSubcode();
/** Returns the reason of the fault that indicates that a header is missing. */
protected abstract String getMessageAddressingHeaderRequiredFaultReason();
/** Returns the qualified name of the fault subcode that indicates that a header is invalid. */
protected abstract QName getInvalidAddressingHeaderFaultSubcode();
/** Returns the reason of the fault that indicates that a header is invalid. */
protected abstract String getInvalidAddressingHeaderFaultReason();
}

View File

@@ -1,105 +0,0 @@
/*
* 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.soap.addressing;
import java.util.Collections;
import java.util.List;
import org.springframework.util.Assert;
import org.w3c.dom.Node;
/**
* Represents a set of Message Addressing Properties, as defined in the WS-Addressing specification.
* <p/>
* In earlier versions of the spec, these properties were called Message Information Headers.
*
* @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/ws-addr-core/#eprs">Endpoint References</a>
* @since 1.1.0
*/
public final class EndpointReference {
private final String address;
private final List referenceProperties;
private final List referenceParameters;
/**
* Creates a new instance of the {@link EndpointReference} class with the given address. The reference parameters
* and properties are empty.
*
* @param address the endpoint address
*/
public EndpointReference(String address) {
Assert.notNull(address, "address must not be null");
this.address = address;
this.referenceParameters = Collections.EMPTY_LIST;
this.referenceProperties = Collections.EMPTY_LIST;
}
/**
* Creates a new instance of the {@link EndpointReference} class with the given address, reference properties, and
* reference paramters.
*
* @param address the endpoint address
* @param referenceProperties the reference properties, as a list of {@link Node}
* @param referenceProperties the reference parameters, as a list of {@link Node}
*/
public EndpointReference(String address, List referenceProperties, List referenceParameters) {
Assert.notNull(address, "address must not be null");
Assert.notNull(referenceProperties, "referenceProperties must not be null");
Assert.notNull(referenceParameters, "referenceParameters must not be null");
this.address = address;
this.referenceProperties = referenceProperties;
this.referenceParameters = referenceParameters;
}
/** Returns the address of the endpoint. */
public String getAddress() {
return address;
}
/** Returns the reference properties of the endpoint, as a list of {@link Node} objects. */
public List getReferenceProperties() {
return referenceProperties;
}
/** Returns the reference parameters of the endpoint, as a list of {@link Node} objects. */
public List getReferenceParameters() {
return referenceParameters;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof EndpointReference) {
EndpointReference other = (EndpointReference) o;
return address.equals(other.address);
}
return false;
}
public int hashCode() {
return address.hashCode();
}
public String toString() {
return "EndpointReference[" + address + ']';
}
}

View File

@@ -1,163 +0,0 @@
/*
* 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.soap.addressing;
import java.util.Collections;
import java.util.List;
import org.springframework.util.StringUtils;
/**
* Represents a set of Message Addressing Properties, as defined in the WS-Addressing specification.
* <p/>
* In earlier versions of the spec, these properties were called Message Information Headers.
*
* @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/ws-addr-core/#msgaddrprops">Message Addressing Properties</a>
* @since 1.1.0
*/
public final class MessageAddressingProperties {
private final String to;
private final EndpointReference from;
private final EndpointReference replyTo;
private final EndpointReference faultTo;
private final String action;
private final String messageId;
private final String relatesTo;
private final List referenceProperties;
private final List referenceParameters;
/**
* Constructs a new {@link MessageAddressingProperties} with the given parameters.
*
* @param to the value of the destination property
* @param from the value of the source endpoint property
* @param replyTo the value of the reply endpoint property
* @param faultTo the value of the fault endpoint property
* @param action the value of the action property
* @param messageId the value of the message id property
*/
public MessageAddressingProperties(String to,
EndpointReference from,
EndpointReference replyTo,
EndpointReference faultTo,
String action,
String messageId) {
this.to = to;
this.from = from;
this.replyTo = replyTo;
this.faultTo = faultTo;
this.action = action;
this.messageId = messageId;
this.relatesTo = null;
this.referenceProperties = Collections.EMPTY_LIST;
this.referenceParameters = Collections.EMPTY_LIST;
}
private MessageAddressingProperties(EndpointReference epr, String action, String messageId, String relatesTo) {
this.to = epr.getAddress();
this.action = action;
this.messageId = messageId;
this.relatesTo = relatesTo;
this.referenceParameters = epr.getReferenceParameters();
this.referenceProperties = epr.getReferenceProperties();
this.from = null;
this.replyTo = null;
this.faultTo = null;
}
/** Returns the value of the destination property. */
public String getTo() {
return to;
}
/** Returns the value of the source endpoint property. */
public EndpointReference getFrom() {
return from;
}
/** Returns the value of the reply endpoint property. */
public EndpointReference getReplyTo() {
return replyTo;
}
/** Returns the value of the fault endpoint property. Defaults to {@link #getReplyTo()} if no fault endpoint is set. */
public EndpointReference getFaultTo() {
return faultTo != null ? faultTo : getReplyTo();
}
/** Returns the value of the action property. */
public String getAction() {
return action;
}
/** Returns the value of the message id property. */
public String getMessageId() {
return messageId;
}
/** Returns the value of the relationship property. */
public String getRelatesTo() {
return relatesTo;
}
/** Returns the endpoint properties. Returns an empty list of none are set. */
public List getReferenceProperties() {
return Collections.unmodifiableList(referenceProperties);
}
/** Returns the endpoint parameters. Returns an empty list of none are set. */
public List getReferenceParameters() {
return Collections.unmodifiableList(referenceParameters);
}
/**
* Indicates whether is {@link MessageAddressingProperties} is valid, i.e. whether all required elements are listed.
* Returns <code>true</code> if the destination and action properties have been set, and if a reply or fault
* endpoint has been set, also checks for the message id.
*/
public boolean isValid() {
return StringUtils.hasLength(to) && StringUtils.hasLength(action) &&
!(replyTo != null && !StringUtils.hasLength(messageId)) &&
!(faultTo != null && !StringUtils.hasLength(messageId));
}
public MessageAddressingProperties getResponseProperties(EndpointReference epr, String action, String messageId) {
return new MessageAddressingProperties(epr, action, messageId, this.messageId);
}
/**
* Indicates whether is {@link MessageAddressingProperties} has all required properties. Returns <code>true</code>
* if the destination and action properties have been set, and if a reply or fault endpoint has been set, also
* checks for the message id.
*/
public boolean hasRequiredProperties() {
return StringUtils.hasLength(to) && StringUtils.hasLength(action) &&
!(replyTo != null && !StringUtils.hasLength(messageId)) &&
!(faultTo != null && !StringUtils.hasLength(messageId));
}
}

View File

@@ -1,62 +0,0 @@
/*
* 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.soap.addressing;
import javax.xml.namespace.QName;
import org.springframework.xml.namespace.QNameUtils;
/**
* Implements the August 2004 edition of the WS-Addressing specification. This version of the specification is used by
* Microsoft's Web Services Enhancements (WSE) 3.0, and supported by Axis 1 and 2, and XFire.
*
* @author Arjen Poutsma
* @see <a href="http://msdn.microsoft.com/ws/2004/08/ws-addressing/">Web Services Addressing, August 2004</a>
* @since 1.1.0
*/
public class WsAddressing200408 extends AbstractWsAddressingVersion {
private static final String NAMESPACE_URI = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
protected final String getAnonymousUri() {
return NAMESPACE_URI + "/role/anonymous";
}
protected final String getInvalidAddressingHeaderFaultReason() {
return "A message information header is not valid and the message cannot be processed.";
}
protected final QName getInvalidAddressingHeaderFaultSubcode() {
return QNameUtils.createQName(NAMESPACE_URI, "InvalidMessageInformationHeader", getNamespacePrefix());
}
protected final String getMessageAddressingHeaderRequiredFaultReason() {
return "A required message information header, To, MessageID, or Action, is not present.";
}
protected final QName getMessageAddressingHeaderRequiredFaultSubcode() {
return QNameUtils.createQName(NAMESPACE_URI, "MessageInformationHeaderRequired", getNamespacePrefix());
}
protected final String getNamespaceUri() {
return NAMESPACE_URI;
}
protected final String getNoneUri() {
return null;
}
}

View File

@@ -1,67 +0,0 @@
/*
* 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.soap.addressing;
import javax.xml.namespace.QName;
import org.springframework.xml.namespace.QNameUtils;
/**
* Implements the May 2006 edition of the WS-Addressing specification. This version of the specification is used by
* Microsoft's Windows Communication Foundation (WCF), and supported by Axis 1 and 2.
*
* @author Arjen Poutsma
* @see <a href="http://www.w3.org/TR/2006/REC-ws-addr-core-20060509">Web Services Addressing, August 2004</a>
* @since 1.1.0
*/
public class WsAddressing200605 extends AbstractWsAddressingVersion {
private static final String NAMESPACE_URI = "http://www.w3.org/2005/08/addressing";
protected String getNamespaceUri() {
return NAMESPACE_URI;
}
protected QName getReferencePropertiesName() {
return null;
}
protected final String getAnonymousUri() {
return NAMESPACE_URI + "/anonymous";
}
protected final String getNoneUri() {
return NAMESPACE_URI + "/none";
}
protected final QName getMessageAddressingHeaderRequiredFaultSubcode() {
return QNameUtils.createQName(NAMESPACE_URI, "MessageAddressingHeaderRequired", getNamespacePrefix());
}
protected final String getMessageAddressingHeaderRequiredFaultReason() {
return "A required header representing a Message Addressing Property is not present";
}
protected QName getInvalidAddressingHeaderFaultSubcode() {
return QNameUtils.createQName(NAMESPACE_URI, "InvalidAddressingHeader", getNamespacePrefix());
}
protected String getInvalidAddressingHeaderFaultReason() {
return "A header representing a Message Addressing Property is not valid and the message cannot be processed";
}
}

View File

@@ -1,36 +0,0 @@
/*
* 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.soap.addressing;
import org.springframework.ws.WebServiceException;
/**
* Exception thrown in cases on WS-Addressing errors.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class WsAddressingException extends WebServiceException {
public WsAddressingException(String msg) {
super(msg);
}
public WsAddressingException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -1,141 +0,0 @@
/*
* 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.soap.addressing;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.addressing.messageid.MessageIdStrategy;
import org.springframework.ws.soap.server.SoapEndpointInterceptor;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;
/**
* {@link SoapEndpointInterceptor} implementation that u
*
* @author Arjen Poutsma
*/
class WsAddressingInterceptor implements SoapEndpointInterceptor {
private static final Log logger = LogFactory.getLog(WsAddressingInterceptor.class);
private final WsAddressingVersion version;
private final MessageIdStrategy messageIdStrategy;
private final WebServiceMessageSender[] messageSenders;
WsAddressingInterceptor(WsAddressingVersion version,
MessageIdStrategy messageIdStrategy,
WebServiceMessageSender[] messageSenders) {
Assert.notNull(version, "version must not be null");
Assert.notNull(messageIdStrategy, "messageIdStrategy must not be null");
Assert.notNull(messageSenders, "messageSenders must not be null");
this.version = version;
this.messageIdStrategy = messageIdStrategy;
this.messageSenders = messageSenders;
}
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest(),
"WsAddressingInterceptor requires a SoapMessage request");
SoapMessage request = (SoapMessage) messageContext.getRequest();
MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request);
if (!requestMap.hasRequiredProperties()) {
version.addMessageAddressingHeaderRequiredFault((SoapMessage) messageContext.getResponse());
return false;
}
if (!requestMap.isValid() || messageIdStrategy.isDuplicate(requestMap.getMessageId())) {
version.addInvalidAddressingHeaderFault((SoapMessage) messageContext.getResponse());
return false;
}
return true;
}
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
return handleResponseOrFault(messageContext);
}
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return handleResponseOrFault(messageContext);
}
private boolean handleResponseOrFault(MessageContext messageContext) throws Exception {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest(),
"WsAddressingInterceptor requires a SoapMessage request");
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(),
"WsAddressingInterceptor requires a SoapMessage response");
SoapMessage request = (SoapMessage) messageContext.getRequest();
MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request);
SoapMessage response = (SoapMessage) messageContext.getResponse();
EndpointReference responseEpr = response.hasFault() ? requestMap.getFaultTo() : requestMap.getReplyTo();
if (responseEpr == null || version.hasNoneAddress(responseEpr)) {
logger.debug("Request has none reply address");
return false;
}
String responseMessageId = messageIdStrategy.newMessageId(response);
if (logger.isDebugEnabled()) {
logger.debug("Generated reply MessageID [" + responseMessageId + "]");
}
MessageAddressingProperties replyMap = requestMap.getResponseProperties(responseEpr, null, responseMessageId);
version.addAddressingHeaders(response, replyMap);
if (version.hasAnonymousAddress(responseEpr)) {
logger.debug("Sending in-band reply");
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Sending out-of-band reply message to EPR address [" + responseEpr.getAddress() + "]");
}
sendOutOfBand(responseEpr.getAddress(), response);
return false;
}
}
private void sendOutOfBand(String uri, SoapMessage message) throws IOException {
boolean supported = false;
for (int i = 0; i < messageSenders.length; i++) {
if (messageSenders[i].supports(uri)) {
supported = true;
WebServiceConnection connection = null;
try {
connection = messageSenders[i].createConnection(uri);
connection.send(message);
break;
}
finally {
if (connection != null) {
connection.close();
}
}
}
}
if (!supported) {
logger.warn("Could not send out-of-band response to [" + uri + "]. " +
"Configure WebServiceMessageSenders which support this uri.");
}
}
public boolean understands(SoapHeaderElement header) {
return version.understands(header);
}
}

View File

@@ -1,94 +0,0 @@
/*
* 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.soap.addressing;
import org.springframework.ws.soap.SoapFault;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;
/**
* Defines the contract for a specific version of the WS-Addressing specification.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public interface WsAddressingVersion {
/**
* Returns the {@link MessageAddressingProperties} for the given message.
*
* @param message the message to find the map for
* @return the message addressing properties
* @see <a href="http://www.w3.org/TR/ws-addr-core/#msgaddrprops">Message Addressing Properties</a>
*/
MessageAddressingProperties getMessageAddressingProperties(SoapMessage message);
/**
* Adds addressing SOAP headers to the given message, using the given {@link MessageAddressingProperties}.
*
* @param message the message to add the headers to
* @param map the message addressing properties
*/
void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map);
/**
* Given a <code>SoapHeaderElement</code>, return whether or not this version understands it.
*
* @param headerElement the header
* @return <code>true</code> if understood, <code>false</code> otherwise
*/
boolean understands(SoapHeaderElement headerElement);
/*
* Address URIs
*/
/**
* Indicates whether the given endpoint reference has a Anonymous address. This address is used to indicate that a
* message should be sent in-band.
*
* @see <a href="http://www.w3.org/TR/ws-addr-core/#formreplymsg">Formulating a Reply Message</a>
*/
boolean hasAnonymousAddress(EndpointReference epr);
/**
* Indicates whether the given endpoint reference has a None address. Messages to be sent to this address will not
* be sent.
*
* @see <a href="http://www.w3.org/TR/ws-addr-core/#sendmsgepr">Sending a Message to an EPR</a>
*/
boolean hasNoneAddress(EndpointReference epr);
/*
* Faults
*/
/**
* Adds a Invalid Addressing Header fault to the given message.
*
* @see <a href="http://www.w3.org/TR/ws-addr-soap/#invalidmapfault">Invalid Addressing Header</a>
*/
SoapFault addInvalidAddressingHeaderFault(SoapMessage message);
/**
* Adds a Message Addressing Header Required fault to the given message.
*
* @see <a href="http://www.w3.org/TR/ws-addr-soap/#missingmapfault">Message Addressing Header Required</a>
*/
SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message);
}

View File

@@ -1,45 +0,0 @@
/*
* 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.soap.addressing.messageid;
import org.springframework.ws.soap.SoapMessage;
/**
* Strategy interface that encapsulates the creation and validation of WS-Addressing <code>MessageID</code>s.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public interface MessageIdStrategy {
/**
* Indicates whether the given <code>MessageID</code> value is a duplicate or not
*
* @param messageId the message id
* @return <code>true</code> if a duplicate; <code>false</code> otherwise
*/
boolean isDuplicate(String messageId);
/**
* Returns a new WS-Addressing <code>MessageID</code> for the given message.
*
* @param message the SOAP message to create a new message id for
* @return the new message id
*/
String newMessageId(SoapMessage message);
}

View File

@@ -1,41 +0,0 @@
/*
* 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.soap.addressing.messageid;
import java.rmi.server.UID;
import org.springframework.ws.soap.SoapMessage;
/**
* Implementation of the {@link MessageIdStrategy} interface that uses a {@link UID} to generate a Message Id. The UID
* is prefixed by <code>uid:</code>.
*
* @author Arjen Poutsma
*/
public class UidMessageIdStrategy implements MessageIdStrategy {
public static final String PREFIX = "uid:";
/** Returns <code>false</code>. */
public boolean isDuplicate(String messageId) {
return false;
}
public String newMessageId(SoapMessage message) {
return PREFIX + new UID().toString();
}
}

View File

@@ -1,43 +0,0 @@
/*
* 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.soap.addressing.messageid;
import java.util.UUID;
import org.springframework.ws.soap.SoapMessage;
/**
* Implementation of the {@link MessageIdStrategy} interface that uses a {@link UUID} to generate a Message Id. The UUID
* is prefixed by <code>uuid:</code>.
* <p/>
* Note that the {@link UUID} class is only available on Java 5 and above.
*
* @author Arjen Poutsma
*/
public class UuidMessageIdStrategy implements MessageIdStrategy {
public static final String PREFIX = "uuid:";
/** Returns <code>false</code>. */
public boolean isDuplicate(String messageId) {
return false;
}
public String newMessageId(SoapMessage message) {
return PREFIX + UUID.randomUUID().toString();
}
}

View File

@@ -1,5 +0,0 @@
<html>
<body>
Contains various strategies for generating WS-Addressing MessageIDs.
</body>
</html>

View File

@@ -1,5 +0,0 @@
<html>
<body>
Provides WS-Addressing implementation classes.
</body>
</html>

View File

@@ -1,73 +0,0 @@
/*
* 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.jms;
import java.io.IOException;
import java.io.InputStream;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageEOFException;
/**
* Input stream that wraps a {@link BytesMessage}.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
class BytesMessageInputStream extends InputStream {
private BytesMessage message;
BytesMessageInputStream(BytesMessage message) {
this.message = message;
}
public int read(byte b[]) throws IOException {
try {
return message.readBytes(b);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
public int read(byte b[], int off, int len) throws IOException {
if (off == 0) {
try {
return message.readBytes(b, len);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
else {
return super.read(b, off, len);
}
}
public int read() throws IOException {
try {
return message.readByte();
}
catch (MessageEOFException ex) {
return -1;
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
}

View File

@@ -1,64 +0,0 @@
/*
* 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.jms;
import java.io.IOException;
import java.io.OutputStream;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
/**
* Output stream that wraps a {@link BytesMessage}.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
class BytesMessageOutputStream extends OutputStream {
private BytesMessage message;
BytesMessageOutputStream(BytesMessage message) {
this.message = message;
}
public void write(byte b[]) throws IOException {
try {
message.writeBytes(b);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
public void write(byte b[], int off, int len) throws IOException {
try {
message.writeBytes(b, off, len);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
public void write(int b) throws IOException {
try {
message.writeByte((byte) b);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 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.ws.transport.jms;
import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageReceiver;
import org.springframework.ws.transport.support.SimpleWebServiceMessageReceiverObjectSupport;
/**
* Convenience base class for JMS server-side transport objects. Contains a {@link WebServiceMessageReceiver}, and has
* methods for handling incoming JMS {@link Message} requests.
* <p/>
* Used by {@link WebServiceMessageListener} and {@link WebServiceMessageDrivenBean}.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class JmsMessageReceiver extends SimpleWebServiceMessageReceiverObjectSupport {
/**
* Handles an incoming messages. Uses the given session to create a response message.
*
* @param request the incoming message
* @param session the JMS session used to create a response
* @throws IllegalArgumentException when request is not a {@link BytesMessage}
*/
protected final void handleMessage(Message request, Session session) throws Exception {
if (request instanceof BytesMessage) {
WebServiceConnection connection = new JmsReceiverConnection((BytesMessage) request, session);
handleConnection(connection);
}
else {
throw new IllegalArgumentException(
"Wrong message type: [" + request.getClass() + "]. Only BytesMessages can be handled.");
}
}
}

View File

@@ -1,99 +0,0 @@
/*
* 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.jms;
import java.io.IOException;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.jms.support.destination.DynamicDestinationResolver;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;
/**
* {@link WebServiceMessageSender} implementation that uses JMS.
* <p/>
* This message sender sends the request message of the queue configured with either the <code>queue</code> or
* <code>queueName</code> property. It creates a temporary queue for the response message. For both request and response
* {@link BytesMessage}s are used.
*
* @author Arjen Poutsma
*/
public class JmsMessageSender implements WebServiceMessageSender, JmsTransportConstants {
/**
* Default timeout for receive operations: -1 indicates a blocking receive without timeout.
*/
public static final long DEFAULT_RECEIVE_TIMEOUT = -1;
private ConnectionFactory connectionFactory;
private DestinationResolver destinationResolver = new DynamicDestinationResolver();
private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;
public JmsMessageSender() {
}
public JmsMessageSender(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
/**
* Set the ConnectionFactory to use for obtaining JMS {@link Connection}s.
*/
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setDestinationResolver(DestinationResolver destinationResolver) {
this.destinationResolver = destinationResolver;
}
/**
* Set the timeout to use for receive calls. The default is 0, which means no timeout.
*/
public void setReceiveTimeout(long receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
public WebServiceConnection createConnection(String uriString) throws IOException {
Assert.notNull(connectionFactory, "connectionFactory must not be null");
JmsSenderConnection connection = null;
try {
JmsUri uri = new JmsUri(uriString);
connection = new JmsSenderConnection(uri, connectionFactory, destinationResolver, receiveTimeout);
return connection;
}
catch (JMSException ex) {
if (connection != null) {
connection.close();
}
throw new JmsTransportException(ex);
}
}
public boolean supports(String uri) {
return StringUtils.hasLength(uri) && uri.startsWith(URI_SCHEME + ":");
}
}

View File

@@ -1,202 +0,0 @@
/*
* 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.jms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.springframework.jms.support.JmsUtils;
import org.springframework.util.Assert;
import org.springframework.ws.FaultAwareWebServiceMessage;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.transport.AbstractReceiverConnection;
import org.springframework.ws.transport.FaultAwareWebServiceConnection;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.jms.support.JmsTransportUtils;
/**
* Implementation of {@link WebServiceConnection} that is used for server-side JMS access.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class JmsReceiverConnection extends AbstractReceiverConnection
implements JmsTransportConstants, FaultAwareWebServiceConnection {
private final BytesMessage requestMessage;
private final Session session;
private BytesMessage responseMessage;
/**
* Constructs a new JMS connection with the given parameters.
*/
protected JmsReceiverConnection(BytesMessage requestMessage, Session session) {
Assert.notNull(requestMessage, "requestMessage must not be null");
Assert.notNull(session, "session must not be null");
this.requestMessage = requestMessage;
this.session = session;
}
/**
* Returns the request message for this connection.
*/
public BytesMessage getRequestMessage() {
return requestMessage;
}
/**
* Returns the response message, if any, for this connection.
*/
public BytesMessage getResponseMessage() {
return responseMessage;
}
public String getErrorMessage() throws IOException {
return null;
}
public boolean hasError() throws IOException {
return false;
}
/*
* Receiving
*/
protected Iterator getRequestHeaderNames() throws IOException {
try {
Enumeration headers = requestMessage.getPropertyNames();
List results = new ArrayList();
while (headers.hasMoreElements()) {
String header = (String) headers.nextElement();
if (header.startsWith(JmsTransportConstants.PROPERTY_PREFIX)) {
results.add(header);
}
}
return results.iterator();
}
catch (JMSException ex) {
throw new JmsTransportException("Could not get property names", ex);
}
}
protected Iterator getRequestHeaders(String name) throws IOException {
try {
String value = requestMessage.getStringProperty(name);
return Collections.singletonList(value).iterator();
}
catch (JMSException ex) {
throw new JmsTransportException("Could not get property value", ex);
}
}
protected InputStream getRequestInputStream() throws IOException {
return new BytesMessageInputStream(requestMessage);
}
/*
* Sending
*/
protected void onSendBeforeWrite(WebServiceMessage message) throws IOException {
try {
responseMessage = session.createBytesMessage();
responseMessage.setJMSCorrelationID(requestMessage.getJMSMessageID());
responseMessage.setStringProperty(PROPERTY_BINDING_VERSION, "1.0");
if (message instanceof FaultAwareWebServiceMessage) {
FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) message;
responseMessage.setBooleanProperty(PROPERTY_IS_FAULT, faultMessage.hasFault());
}
}
catch (JMSException ex) {
throw new JmsTransportException("Could not create response message", ex);
}
}
protected void addResponseHeader(String name, String value) throws IOException {
try {
String property = JmsTransportUtils.headerToJmsProperty(name);
responseMessage.setStringProperty(property, value);
}
catch (JMSException ex) {
throw new JmsTransportException("Could not set property", ex);
}
}
protected OutputStream getResponseOutputStream() throws IOException {
return new BytesMessageOutputStream(responseMessage);
}
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
MessageProducer messageProducer = null;
try {
if (requestMessage.getJMSReplyTo() != null) {
messageProducer = session.createProducer(requestMessage.getJMSReplyTo());
messageProducer.setDeliveryMode(requestMessage.getJMSDeliveryMode());
messageProducer.setPriority(requestMessage.getJMSPriority());
messageProducer.send(responseMessage);
}
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
finally {
JmsUtils.closeMessageProducer(messageProducer);
}
}
public void close() throws IOException {
}
/*
* Faults
*/
public boolean hasFault() throws IOException {
try {
return requestMessage.getBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
public void setFault(boolean fault) throws IOException {
if (responseMessage != null) {
try {
responseMessage.setBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT, fault);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
}
}

View File

@@ -1,276 +0,0 @@
/*
* 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.jms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import org.springframework.jms.connection.ConnectionFactoryUtils;
import org.springframework.jms.support.JmsUtils;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.util.Assert;
import org.springframework.ws.FaultAwareWebServiceMessage;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.transport.AbstractSenderConnection;
import org.springframework.ws.transport.FaultAwareWebServiceConnection;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.jms.support.JmsTransportUtils;
/**
* Implementation of {@link WebServiceConnection} that is used for client-side JMS access.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class JmsSenderConnection extends AbstractSenderConnection
implements FaultAwareWebServiceConnection, JmsTransportConstants {
private final ConnectionFactory connectionFactory;
private final DestinationResolver destinationResolver;
private final Connection connection;
private final Session session;
private final Destination requestDestination;
private final JmsUri uri;
private final long receiveTimeout;
private Destination responseDestination;
private BytesMessage requestMessage;
private BytesMessage responseMessage;
/**
* Constructs a new JMS connection with the given parameters.
*/
protected JmsSenderConnection(JmsUri uri,
ConnectionFactory connectionFactory,
DestinationResolver destinationResolver,
long receiveTimeout) throws JMSException {
Assert.notNull(uri, "'uri' must not be null");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
Assert.notNull(destinationResolver, "destinationResolver must not be null");
this.connectionFactory = connectionFactory;
this.destinationResolver = destinationResolver;
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
requestDestination =
destinationResolver.resolveDestinationName(session, uri.getDestination(), uri.isPubSubDomain());
this.uri = uri;
this.receiveTimeout = receiveTimeout;
}
/**
* Returns the request message for this connection.
*/
public BytesMessage getRequestMessage() {
return requestMessage;
}
/**
* Returns the response message, if any, for this connection.
*/
public BytesMessage getResponseMessage() {
return responseMessage;
}
public boolean hasError() throws IOException {
return false;
}
public String getErrorMessage() throws IOException {
return null;
}
/*
* Sending
*/
protected void onSendBeforeWrite(WebServiceMessage message) throws IOException {
try {
requestMessage = session.createBytesMessage();
requestMessage.setStringProperty(PROPERTY_BINDING_VERSION, "1.0");
if (message instanceof FaultAwareWebServiceMessage) {
FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) message;
requestMessage.setBooleanProperty(PROPERTY_IS_FAULT, faultMessage.hasFault());
}
requestMessage.setStringProperty(PROPERTY_REQUEST_IRI, uri.toString());
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
protected void addRequestHeader(String name, String value) throws IOException {
try {
String property = JmsTransportUtils.headerToJmsProperty(name);
requestMessage.setStringProperty(property, value);
}
catch (JMSException ex) {
throw new JmsTransportException("Could not set property", ex);
}
}
protected OutputStream getRequestOutputStream() throws IOException {
return new BytesMessageOutputStream(requestMessage);
}
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
MessageProducer messageProducer = null;
try {
messageProducer = session.createProducer(requestDestination);
messageProducer.setDeliveryMode(uri.getDeliveryMode());
messageProducer.setTimeToLive(uri.getTimeToLive());
messageProducer.setPriority(uri.getPriority());
if (uri.hasReplyTo()) {
responseDestination =
destinationResolver.resolveDestinationName(session, uri.getReplyTo(), uri.isPubSubDomain());
}
else {
responseDestination = session.createTemporaryQueue();
}
requestMessage.setJMSReplyTo(responseDestination);
connection.start();
messageProducer.send(requestMessage);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
finally {
JmsUtils.closeMessageProducer(messageProducer);
}
}
/*
* Receiving
*/
protected void onReceiveBeforeRead() throws IOException {
MessageConsumer messageConsumer = null;
try {
messageConsumer = session.createConsumer(responseDestination);
responseMessage = (BytesMessage) (receiveTimeout >= 0 ? messageConsumer.receive(receiveTimeout) :
messageConsumer.receive());
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
finally {
JmsUtils.closeMessageConsumer(messageConsumer);
if (responseDestination instanceof TemporaryQueue) {
try {
((TemporaryQueue) responseDestination).delete();
}
catch (JMSException e) {
// ignore
}
}
}
}
protected boolean hasResponse() throws IOException {
return responseMessage != null;
}
protected Iterator getResponseHeaderNames() throws IOException {
try {
List headerNames = new ArrayList();
Enumeration propertyNames = responseMessage.getPropertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
headerNames.add(JmsTransportUtils.jmsPropertyToHeader(propertyName));
}
return headerNames.iterator();
}
catch (JMSException ex) {
throw new JmsTransportException("Could not get property names", ex);
}
}
protected Iterator getResponseHeaders(String name) throws IOException {
try {
String propertyName = JmsTransportUtils.headerToJmsProperty(name);
String value = responseMessage.getStringProperty(propertyName);
if (value != null) {
return Collections.singletonList(value).iterator();
}
else {
return Collections.EMPTY_LIST.iterator();
}
}
catch (JMSException ex) {
throw new JmsTransportException("Could not get property value", ex);
}
}
protected InputStream getResponseInputStream() throws IOException {
return new BytesMessageInputStream(responseMessage);
}
public void close() throws IOException {
JmsUtils.closeSession(session);
ConnectionFactoryUtils.releaseConnection(connection, connectionFactory, true);
}
/*
* Faults
*/
public boolean hasFault() throws IOException {
if (responseMessage != null) {
try {
return responseMessage.getBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
else {
return false;
}
}
public void setFault(boolean fault) throws IOException {
try {
requestMessage.setBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT, fault);
}
catch (JMSException ex) {
throw new JmsTransportException(ex);
}
}
}

View File

@@ -1,68 +0,0 @@
/*
* 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.jms;
import org.springframework.ws.transport.TransportConstants;
/**
* Declares JMS-specific transport constants.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public interface JmsTransportConstants extends TransportConstants {
String URI_SCHEME = "jms";
String PARAM_DELIVERY_MODE = "deliveryMode";
String PARAM_CONNECTION_FACTORY_NAME = "connectionFactoryName";
String PARAM_INITIAL_CONTEXT_FACTORY = "initialContextFactory";
String PARAM_JNDI_URL = "jndiURL";
String PARAM_TIME_TO_LIVE = "timeToLive";
String PARAM_PRIORITY = "priority";
String PARAM_DESTINATION_TYPE = "destinationType";
String PARAM_REPLY_TO_NAME = "replyToName";
String DESTINATION_TYPE_QUEUE = "queue";
String DESTINATION_TYPE_TOPIC = "topic";
String PROPERTY_PREFIX = "SOAPJMS_";
String PROPERTY_IS_FAULT = PROPERTY_PREFIX + "isFault";
String PROPERTY_SOAP_ACTION = PROPERTY_PREFIX + "soapAction";
String PROPERTY_CONTENT_LENGTH = PROPERTY_PREFIX + "contentLength";
String PROPERTY_CONTENT_TYPE = PROPERTY_PREFIX + "contentType";
String PROPERTY_BINDING_VERSION = PROPERTY_PREFIX + "bindingVersion";
String PROPERTY_TARGET_SERVICE = PROPERTY_PREFIX + "targetService";
String PROPERTY_REQUEST_IRI = PROPERTY_PREFIX + "requestIRI";
String PROPERTY_SOAP_MEP = PROPERTY_PREFIX + "soapMEP";
}

View File

@@ -1,47 +0,0 @@
/*
* 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.jms;
import javax.jms.JMSException;
import org.springframework.ws.transport.TransportException;
/**
* Exception that is thrown when an error occurs in the JMS transport.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class JmsTransportException extends TransportException {
private final JMSException jmsException;
public JmsTransportException(String msg, JMSException ex) {
super(msg + ": " + ex.getMessage());
jmsException = ex;
}
public JmsTransportException(JMSException ex) {
super(ex.getMessage());
jmsException = ex;
}
public JMSException getJmsException() {
return jmsException;
}
}

View File

@@ -1,134 +0,0 @@
/*
* 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.jms;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Topic;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.ws.transport.support.ParameterizedUri;
/**
* @author Arjen Poutsma
* @see <a href="http://mail-archives.apache.org/mod_mbox/ws-axis-dev/200701.mbox/raw/%3C80A43FC052CE3949A327527DCD5D6B27020FB65C@MAIL01.bedford.progress.com%3E/2">RI
* Scheme for Java Message Service 1.0 RC1</a>
*/
public class JmsUri extends ParameterizedUri implements JmsTransportConstants {
public JmsUri(String uri) {
super(uri);
validateParameters();
}
private void validateParameters() {
validateIntegerParameter(PARAM_DELIVERY_MODE);
validateIntegerParameter(PARAM_PRIORITY);
validateIntegerParameter(PARAM_TIME_TO_LIVE);
String destinationType = getDestinationType();
if (StringUtils.hasLength(destinationType)) {
Assert.isTrue(
DESTINATION_TYPE_QUEUE.equals(destinationType) || DESTINATION_TYPE_TOPIC.equals(destinationType),
"Invalid " + PARAM_DESTINATION_TYPE + ": [" + destinationType + "]. Expected '" +
DESTINATION_TYPE_QUEUE + "' or '" + DESTINATION_TYPE_TOPIC + "'");
}
}
private void validateIntegerParameter(String paramName) {
String paramValue = getParameter(paramName);
if (StringUtils.hasLength(paramValue)) {
try {
Integer.parseInt(paramValue);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid " + paramName + ": [" + paramValue + "]. Not an integer.");
}
}
}
/**
* Returns whether the request message is persistent or not.
*
* @see DeliveryMode#NON_PERSISTENT
* @see DeliveryMode#PERSISTENT
*/
public int getDeliveryMode() {
return getIntegerParameter(PARAM_DELIVERY_MODE, Message.DEFAULT_DELIVERY_MODE);
}
public String getDestination() {
return super.getDestination();
}
/**
* Specifies whether the destination is a {@link Queue} or a {@link Topic}, with the value "<code>queue</code>" or
* "<code>topic</code>", respectively.
*/
public String getDestinationType() {
return getParameter(PARAM_DESTINATION_TYPE);
}
/**
* Returns the JMS priority associated with the request message.
*
* @see Message#setJMSPriority(int)
*/
public int getPriority() {
return getIntegerParameter(PARAM_PRIORITY, Message.DEFAULT_PRIORITY);
}
/**
* Returns the lifetime, in milliseconds, of the request message.
*/
public long getTimeToLive() {
String paramValue = getParameter(PARAM_TIME_TO_LIVE);
return paramValue != null ? Long.parseLong(paramValue) : Message.DEFAULT_TIME_TO_LIVE;
}
private int getIntegerParameter(String paramName, int defaultValue) {
String paramValue = getParameter(paramName);
return paramValue != null ? Integer.parseInt(paramValue) : defaultValue;
}
/**
* Indicates whether this URI has a reply-to name.
*/
public boolean hasReplyTo() {
return StringUtils.hasLength(getReplyTo());
}
/**
* Returns the reply-to name.
*
* @see Message#setJMSReplyTo(Destination)
*/
public String getReplyTo() {
return getParameter(PARAM_REPLY_TO_NAME);
}
/**
* Return whether the Publish/Subscribe domain ({@link javax.jms.Topic Topics}) is used. Otherwise, the
* Point-to-Point domain ({@link javax.jms.Queue Queues}) is used.
*/
public boolean isPubSubDomain() {
return DESTINATION_TYPE_TOPIC.equals(getDestinationType());
}
}

View File

@@ -1,157 +0,0 @@
/*
* 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.jms;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.naming.NamingException;
import org.springframework.ejb.support.AbstractJmsMessageDrivenBean;
import org.springframework.jms.connection.ConnectionFactoryUtils;
import org.springframework.jms.support.JmsUtils;
import org.springframework.jndi.JndiLookupFailureException;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.transport.WebServiceMessageReceiver;
/**
* EJB {@link MessageDrivenBean} that can be used to handleMessage incoming JMS messages.
* <p/>
* This class needs a JMS {@link ConnectionFactory}, and a {@link WebServiceMessageFactory} and {@link
* WebServiceMessageReceiver} to operate. By default, these are obtained by doing a bean lookup on the bean factory
* provided by {@link #getBeanFactory()} the super class.
*
* @author Arjen Poutsma
* @see #createConnectionFactory()
* @see #createMessageFactory()
* @see #createMessageReceiver()
*/
public class WebServiceMessageDrivenBean extends AbstractJmsMessageDrivenBean {
/** Well-known name for the {@link ConnectionFactory} object in the bean factory for this bean. */
public static final String CONNECTION_FACTORY_BEAN_NAME = "connectionFactory";
/** Well-known name for the {@link WebServiceMessageFactory} bean in the bean factory for this bean. */
public static final String MESSAGE_FACTORY_BEAN_NAME = "messageFactory";
/** Well-known name for the {@link WebServiceMessageReceiver} object in the bean factory for this bean. */
public static final String MESSAGE_RECEIVER_BEAN_NAME = "messageReceiver";
private JmsMessageReceiver delegate;
private ConnectionFactory connectionFactory;
/** Delegates to {@link JmsMessageReceiver#handleMessage(Message,Session)}. */
public void onMessage(Message message) {
Connection connection = null;
Session session = null;
try {
connection = createConnection(connectionFactory);
session = createSession(connection);
delegate.handleMessage(message, session);
}
catch (JmsTransportException ex) {
throw JmsUtils.convertJmsAccessException(ex.getJmsException());
}
catch (JMSException ex) {
throw JmsUtils.convertJmsAccessException(ex);
}
catch (Exception ex) {
throw new EJBException(ex);
}
finally {
JmsUtils.closeSession(session);
ConnectionFactoryUtils.releaseConnection(connection, connectionFactory, true);
}
}
/**
* Creates a new {@link Connection}, {@link WebServiceMessageFactory}, and {@link WebServiceMessageReceiver}.
*
* @see #createConnectionFactory()
* @see #createMessageFactory()
* @see #createMessageReceiver()
*/
protected void onEjbCreate() {
try {
connectionFactory = createConnectionFactory();
delegate = new JmsMessageReceiver();
delegate.setMessageFactory(createMessageFactory());
delegate.setMessageReceiver(createMessageReceiver());
}
catch (NamingException ex) {
throw new JndiLookupFailureException("Could not create connection", ex);
}
catch (JMSException ex) {
throw JmsUtils.convertJmsAccessException(ex);
}
catch (Exception ex) {
throw new EJBException(ex);
}
}
/** Creates a connection factory. Default implemantion does a bean lookup for {@link #CONNECTION_FACTORY_BEAN_NAME}. */
protected ConnectionFactory createConnectionFactory() throws Exception {
return (ConnectionFactory) getBeanFactory().getBean(CONNECTION_FACTORY_BEAN_NAME, ConnectionFactory.class);
}
/** Creates a message factory. Default implemantion does a bean lookup for {@link #MESSAGE_FACTORY_BEAN_NAME}. */
protected WebServiceMessageFactory createMessageFactory() {
return (WebServiceMessageFactory) getBeanFactory()
.getBean(MESSAGE_FACTORY_BEAN_NAME, WebServiceMessageFactory.class);
}
/** Creates a connection factory. Default implemantion does a bean lookup for {@link #MESSAGE_RECEIVER_BEAN_NAME}. */
protected WebServiceMessageReceiver createMessageReceiver() {
return (WebServiceMessageReceiver) getBeanFactory()
.getBean(MESSAGE_RECEIVER_BEAN_NAME, WebServiceMessageReceiver.class);
}
/**
* Create a JMS {@link Connection} using the given {@link ConnectionFactory}.
* <p/>
* This implementation uses JMS 1.1 API.
*
* @param connectionFactory the JMS ConnectionFactory to create a Connection with
* @return the new JMS Connection
* @throws JMSException if thrown by JMS API methods
* @see ConnectionFactory#createConnection()
*/
protected Connection createConnection(ConnectionFactory connectionFactory) throws JMSException {
return connectionFactory.createConnection();
}
/**
* Creates a JMS {@link Session}. Default implemantion creates a non-transactional, {@link Session#AUTO_ACKNOWLEDGE
* auto acknowledged} session.
* <p/>
* This implementation uses JMS 1.1 API.
*
* @param connection the JMS Connection to create a Session for
* @return the new JMS Session
* @throws JMSException if thrown by JMS API methods
* @see Connection#createSession(boolean,int)
*/
protected Session createSession(Connection connection) throws JMSException {
return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
}

View File

@@ -1,57 +0,0 @@
/*
* Copyright 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.ws.transport.jms;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.transport.WebServiceMessageReceiver;
/**
* Spring-2.0 {@link SessionAwareMessageListener} that can be used to handle incoming JMS messages.
* <p/>
* Requires a {@link WebServiceMessageFactory} which is used to convert the incoming JMS {@link BytesMessage} into a
* {@link WebServiceMessage}, and passes that to the {@link WebServiceMessageReceiver} {@link
* #setMessageReceiver(WebServiceMessageReceiver) registered}.
*
* @author Arjen Poutsma
* @see #setMessageFactory(org.springframework.ws.WebServiceMessageFactory)
* @see #setMessageReceiver(org.springframework.ws.transport.WebServiceMessageReceiver)
* @since 1.1.0
*/
public class WebServiceMessageListener extends JmsMessageReceiver implements SessionAwareMessageListener {
public void onMessage(Message message, Session session) throws JMSException {
try {
handleMessage(message, session);
}
catch (JmsTransportException ex) {
throw ex.getJmsException();
}
catch (Exception ex) {
JMSException jmsException = new JMSException(ex.getMessage());
jmsException.setLinkedException(ex);
throw jmsException;
}
}
}

View File

@@ -1,5 +0,0 @@
<html>
<body>
Package providing support for handling messages via JMS.
</body>
</html>

View File

@@ -1,69 +0,0 @@
/*
* 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.jms.support;
import org.springframework.ws.transport.jms.JmsTransportConstants;
/**
* Collection of utility methods to work with JMS transports. Includes methods to convert from transport header names to
* JMS Properties and vice-versa.
*
* @author Arjen Poutsma
* @since 1.1.0
*/
public class JmsTransportUtils {
private static final String[] CONVERSION_TABLE = new String[]{JmsTransportConstants.HEADER_CONTENT_TYPE,
JmsTransportConstants.PROPERTY_CONTENT_TYPE, JmsTransportConstants.HEADER_CONTENT_LENGTH,
JmsTransportConstants.PROPERTY_CONTENT_LENGTH, JmsTransportConstants.HEADER_SOAP_ACTION,
JmsTransportConstants.PROPERTY_SOAP_ACTION};
private JmsTransportUtils() {
}
/**
* Converts the given transport header to a JMS property name. Returns the given header name if no match is found.
*
* @param headerName the header name to transform
* @return the JMS property name
*/
public static String headerToJmsProperty(String headerName) {
for (int i = 0; i < CONVERSION_TABLE.length; i = i + 2) {
if (CONVERSION_TABLE[i].equals(headerName)) {
return CONVERSION_TABLE[i + 1];
}
}
return headerName;
}
/**
* Converts the given JMS property name to a transport header name. Returns the given property name if no match is
* found.
*
* @param propertyName the JMS property name to transform
* @return the transport header name
*/
public static String jmsPropertyToHeader(String propertyName) {
for (int i = 1; i < CONVERSION_TABLE.length; i = i + 2) {
if (CONVERSION_TABLE[i].equals(propertyName)) {
return CONVERSION_TABLE[i - 1];
}
}
return propertyName;
}
}

View File

@@ -1,5 +0,0 @@
<html>
<body>
Classes supporting the org.springframework.ws.transport.jms package.
</body>
</html>

View File

@@ -1,90 +0,0 @@
/*
* 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.mail;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
/**
* Abstract base class for {@link MonitoringStrategy} implementations that use a polling mechanism. Defines a {@link
* #setPollingInterval(int) polling interval} property which defines the interval in between message polls.
*
* @author Arjen Poutsma
*/
public abstract class AbstractPollingMonitoringStrategy implements MonitoringStrategy, InitializingBean {
/**
* Defines the default polling frequency. Set to 1000 * 60 * 5 milliseconds (i.e. 5 minutes).
*/
public static final int DEFAULT_POLLING_FREQUENCY = 1000 * 60 * 5;
/**
* Logger available to subclasses.
*/
private final Log logger = LogFactory.getLog(getClass());
private int pollingInterval = DEFAULT_POLLING_FREQUENCY;
public void afterPropertiesSet() throws Exception {
logger.info("Polling every " + getPollingInterval() + " milliseconds");
}
/**
* Returns the polling interval.
*/
public int getPollingInterval() {
return pollingInterval;
}
/**
* Sets the interval used in between message polls, <strong>in milliseconds</strong>. The default is 1000 * 60 * 5
* ms, that is 5 minutes.
*/
public void setPollingInterval(int pollingInterval) {
this.pollingInterval = pollingInterval;
}
/**
* Sleeps for the {@link #setPollingInterval(int) defined amount of milliseconds}, and calls {@link
* #pollForNewMessages(Folder)}.
*
* @param folder the folder to look in
* @return the new messages
* @throws MessagingException in case of JavaMail errors.
*/
public final Message[] getNewMessages(Folder folder) throws MessagingException {
try {
Thread.sleep(getPollingInterval());
folder.getMessageCount();
return pollForNewMessages(folder);
}
catch (InterruptedException e) {
logger.warn(e);
return new Message[0];
}
}
/**
* Abstract template method that is invoked every interval.
*/
protected abstract Message[] pollForNewMessages(Folder folder) throws MessagingException;
}

View File

@@ -1,108 +0,0 @@
/*
* 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.mail;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;
/**
* Default implementation of the {@link MonitoringStrategy}. Polls for new messages using a defined {@link
* #setPollingInterval(int) interval}.
*
* @author Arjen Poutsma
*/
public class DefaultMonitoringStrategy extends AbstractPollingMonitoringStrategy {
private boolean deleteMessages = true;
/**
* Sets whether messages should be marked as {@link Flags.Flag#DELETED DELETED} after they have been read. Default
* is <code>true</code>.
*/
public void setDeleteMessages(boolean deleteMessages) {
this.deleteMessages = deleteMessages;
}
/**
* Polls for new messages in the given folder. Calls {@link #createSearchTerm(Folder)}, and uses that created term
* to search for messages in the given folder. Marks the messages as {@link Flags.Flag#DELETED DELETED} if the
* {@link #setDeleteMessages(boolean) deleteMessages} property is set.
*/
protected final Message[] pollForNewMessages(Folder folder) throws MessagingException {
SearchTerm searchTerm = createSearchTerm(folder);
Message[] messages;
if (searchTerm == null) {
messages = folder.getMessages();
}
else {
messages = folder.search(searchTerm);
}
if (messages.length > 0) {
FetchProfile contentsProfile = new FetchProfile();
contentsProfile.add(FetchProfile.Item.ENVELOPE);
contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
folder.fetch(messages, contentsProfile);
if (deleteMessages) {
for (int i = 0; i < messages.length; i++) {
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
}
return messages;
}
/**
* Creates the search term that defines the messages to look for. Default implementation returns a term that
* searches for all messages in the folder that are {@link Flags.Flag#RECENT RECENT}, not {@link Flags.Flag#ANSWERED
* ANSWERED}, and not {@link Flags.Flag#DELETED DELETED}.
* <p/>
* Return <code>null</code> if all messages should be returned from {@link #pollForNewMessages(Folder)}.
*/
protected SearchTerm createSearchTerm(Folder folder) {
Flags supportedFlags = folder.getPermanentFlags();
SearchTerm searchTerm = null;
if (supportedFlags.contains(Flags.Flag.RECENT)) {
searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
}
if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
if (searchTerm == null) {
searchTerm = answeredTerm;
}
else {
searchTerm = new AndTerm(searchTerm, answeredTerm);
}
}
if (supportedFlags.contains(Flags.Flag.DELETED)) {
FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
if (searchTerm == null) {
searchTerm = deletedTerm;
}
else {
searchTerm = new AndTerm(searchTerm, deletedTerm);
}
}
return searchTerm;
}
}

View File

@@ -1,191 +0,0 @@
/*
* 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.mail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.util.Assert;
import org.springframework.ws.transport.mail.support.MailUtils;
import org.springframework.ws.transport.support.AbstractMultiThreadedMessageReceiver;
/**
* @author Arjen Poutsma
*/
public class MailMessageReceiver extends AbstractMultiThreadedMessageReceiver {
private Session session = Session.getInstance(new Properties(), null);
private URLName storeUri;
private URLName transportUri;
private Folder folder;
private Store store;
private MonitoringStrategy monitoringStrategy = new DefaultMonitoringStrategy();
private InternetAddress from;
public void setFrom(String from) throws AddressException {
this.from = new InternetAddress(from);
}
/**
* Set JavaMail properties for the {@link Session}.
* <p/>
* A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but
* not both.
* <p/>
* Non-default properties in this instance will override given JavaMail properties.
*/
public void setJavaMailProperties(Properties javaMailProperties) {
session = Session.getInstance(javaMailProperties, null);
}
/**
*
* @param monitoringStrategy
*/
public void setMonitoringStrategy(MonitoringStrategy monitoringStrategy) {
this.monitoringStrategy = monitoringStrategy;
}
/**
* Set the JavaMail <code>Session</code>, possibly pulled from JNDI.
* <p/>
* Default is a new <code>Session</code> without defaults, that is completely configured via this instance's
* properties.
* <p/>
* If using a pre-configured <code>Session</code>, non-default properties in this instance will override the
* settings in the <code>Session</code>.
*
* @see #setJavaMailProperties
*/
public void setSession(Session session) {
Assert.notNull(session, "Session must not be null");
this.session = session;
}
public void setStoreUri(String storeUri) {
this.storeUri = new URLName(storeUri);
}
public void setTransportUri(String transportUri) {
this.transportUri = new URLName(transportUri);
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(storeUri, "Property 'storeUri' is required");
Assert.notNull(transportUri, "Property 'transportUri' is required");
Assert.notNull(monitoringStrategy, "Property 'monitoringStrategy' is required");
super.afterPropertiesSet();
}
protected void onActivate() throws Exception {
openFolder();
}
protected void onStart() {
if (logger.isInfoEnabled()) {
logger.info("Starting mail receiver [" + storeUri.toString() + "]");
}
getTaskExecutor().execute(new MonitoringRunnable());
}
protected void onStop() {
if (logger.isInfoEnabled()) {
logger.info("Stopping mail receiver [" + storeUri.toString() + "]");
}
}
protected void onShutdown() {
if (logger.isInfoEnabled()) {
logger.info("Shutting down mail receiver [" + storeUri.toString() + "]");
}
closeFolder();
}
protected void closeFolder() {
MailUtils.closeFolder(folder, true);
MailUtils.closeService(store);
}
protected void openFolder() throws MessagingException, MailTransportException {
store = session.getStore(storeUri);
store.connect();
folder = store.getFolder(storeUri);
if (folder == null || !folder.exists()) {
throw new MailTransportException("No default folder to receive from");
}
folder.open(Folder.READ_WRITE);
}
private class MonitoringRunnable implements Runnable {
public void run() {
while (isRunning()) {
try {
Message[] newMessages = monitoringStrategy.getNewMessages(folder);
for (int i = 0; i < newMessages.length; i++) {
if (logger.isDebugEnabled()) {
if (newMessages[i] instanceof MimeMessage) {
MimeMessage mimeMessage = (MimeMessage) newMessages[i];
logger.debug("Received email message with MessageID " + mimeMessage.getMessageID());
}
}
MessageRequestHandler handler = new MessageRequestHandler(newMessages[i]);
getTaskExecutor().execute(handler);
}
}
catch (MessagingException ex) {
logger.warn(ex);
}
}
}
}
private class MessageRequestHandler implements Runnable {
private final Message message;
public MessageRequestHandler(Message message) {
this.message = message;
}
public void run() {
MailReceiverConnection connection = new MailReceiverConnection(message, session);
connection.setTransportUri(transportUri);
connection.setFrom(from);
try {
handleConnection(connection);
}
catch (Exception ex) {
logger.warn("Could not handle message", ex);
}
}
}
}

View File

@@ -1,104 +0,0 @@
/*
* 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.mail;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;
/**
* @author Arjen Poutsma
*/
public class MailMessageSender implements WebServiceMessageSender, InitializingBean {
private Session session = Session.getInstance(new Properties(), null);
private URLName storeUri;
private URLName transportUri;
private InternetAddress from;
public void setFrom(String from) throws AddressException {
this.from = new InternetAddress(from);
}
/**
* Set JavaMail properties for the {@link Session}.
* <p/>
* A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but
* not both.
* <p/>
* Non-default properties in this instance will override given JavaMail properties.
*/
public void setJavaMailProperties(Properties javaMailProperties) {
session = Session.getInstance(javaMailProperties, null);
}
/**
* Set the JavaMail <code>Session</code>, possibly pulled from JNDI.
* <p/>
* Default is a new <code>Session</code> without defaults, that is completely configured via this instance's
* properties.
* <p/>
* If using a pre-configured <code>Session</code>, non-default properties in this instance will override the
* settings in the <code>Session</code>.
*
* @see #setJavaMailProperties
*/
public void setSession(Session session) {
Assert.notNull(session, "Session must not be null");
this.session = session;
}
public void setStoreUri(String storeUri) {
this.storeUri = new URLName(storeUri);
}
public void setTransportUri(String transportUri) {
this.transportUri = new URLName(transportUri);
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(from, "Property 'from' is required");
}
public WebServiceConnection createConnection(String uri) throws IOException {
MailtoUri mailtoUri = new MailtoUri(uri);
MailSenderConnection connection = new MailSenderConnection(mailtoUri, session, from);
if (transportUri != null) {
connection.setTransportUri(transportUri);
}
if (storeUri != null) {
connection.setStoreUri(storeUri);
}
return connection;
}
public boolean supports(String uri) {
return StringUtils.hasLength(uri) && uri.startsWith(MailTransportConstants.URI_SCHEME + ":");
}
}

View File

@@ -1,205 +0,0 @@
/*
* 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.mail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import org.springframework.util.Assert;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.transport.AbstractReceiverConnection;
import org.springframework.ws.transport.TransportConstants;
import org.springframework.ws.transport.mail.support.MailUtils;
/**
* @author Arjen Poutsma
*/
public class MailReceiverConnection extends AbstractReceiverConnection {
private final Message requestMessage;
private final Session session;
private Message responseMessage;
private ByteArrayOutputStream responseBuffer;
private String responseContentType;
private URLName transportUri;
private InternetAddress from;
public MailReceiverConnection(Message requestMessage, Session session) {
Assert.notNull(requestMessage, "'requestMessage' must not be null");
Assert.notNull(session, "'session' must not be null");
this.requestMessage = requestMessage;
this.session = session;
}
public String getErrorMessage() throws IOException {
return null;
}
public boolean hasError() throws IOException {
return false;
}
public void setTransportUri(URLName transportUri) {
this.transportUri = transportUri;
}
public void close() throws IOException {
}
/*
* Receiving
*/
protected Iterator getRequestHeaderNames() throws IOException {
try {
List headers = new ArrayList();
Enumeration enumeration = requestMessage.getAllHeaders();
while (enumeration.hasMoreElements()) {
Header header = (Header) enumeration.nextElement();
headers.add(header.getName());
}
return headers.iterator();
}
catch (MessagingException ex) {
throw new IOException(ex.getMessage());
}
}
protected Iterator getRequestHeaders(String name) throws IOException {
try {
String[] headers = requestMessage.getHeader(name);
return Arrays.asList(headers).iterator();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected InputStream getRequestInputStream() throws IOException {
try {
return requestMessage.getInputStream();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected void addResponseHeader(String name, String value) throws IOException {
try {
responseMessage.addHeader(name, value);
if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) {
responseContentType = value;
}
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected OutputStream getResponseOutputStream() throws IOException {
return responseBuffer;
}
/*
* Sending
*/
protected void onSendBeforeWrite(WebServiceMessage message) throws IOException {
try {
responseMessage = requestMessage.reply(false);
responseMessage.setFrom(from);
responseBuffer = new ByteArrayOutputStream();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
Transport transport = null;
try {
responseMessage.setDataHandler(
new DataHandler(new ByteArrayDataSource(responseContentType, responseBuffer.toByteArray())));
transport = session.getTransport(transportUri);
transport.connect();
responseMessage.saveChanges();
transport.sendMessage(responseMessage, responseMessage.getAllRecipients());
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
finally {
MailUtils.closeService(transport);
}
}
public void setFrom(InternetAddress from) {
this.from = from;
}
private class ByteArrayDataSource implements DataSource {
private byte[] data;
private String contentType;
public ByteArrayDataSource(String contentType, byte[] data) {
this.data = data;
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
}
}

View File

@@ -1,291 +0,0 @@
/*
* 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.mail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.HeaderTerm;
import javax.mail.search.SearchTerm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.transport.AbstractSenderConnection;
import org.springframework.ws.transport.TransportConstants;
import org.springframework.ws.transport.mail.support.MailUtils;
/**
* @author Arjen Poutsma
*/
public class MailSenderConnection extends AbstractSenderConnection {
private static final Log logger = LogFactory.getLog(MailSenderConnection.class);
private final Session session;
private final MailtoUri uri;
private MimeMessage requestMessage;
private Message responseMessage;
private String requestContentType;
private boolean deleteAfterReceive = false;
private URLName storeUri;
private URLName transportUri;
private ByteArrayOutputStream requestBuffer;
private InternetAddress from;
protected MailSenderConnection(MailtoUri uri, Session session, InternetAddress from) {
Assert.notNull(uri, "'uri' must not be null");
Assert.notNull(session, "'session' must not be null");
this.uri = uri;
this.session = session;
this.from = from;
}
public Message getRequestMessage() {
return requestMessage;
}
public void setTransportUri(URLName transportUri) {
this.transportUri = transportUri;
}
public void setStoreUri(URLName storeUri) {
this.storeUri = storeUri;
}
/*
* Sending
*/
protected void onSendBeforeWrite(WebServiceMessage message) throws IOException {
try {
requestMessage = new MimeMessage(session);
requestMessage.setFrom(from);
requestMessage.setRecipient(Message.RecipientType.TO, uri.getTo());
if (uri.hasCc()) {
requestMessage.setRecipient(Message.RecipientType.CC, uri.getCc());
}
if (uri.hasSubject()) {
requestMessage.setSubject(uri.getSubject());
}
requestMessage.setSentDate(new Date());
requestBuffer = new ByteArrayOutputStream();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected void addRequestHeader(String name, String value) throws IOException {
try {
requestMessage.addHeader(name, value);
if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) {
requestContentType = value;
}
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected OutputStream getRequestOutputStream() throws IOException {
return requestBuffer;
}
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
Transport transport = null;
try {
requestMessage.setDataHandler(
new DataHandler(new ByteArrayDataSource(requestContentType, requestBuffer.toByteArray())));
transport = session.getTransport(transportUri);
transport.connect();
requestMessage.saveChanges();
transport.sendMessage(requestMessage, requestMessage.getAllRecipients());
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
finally {
MailUtils.closeService(transport);
}
}
/*
* Receiving
*/
protected void onReceiveBeforeRead() throws IOException {
Store store = null;
Folder folder = null;
try {
String requestMessageId = requestMessage.getMessageID();
if (StringUtils.hasLength(requestMessageId)) {
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
logger.debug(e);
}
store = session.getStore(storeUri);
store.connect();
folder = store.getFolder(storeUri);
if (folder == null || !folder.exists()) {
throw new MailTransportException("No default folder to receive from");
}
if (deleteAfterReceive) {
folder.open(Folder.READ_WRITE);
}
else {
folder.open(Folder.READ_ONLY);
}
SearchTerm searchTerm = new HeaderTerm(MailTransportConstants.HEADER_IN_REPLY_TO, requestMessageId);
Message[] responses = folder.search(searchTerm);
if (responses.length > 0) {
if (responses.length > 1) {
logger.warn("Received more than one response for request with ID [" + requestMessageId + "]");
}
responseMessage = responses[0];
}
if (deleteAfterReceive) {
responseMessage.setFlag(Flags.Flag.DELETED, true);
}
}
else {
logger.warn("Request message had no Message ID, could not find response");
}
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
finally {
MailUtils.closeFolder(folder, deleteAfterReceive);
MailUtils.closeService(store);
}
}
protected boolean hasResponse() throws IOException {
return responseMessage != null;
}
protected Iterator getResponseHeaderNames() throws IOException {
try {
List headers = new ArrayList();
Enumeration enumeration = responseMessage.getAllHeaders();
while (enumeration.hasMoreElements()) {
Header header = (Header) enumeration.nextElement();
headers.add(header.getName());
}
return headers.iterator();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected Iterator getResponseHeaders(String name) throws IOException {
try {
String[] headers = responseMessage.getHeader(name);
return Arrays.asList(headers).iterator();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
protected InputStream getResponseInputStream() throws IOException {
try {
return responseMessage.getDataHandler().getInputStream();
}
catch (MessagingException ex) {
throw new MailTransportException(ex);
}
}
public boolean hasError() throws IOException {
return false;
}
public String getErrorMessage() throws IOException {
return null;
}
public void close() throws IOException {
}
private class ByteArrayDataSource implements DataSource {
private byte[] data;
private String contentType;
public ByteArrayDataSource(String contentType, byte[] data) {
this.data = data;
this.contentType = contentType;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public OutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
public String getContentType() {
return contentType;
}
public String getName() {
return "ByteArrayDataSource";
}
}
}

View File

@@ -1,32 +0,0 @@
/*
* 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.mail;
import org.springframework.ws.transport.TransportConstants;
/**
* @author Arjen Poutsma
*/
public interface MailTransportConstants extends TransportConstants {
/**
* The "In-Reply-To" header.
*/
String HEADER_IN_REPLY_TO = "In-Reply-To";
String URI_SCHEME = "mailto";
}

View File

@@ -1,46 +0,0 @@
/*
* 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.mail;
import javax.jms.JMSException;
import javax.mail.MessagingException;
import org.springframework.ws.transport.TransportException;
/** @author Arjen Poutsma */
public class MailTransportException extends TransportException {
private MessagingException messagingException;
public MailTransportException(String msg) {
super(msg);
}
public MailTransportException(String msg, MessagingException ex) {
super(msg + ": " + ex.getMessage());
initCause(ex);
}
public MailTransportException(MessagingException ex) {
super(ex.getMessage());
initCause(ex);
}
public MessagingException getMessagingException() {
return messagingException;
}
}

View File

@@ -1,60 +0,0 @@
/*
* 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.mail;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.springframework.util.Assert;
import org.springframework.ws.transport.support.ParameterizedUri;
/**
* @author Arjen Poutsma
*/
public class MailtoUri extends ParameterizedUri {
public MailtoUri(String uri) {
super(uri);
Assert.isTrue(uri.startsWith(MailTransportConstants.URI_SCHEME), "Invalid uri: " + uri);
try {
InternetAddress.parse(getDestination(), false);
}
catch (AddressException ex) {
throw new IllegalArgumentException(ex);
}
}
public InternetAddress getTo() throws AddressException {
return new InternetAddress(getDestination());
}
public String getSubject() {
return getParameter("subject");
}
public boolean hasSubject() {
return hasParameter("subject");
}
public boolean hasCc() {
return hasParameter("cc");
}
public InternetAddress getCc() throws AddressException {
return new InternetAddress(getParameter("cc"));
}
}

View File

@@ -1,40 +0,0 @@
/*
* 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.mail;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
/**
* Defines the contract for objects that monitor a given folder for new messages. Allows for multiple implementation
* strategies, including polling, or event-driven techniques such as IMAP's <code>IDLE</code> command.
*
* @author Arjen Poutsma
*/
public interface MonitoringStrategy {
/**
* Return the new messages in a given JavaMail folder.
*
* @param folder the folder in which to look for new messages
* @return the new messages
* @throws MessagingException in case of JavaMail errors
*/
Message[] getNewMessages(Folder folder) throws MessagingException;
}

View File

@@ -1,82 +0,0 @@
/*
* 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.mail.support;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Service;
import javax.mail.Store;
import javax.mail.Transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** @author Arjen Poutsma */
public abstract class MailUtils {
private static final Log logger = LogFactory.getLog(MailUtils.class);
/**
* Close the given JavaMail Service and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param service the JavaMail Service to close (may be <code>null</code>)
* @see Transport
* @see Store
*/
public static void closeService(Service service) {
if (service != null) {
try {
service.close();
}
catch (MessagingException ex) {
logger.debug("Could not close JavaMail Transport", ex);
}
}
}
/**
* Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param folder the JavaMail Folder to close (may be <code>null</code>)
*/
public static void closeFolder(Folder folder) {
closeFolder(folder, false);
}
/**
* Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical <code>finally</code>
* blocks in manual JavaMail code.
*
* @param folder the JavaMail Folder to close (may be <code>null</code>)
* @param expunge whether all deleted messages should be expunged from the folder
*/
public static void closeFolder(Folder folder, boolean expunge) {
if (folder != null) {
try {
folder.close(expunge);
}
catch (MessagingException ex) {
logger.debug("Could not close JavaMail Transport", ex);
}
}
}
}

View File

@@ -1,80 +0,0 @@
/*
* 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 org.springframework.beans.factory.BeanNameAware;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.ClassUtils;
import org.springframework.scheduling.commonj.WorkManagerTaskExecutor;
/**
* Abstract base class for standalone, server-side transport objects. Contains a Spring {@link TaskExecutor}, and
* various lifecycle callbacks.
*
* @author Arjen Poutsma
*/
public abstract class AbstractMultiThreadedMessageReceiver extends AbstractStandaloneMessagingReceiver
implements BeanNameAware {
/** Default thread name prefix. */
public final String DEFAULT_THREAD_NAME_PREFIX = ClassUtils.getShortName(getClass()) + "-";
private TaskExecutor taskExecutor;
private String beanName;
/** Returns the task executor. */
public TaskExecutor getTaskExecutor() {
return taskExecutor;
}
/**
* Set the Spring {@link TaskExecutor} to use for running the listener threads. Default is {@link
* SimpleAsyncTaskExecutor}, starting up a number of new threads.
* <p/>
* Specify an alternative task executor for integration with an existing thread pool, such as the {@link
* WorkManagerTaskExecutor} to integrate with WebSphere or WebLogic.
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public void afterPropertiesSet() throws Exception {
if (taskExecutor == null) {
taskExecutor = createDefaultTaskExecutor();
}
super.afterPropertiesSet();
}
/**
* Create a default TaskExecutor. Called if no explicit TaskExecutor has been specified.
* <p/>
* The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the
* specified bean name (or the class name, if no bean name specified) as thread name prefix.
*
* @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String)
*/
protected TaskExecutor createDefaultTaskExecutor() {
String threadNamePrefix = beanName != null ? beanName + "-" : DEFAULT_THREAD_NAME_PREFIX;
return new SimpleAsyncTaskExecutor(threadNamePrefix);
}
}

View File

@@ -1,117 +0,0 @@
/*
* 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 org.springframework.beans.factory.DisposableBean;
import org.springframework.context.Lifecycle;
/** @author Arjen Poutsma */
public abstract class AbstractStandaloneMessagingReceiver extends SimpleWebServiceMessageReceiverObjectSupport
implements Lifecycle, DisposableBean {
private volatile boolean active = false;
private boolean autoStartup = true;
private boolean running = false;
private final Object lifecycleMonitor = new Object();
/** Return whether this server is currently active, that is, whether it has been set up but not shut down yet. */
public final boolean isActive() {
synchronized (lifecycleMonitor) {
return active;
}
}
/** Return whether this server is currently running, that is, whether it has been started and not stopped yet. */
public final boolean isRunning() {
synchronized (lifecycleMonitor) {
return running;
}
}
/**
* Set whether to automatically start the listener after initialization.
* <p/>
* Default is <code>true</code>; set this to <code>false</code> to allow for manual startup.
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
public void afterPropertiesSet() throws Exception {
activate();
}
/**
* Calls <code>shutdown</code> when the BeanFactory destroys the server instance.
*
* @see #shutdown()
*/
public void destroy() {
shutdown();
}
/** Initialize this server. Starts the server if <code>autoStartup</code> hasn't been turned off. */
public final void activate() throws Exception {
synchronized (lifecycleMonitor) {
active = true;
lifecycleMonitor.notifyAll();
}
onActivate();
if (autoStartup) {
start();
}
}
/** Start this server. */
public final void start() {
synchronized (lifecycleMonitor) {
running = true;
lifecycleMonitor.notifyAll();
}
onStart();
}
/** Stop this server. */
public final void stop() {
synchronized (lifecycleMonitor) {
running = false;
lifecycleMonitor.notifyAll();
}
onStop();
}
/** Shut down the registered listeners and close this listener container. */
public final void shutdown() {
synchronized (lifecycleMonitor) {
running = false;
active = false;
lifecycleMonitor.notifyAll();
}
onShutdown();
}
protected abstract void onActivate() throws Exception;
protected abstract void onStart();
protected abstract void onStop();
protected abstract void onShutdown();
}

View File

@@ -1,84 +0,0 @@
/*
* 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.Map;
import java.util.StringTokenizer;
import org.springframework.core.CollectionFactory;
import org.springframework.util.Assert;
/** @author Arjen Poutsma */
public class ParameterizedUri {
private final String uri;
private final String scheme;
// keys are string parameter names; values are string parameter values
private final Map parameters = CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(5);
private final String destination;
public ParameterizedUri(String uri) {
Assert.hasLength(uri, "'uri' must not be empty");
this.uri = uri;
int scIdx = uri.indexOf(':');
Assert.isTrue(scIdx != -1, uri + " does contain scheme");
scheme = uri.substring(0, scIdx);
Assert.isTrue(uri.length() > scheme.length(), uri + " does not have a destination");
int paramStart = uri.indexOf('?');
if (paramStart == -1) {
destination = uri.substring(scIdx + 1);
}
else {
destination = uri.substring(scIdx + 1, paramStart);
parseParameters(uri.substring(paramStart + 1));
}
}
private void parseParameters(String parametersString) {
StringTokenizer params = new StringTokenizer(parametersString, "&");
while (params.hasMoreTokens()) {
String param = params.nextToken();
int paramSep = param.indexOf('=');
if (paramSep == -1) {
throw new IllegalArgumentException(param + " is not a valid parameter: it has no '='");
}
String paramName = param.substring(0, paramSep);
String paramValue = param.substring(paramSep + 1);
parameters.put(paramName, paramValue);
}
}
/** Returns the destination of the uri. */
protected String getDestination() {
return destination;
}
public String toString() {
return uri;
}
protected String getParameter(String paramName) {
return (String) parameters.get(paramName);
}
protected boolean hasParameter(String paramName) {
return parameters.containsKey(paramName);
}
}

View File

@@ -1,59 +0,0 @@
/*
* 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 org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageReceiver;
/**
* Base class for server-side transport objects which have a predefined {@link WebServiceMessageReceiver}.
*
* @author Arjen Poutsma
* @see #handleConnection(WebServiceConnection)
* @since 1.1.0
*/
public abstract class SimpleWebServiceMessageReceiverObjectSupport extends WebServiceMessageReceiverObjectSupport
implements InitializingBean {
private WebServiceMessageReceiver messageReceiver;
/**
* Returns the <code>WebServiceMessageReceiver</code> used by this listener.
*/
public WebServiceMessageReceiver getMessageReceiver() {
return messageReceiver;
}
/**
* Sets the <code>WebServiceMessageReceiver</code> used by this listener.
*/
public void setMessageReceiver(WebServiceMessageReceiver messageReceiver) {
this.messageReceiver = messageReceiver;
}
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.notNull(getMessageReceiver(), "messageReceiver must not be null");
}
protected final void handleConnection(WebServiceConnection connection) throws Exception {
handleConnection(connection, getMessageReceiver());
}
}

View File

@@ -1,144 +0,0 @@
/*
* 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.tcp;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.support.AbstractMultiThreadedMessageReceiver;
/** @author Arjen Poutsma */
public class TcpMessageReceiver extends AbstractMultiThreadedMessageReceiver {
public static final int DEFAULT_PORT = 8081;
private ServerSocket serverSocket;
private InetAddress bindAddress;
private int backlog = -1;
private int port = DEFAULT_PORT;
/** Sets the port the server will bind to. */
public void setPort(int port) {
this.port = port;
}
/** Sets the server back log. */
public void setBacklog(int backlog) {
this.backlog = backlog;
}
/**
* Sets the local internet address the server will bind to. By default, it will accept connections on any/all local
* addresses.
*
* @throws java.net.UnknownHostException when the given address is not known
* @see java.net.ServerSocket#ServerSocket(int,int,java.net.InetAddress)
*/
public void setBindAddress(String bindAddress) throws UnknownHostException {
this.bindAddress = InetAddress.getByName(bindAddress);
}
protected void onActivate() throws IOException {
openServerSocket();
}
protected void onStart() {
if (logger.isInfoEnabled()) {
logger.info("Starting tcp receiver [" + serverSocket.getLocalSocketAddress() + "]");
}
getTaskExecutor().execute(new SocketAcceptingRunnable());
}
protected void onStop() {
if (logger.isInfoEnabled()) {
logger.info("Stopping tcp receiver [" + serverSocket.getLocalSocketAddress() + "]");
}
}
protected void onShutdown() {
if (logger.isInfoEnabled()) {
logger.info("Shutting down tcp receiver [" + serverSocket.getLocalSocketAddress() + "]");
}
closeServerSocket();
}
/**
* Establish a <code>ServerSocket</code> for this receiver.
*/
protected void openServerSocket() throws IOException {
closeServerSocket();
serverSocket = new ServerSocket(port, backlog, bindAddress);
}
protected void closeServerSocket() {
if (serverSocket == null) {
return;
}
try {
serverSocket.close();
}
catch (IOException ex) {
logger.debug("Could not close ServerSocket", ex);
}
}
private class SocketAcceptingRunnable implements Runnable {
public void run() {
while (isRunning()) {
try {
Socket socket = serverSocket.accept();
TcpRequestHandler handler = new TcpRequestHandler(socket);
getTaskExecutor().execute(handler);
}
catch (InterruptedIOException ex) {
logger.warn(ex);
}
catch (IOException ex) {
logger.warn("Could not accept incoming connection: " + ex.getMessage());
}
}
}
}
private class TcpRequestHandler implements Runnable {
private final Socket socket;
public TcpRequestHandler(Socket socket) {
this.socket = socket;
}
public void run() {
WebServiceConnection connection = new TcpReceiverConnection(socket);
try {
handleConnection(connection);
}
catch (Exception ex) {
logger.warn("Could not handle request", ex);
}
}
}
}

View File

@@ -1,65 +0,0 @@
/*
* 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.tcp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;
/** @author Arjen Poutsma */
public class TcpMessageSender implements WebServiceMessageSender {
private static final String TCP_SCHEME = "tcp://";
public static final int DEFAULT_PORT = 8081;
private int timeOut = 1000;
/** Sets the amount of milliseconds before the tcp connection will timeout. */
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public boolean supports(String uri) {
return StringUtils.hasLength(uri) && uri.startsWith(TCP_SCHEME);
}
public WebServiceConnection createConnection(String uri) throws IOException {
Assert.isTrue(uri.startsWith(TCP_SCHEME), "Invalid uri: " + uri);
uri = uri.substring(TCP_SCHEME.length());
int idx = uri.indexOf(':');
String hostname;
int port;
if (idx != -1) {
hostname = uri.substring(0, idx);
port = Integer.parseInt(uri.substring(idx + 1));
} else {
hostname = uri;
port = DEFAULT_PORT;
}
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(hostname, port);
socket.connect(socketAddress, timeOut);
return new TcpSenderConnection(socket);
}
}

View File

@@ -1,88 +0,0 @@
/*
* 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.tcp;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import org.springframework.util.Assert;
import org.springframework.ws.transport.AbstractReceiverConnection;
/** @author Arjen Poutsma */
public class TcpReceiverConnection extends AbstractReceiverConnection {
private final Socket socket;
protected TcpReceiverConnection(Socket socket) {
Assert.notNull(socket, "socket must not be null");
this.socket = socket;
}
public boolean hasError() throws IOException {
return false;
}
public String getErrorMessage() throws IOException {
return null;
}
public void close() throws IOException {
socket.close();
}
protected Iterator getRequestHeaderNames() throws IOException {
return Collections.EMPTY_LIST.iterator();
}
protected Iterator getRequestHeaders(String name) throws IOException {
return Collections.EMPTY_LIST.iterator();
}
protected InputStream getRequestInputStream() throws IOException {
return new FilterInputStream(socket.getInputStream()) {
public void close() throws IOException {
// don't close the socket
socket.shutdownInput();
}
};
}
protected void addResponseHeader(String name, String value) throws IOException {
}
protected OutputStream getResponseOutputStream() throws IOException {
return new FilterOutputStream(socket.getOutputStream()) {
public void close() throws IOException {
// don't close the socket
socket.shutdownOutput();
}
};
}
protected void sendResponse(boolean sentFault) throws IOException {
}
}

View File

@@ -1,90 +0,0 @@
/*
* 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.tcp;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import org.springframework.util.Assert;
import org.springframework.ws.transport.AbstractSenderConnection;
/** @author Arjen Poutsma */
public class TcpSenderConnection extends AbstractSenderConnection {
private final Socket socket;
protected TcpSenderConnection(Socket socket) {
Assert.notNull(socket, "socket must not be null");
this.socket = socket;
}
public void close() throws IOException {
socket.close();
}
public boolean hasError() throws IOException {
return false;
}
public String getErrorMessage() throws IOException {
return null;
}
protected void addRequestHeader(String name, String value) throws IOException {
}
protected OutputStream getRequestOutputStream() throws IOException {
return new FilterOutputStream(socket.getOutputStream()) {
public void close() throws IOException {
// don't close the socket
socket.shutdownOutput();
}
};
}
protected void sendRequest() throws IOException {
}
protected boolean hasResponse() throws IOException {
return true;
}
protected Iterator getResponseHeaderNames() throws IOException {
return Collections.EMPTY_LIST.iterator();
}
protected Iterator getResponseHeaders(String name) throws IOException {
return Collections.EMPTY_LIST.iterator();
}
protected InputStream getResponseInputStream() throws IOException {
return new FilterInputStream(socket.getInputStream()) {
public void close() throws IOException {
// don't close the socket
socket.shutdownInput();
}
};
}
}

View File

@@ -1,37 +0,0 @@
/*
* 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.tcp;
import java.io.IOException;
import org.springframework.ws.transport.TransportException;
/** @author Arjen Poutsma */
public class TcpTransportException extends TransportException {
public TcpTransportException(String msg) {
super(msg);
}
public TcpTransportException(String msg, IOException ex) {
super(msg + ": " + ex.getMessage());
}
public TcpTransportException(IOException ex) {
super(ex.getMessage());
}
}

View File

@@ -1,150 +0,0 @@
/*
* 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.oxm.support;
import javax.jms.BytesMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
public class MarshallingMessageConverterTest extends TestCase {
private MarshallingMessageConverter converter;
private MockControl marshallerControl;
private Marshaller marshallerMock;
private MockControl unmarshallerControl;
private Unmarshaller unmarshallerMock;
private MockControl sessionControl;
private Session sessionMock;
protected void setUp() throws Exception {
marshallerControl = MockControl.createControl(Marshaller.class);
marshallerMock = (Marshaller) marshallerControl.getMock();
unmarshallerControl = MockControl.createControl(Unmarshaller.class);
unmarshallerMock = (Unmarshaller) unmarshallerControl.getMock();
converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock);
sessionControl = MockControl.createControl(Session.class);
sessionMock = (Session) sessionControl.getMock();
}
public void testToBytesMessage() throws Exception {
MockControl bytesMessageControl = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessageMock = (BytesMessage) bytesMessageControl.getMock();
Object toBeMarshalled = new Object();
sessionControl.expectAndReturn(sessionMock.createBytesMessage(), bytesMessageMock);
marshallerMock.marshal(toBeMarshalled, new StringResult());
marshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
bytesMessageControl.replay();
converter.toMessage(toBeMarshalled, sessionMock);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
bytesMessageControl.verify();
}
public void testFromBytesMessage() throws Exception {
MockControl bytesMessageControl = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessageMock = (BytesMessage) bytesMessageControl.getMock();
Object unmarshalled = new Object();
unmarshallerMock.unmarshal(new StringSource(""));
unmarshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
unmarshallerControl.setReturnValue(unmarshalled);
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
bytesMessageControl.replay();
Object result = converter.fromMessage(bytesMessageMock);
assertEquals("Invalid result", result, unmarshalled);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
bytesMessageControl.verify();
}
public void testToTextMessage() throws Exception {
converter.setMarshalToTextMessage(true);
MockControl textMessageControl = MockControl.createControl(TextMessage.class);
TextMessage textMessageMock = (TextMessage) textMessageControl.getMock();
Object toBeMarshalled = new Object();
sessionControl.expectAndReturn(sessionMock.createTextMessage(), textMessageMock);
marshallerMock.marshal(toBeMarshalled, new StringResult());
marshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
textMessageMock.setText("");
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
textMessageControl.replay();
converter.toMessage(toBeMarshalled, sessionMock);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
textMessageControl.verify();
}
public void testFromTextMessage() throws Exception {
MockControl textMessageControl = MockControl.createControl(TextMessage.class);
TextMessage textMessageMock = (TextMessage) textMessageControl.getMock();
Object unmarshalled = new Object();
unmarshallerMock.unmarshal(new StringSource(""));
unmarshallerControl.setMatcher(MockControl.ALWAYS_MATCHER);
unmarshallerControl.setReturnValue(unmarshalled);
textMessageControl.expectAndReturn(textMessageMock.getText(), "");
marshallerControl.replay();
unmarshallerControl.replay();
sessionControl.replay();
textMessageControl.replay();
Object result = converter.fromMessage(textMessageMock);
assertEquals("Invalid result", result, unmarshalled);
marshallerControl.verify();
unmarshallerControl.verify();
sessionControl.verify();
textMessageControl.verify();
}
}

View File

@@ -1,104 +0,0 @@
/*
* 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.oxm.support;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.stream.StreamResult;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.oxm.Marshaller;
public class MarshallingViewTest extends TestCase {
private MarshallingView view;
private MockControl control;
private Marshaller marshallerMock;
protected void setUp() throws Exception {
control = MockControl.createControl(Marshaller.class);
marshallerMock = (Marshaller) control.getMock();
view = new MarshallingView(marshallerMock);
}
public void testGetContentType() {
assertEquals("Invalid content type", "text/xml", view.getContentType());
}
public void testRenderModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
view.setModelKey(modelKey);
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
marshallerMock.marshal(toBeMarshalled, new StreamResult(response.getOutputStream()));
control.setMatcher(MockControl.ALWAYS_MATCHER);
control.replay();
view.render(model, request, response);
control.verify();
}
public void testRenderNoModelKey() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), true);
marshallerMock.marshal(toBeMarshalled, new StreamResult(response.getOutputStream()));
control.setMatcher(MockControl.ALWAYS_MATCHER);
control.replay();
view.render(model, request, response);
control.verify();
}
public void testRenderUnsupportedModel() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map model = new HashMap();
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
control.expectAndReturn(marshallerMock.supports(Object.class), false);
control.replay();
try {
view.render(model, request, response);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// expected
}
control.verify();
}
}

View File

@@ -1,107 +0,0 @@
/*
* 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.jaxws;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Source;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;
import junit.framework.TestCase;
import org.springframework.ws.MockWebServiceMessage;
import org.springframework.ws.MockWebServiceMessageFactory;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
public class JaxWsProviderEndpointAdapterTest extends TestCase {
private JaxWsProviderEndpointAdapter adapter;
protected void setUp() throws Exception {
adapter = new JaxWsProviderEndpointAdapter();
}
public void testSupports() throws Exception {
MyMessageProvider messageProvider = new MyMessageProvider();
assertTrue("Does not support message provider", adapter.supports(messageProvider));
MySourceProvider sourceProvider = new MySourceProvider();
assertTrue("Does not support source provider", adapter.supports(sourceProvider));
MyDefaultProvider defaultProvider = new MyDefaultProvider();
assertTrue("Does not support source provider", adapter.supports(defaultProvider));
}
public void testInvokeMessageProvider() throws Exception {
MyMessageProvider provider = new MyMessageProvider();
MessageContext messageContext =
new DefaultMessageContext(new SaajSoapMessageFactory(MessageFactory.newInstance()));
adapter.invoke(messageContext, provider);
assertTrue("No response", messageContext.hasResponse());
SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest();
SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse();
assertEquals("Invalid response", request.getSaajMessage(), response.getSaajMessage());
}
public void testInvokeSourceProvider() throws Exception {
MySourceProvider provider = new MySourceProvider();
WebServiceMessage request = new MockWebServiceMessage("<contents/>");
MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory());
adapter.invoke(messageContext, provider);
assertTrue("No response", messageContext.hasResponse());
}
public void testInvokeDefaultProvider() throws Exception {
MyDefaultProvider provider = new MyDefaultProvider();
WebServiceMessage request = new MockWebServiceMessage("<contents/>");
MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory());
adapter.invoke(messageContext, provider);
assertTrue("No response", messageContext.hasResponse());
}
@WebServiceProvider
@ServiceMode(Service.Mode.MESSAGE)
private static class MyMessageProvider implements Provider<SOAPMessage> {
public SOAPMessage invoke(SOAPMessage request) {
return request;
}
}
@WebServiceProvider
@ServiceMode(value = Service.Mode.PAYLOAD)
private static class MySourceProvider implements Provider<Source> {
public Source invoke(Source request) {
return request;
}
}
@WebServiceProvider
private static class MyDefaultProvider implements Provider<Source> {
public Source invoke(Source request) {
return request;
}
}
}

View File

@@ -1,132 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing;
import java.util.Iterator;
import org.easymock.MockControl;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.addressing.messageid.MessageIdStrategy;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.transport.WebServiceConnection;
import org.springframework.ws.transport.WebServiceMessageSender;
public abstract class AbstractWsAddressingInterceptorTestCase extends AbstractWsAddressingTestCase {
protected WsAddressingInterceptor interceptor;
private MockControl strategyControl;
private MessageIdStrategy strategyMock;
protected final void onSetUp() throws Exception {
strategyControl = MockControl.createControl(MessageIdStrategy.class);
strategyMock = (MessageIdStrategy) strategyControl.getMock();
strategyControl.expectAndDefaultReturn(strategyMock.isDuplicate(null), false);
interceptor = new WsAddressingInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[0]);
}
public void testUnderstands() throws Exception {
SaajSoapMessage validRequest = loadSaajMessage(getTestPath() + "/valid.xml");
Iterator iterator = validRequest.getSoapHeader().examineAllHeaderElements();
strategyControl.replay();
while (iterator.hasNext()) {
SoapHeaderElement headerElement = (SoapHeaderElement) iterator.next();
assertTrue("Header [" + headerElement.getName() + " not understood",
interceptor.understands(headerElement));
}
strategyControl.verify();
}
public void testHandleValidRequest() throws Exception {
SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml");
MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory));
strategyControl.replay();
boolean result = interceptor.handleRequest(context, null);
assertTrue("Valid request not handled", result);
assertFalse("Message Context has response", context.hasResponse());
strategyControl.verify();
}
public void testHandleInvalidRequest() throws Exception {
SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/invalid.xml");
MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory));
strategyControl.replay();
boolean result = interceptor.handleRequest(context, null);
assertFalse("Invalid request handled", result);
assertTrue("Message Context has no response", context.hasResponse());
SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-invalid.xml");
assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse,
(SaajSoapMessage) context.getResponse());
strategyControl.verify();
}
public void testHandleAnonymousReplyTo() throws Exception {
SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/anonymous.xml");
MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory));
SaajSoapMessage response = (SaajSoapMessage) context.getResponse();
String messageId = "uid:1234";
strategyControl.expectAndReturn(strategyMock.newMessageId(response), messageId);
strategyControl.replay();
boolean result = interceptor.handleResponse(context, null);
assertTrue("Anonymous request not handled", result);
SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml");
assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse,
(SaajSoapMessage) context.getResponse());
strategyControl.verify();
}
public void testHandleNoneReplyTo() throws Exception {
SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/none.xml");
MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory));
strategyControl.replay();
boolean result = interceptor.handleResponse(context, null);
assertFalse("None request handled", result);
strategyControl.verify();
}
public void testHandleOutOfBandReplyTo() throws Exception {
MockControl senderControl = MockControl.createControl(WebServiceMessageSender.class);
WebServiceMessageSender senderMock = (WebServiceMessageSender) senderControl.getMock();
interceptor =
new WsAddressingInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[]{senderMock});
MockControl connectionControl = MockControl.createControl(WebServiceConnection.class);
WebServiceConnection connectionMock = (WebServiceConnection) connectionControl.getMock();
SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml");
MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory));
SaajSoapMessage response = (SaajSoapMessage) context.getResponse();
String messageId = "uid:1234";
strategyControl.expectAndReturn(strategyMock.newMessageId(response), messageId);
String uri = "http://example.com/business/client1";
senderControl.expectAndReturn(senderMock.supports(uri), true);
senderControl.expectAndReturn(senderMock.createConnection(uri), connectionMock);
connectionMock.send(response);
connectionMock.close();
strategyControl.replay();
senderControl.replay();
connectionControl.replay();
boolean result = interceptor.handleResponse(context, null);
assertFalse("Out of Band request handled", result);
strategyControl.verify();
senderControl.verify();
connectionControl.verify();
}
protected abstract WsAddressingVersion getVersion();
protected abstract String getTestPath();
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.w3c.dom.Document;
public abstract class AbstractWsAddressingTestCase extends XMLTestCase {
protected MessageFactory messageFactory;
protected final void setUp() throws Exception {
messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
XMLUnit.setIgnoreWhitespace(true);
onSetUp();
}
protected void onSetUp() throws Exception {
}
protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", " application/soap+xml");
InputStream is = getClass().getResourceAsStream(fileName);
assertNotNull("Could not load " + fileName, is);
try {
return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is));
}
finally {
is.close();
}
}
protected void assertXMLEqual(String message, SaajSoapMessage expected, SaajSoapMessage result) {
Document expectedDocument = expected.getSaajMessage().getSOAPPart();
Document resultDocument = result.getSaajMessage().getSOAPPart();
assertXMLEqual(message, expectedDocument, resultDocument);
}
}

View File

@@ -1,20 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing;
public class WsAddressingInterceptor200408Test extends AbstractWsAddressingInterceptorTestCase {
protected WsAddressingVersion getVersion() {
return new WsAddressing200408();
}
protected String getTestPath() {
return "200408";
}
public void testHandleNoneReplyTo() throws Exception {
// This version of the spec does not have none addresses
}
}

View File

@@ -1,16 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing;
public class WsAddressingInterceptor200605Test extends AbstractWsAddressingInterceptorTestCase {
protected WsAddressingVersion getVersion() {
return new WsAddressing200605();
}
protected String getTestPath() {
return "200508";
}
}

View File

@@ -1,27 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing.messageid;
import junit.framework.TestCase;
import org.springframework.util.StringUtils;
public abstract class AbstractMessageIdStrategyTestCase extends TestCase {
private MessageIdStrategy strategy;
protected final void setUp() throws Exception {
strategy = createProvider();
}
protected abstract MessageIdStrategy createProvider();
public void testProvider() {
String messageId1 = strategy.newMessageId(null);
assertTrue("Empty messageId", StringUtils.hasLength(messageId1));
String messageId2 = strategy.newMessageId(null);
assertTrue("Empty messageId", StringUtils.hasLength(messageId2));
assertFalse("Equal messageIds", messageId1.equals(messageId2));
}
}

View File

@@ -1,12 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing.messageid;
public class UidMessageIdStrategyTest extends AbstractMessageIdStrategyTestCase {
protected MessageIdStrategy createProvider() {
return new UidMessageIdStrategy();
}
}

View File

@@ -1,13 +0,0 @@
/*
* Copyright (c) 2007, Your Corporation. All Rights Reserved.
*/
package org.springframework.ws.soap.addressing.messageid;
public class UuidMessageIdStrategyTest extends AbstractMessageIdStrategyTestCase {
protected MessageIdStrategy createProvider() {
return new UuidMessageIdStrategy();
}
}

View File

@@ -1,34 +0,0 @@
/*
* 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;
import javax.xml.transform.Transformer;
import org.springframework.ws.context.MessageContext;
import org.springframework.xml.transform.TransformerObjectSupport;
import org.springframework.util.Assert;
public class SimpleTestingMessageReceiver extends TransformerObjectSupport implements WebServiceMessageReceiver {
public void receive(MessageContext messageContext) throws Exception {
Assert.notNull(messageContext, "MessageContext is null");
logger.info("Received message");
Transformer transformer = createTransformer();
transformer.transform(messageContext.getRequest().getPayloadSource(),
messageContext.getResponse().getPayloadResult());
}
}

View File

@@ -1,130 +0,0 @@
/*
* 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.jms;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.transport.WebServiceConnection;
public class JmsMessageSenderIntegrationTest extends AbstractDependencyInjectionSpringContextTests {
private JmsMessageSender messageSender;
private JmsTemplate jmsTemplate;
private MessageFactory messageFactory;
private static final String REQUEST_QUEUE_URI = "jms:RequestQueue";
private static final String SOAP_ACTION = "http://springframework.org/DoIt";
protected void onSetUp() throws Exception {
messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
}
protected String[] getConfigLocations() {
return new String[]{"classpath:org/springframework/ws/transport/jms/jms-sender-applicationContext.xml"};
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setMessageSender(JmsMessageSender messageSender) {
this.messageSender = messageSender;
}
public void testSendAndReceiveQueue() throws Exception {
WebServiceConnection connection = null;
try {
connection = messageSender.createConnection(REQUEST_QUEUE_URI);
SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage());
soapRequest.setSoapAction(SOAP_ACTION);
connection.send(soapRequest);
BytesMessage request = (BytesMessage) jmsTemplate.receive();
validateMessage(request);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
messageFactory.createMessage().writeTo(bos);
final byte[] buf = bos.toByteArray();
jmsTemplate.send(request.getJMSReplyTo(), new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
BytesMessage response = session.createBytesMessage();
response.setStringProperty(JmsTransportConstants.PROPERTY_BINDING_VERSION, "1.0");
response.setIntProperty(JmsTransportConstants.PROPERTY_CONTENT_LENGTH, buf.length);
response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, "text/xml");
response.setBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT, false);
response.setStringProperty(JmsTransportConstants.PROPERTY_REQUEST_IRI, REQUEST_QUEUE_URI);
response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION);
response.writeBytes(buf);
return response;
}
});
SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory));
assertNotNull("No response received", response);
assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction());
assertFalse("Message is fault", response.hasFault());
}
finally {
if (connection != null) {
connection.close();
}
}
}
private void validateMessage(BytesMessage message) throws JMSException, IOException {
assertEquals("Invalid SOAPAction", SOAP_ACTION,
message.getStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION));
assertEquals("Invalid binding version", "1.0",
message.getStringProperty(JmsTransportConstants.PROPERTY_BINDING_VERSION));
assertEquals("Invalid service IRI", REQUEST_QUEUE_URI,
message.getStringProperty(JmsTransportConstants.PROPERTY_REQUEST_IRI));
assertFalse("Message is Fault", message.getBooleanProperty(JmsTransportConstants.PROPERTY_IS_FAULT));
assertTrue("Invalid Content Type",
message.getStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE).indexOf("text/xml") != -1);
assertTrue("No Content Length", message.getIntProperty(JmsTransportConstants.PROPERTY_CONTENT_LENGTH) > 0);
assertTrue("Message has no contents", getMessageContents(message).length() > 0);
}
private String getMessageContents(BytesMessage message) throws JMSException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = message.readBytes(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
return out.toString("UTF-8");
}
}

View File

@@ -1,84 +0,0 @@
/*
* 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.jms;
import junit.framework.TestCase;
public class JmsUriTest extends TestCase {
public void testJmsUri() {
JmsUri uri = new JmsUri("jms:news?connectionFactoryName=SOAPJMSFactory&" + "deliveryMode=2&" +
"destinationType=topic&" + "initialContextFactory=com.sun.jndi.ldap.LdapCtxFactory&" +
"jndiURL=theJndiURL&" + "priority=8&" + "timeToLive=10&" + "replyToName=interested&" +
"userprop=mystuff");
assertEquals("Invalid delivery mode", 2, uri.getDeliveryMode());
assertEquals("Invalid destination", "news", uri.getDestination());
assertEquals("Invalid destination type", "topic", uri.getDestinationType());
assertTrue("Invalid pub sub domain", uri.isPubSubDomain());
assertEquals("Invalid prority", 8, uri.getPriority());
assertEquals("Invalid time to live", 10, uri.getTimeToLive());
assertEquals("Invalid reply to name", "interested", uri.getReplyTo());
}
public void testGetDestinationNoParams() {
JmsUri uri = new JmsUri("jms:news");
assertEquals("Invalid destination", "news", uri.getDestination());
}
public void testInvalidDeliveryMode() {
testIllegalArgument("jms:news?deliveryMode=abc");
}
public void testInvalidPriority() {
testIllegalArgument("jms:news?priority=abc");
}
public void testInvalidTimeToLive() {
testIllegalArgument("jms:news?timeToLive=abc");
}
public void testInvalidDestinationType() {
testIllegalArgument("jms:news?destinationType=abc");
}
public void testEmpty() {
testIllegalArgument("");
}
public void testInvalidScheme() {
testIllegalArgument("http://localhost");
}
public void testNoDestination() {
testIllegalArgument("jms:");
}
public void testIllegalParam() {
testIllegalArgument("jms:news?bla");
}
private void testIllegalArgument(String uri) {
try {
new JmsUri(uri);
fail("Expected IllegalArgumentException for uri [" + uri + "]");
}
catch (IllegalArgumentException ex) {
//expected
}
}
}

View File

@@ -1,116 +0,0 @@
/*
*/
/*
* Copyright 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.ws.transport.jms;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.StreamMessage;
import junit.framework.TestCase;
import org.codehaus.activemq.message.ActiveMQBytesMessage;
import org.codehaus.activemq.message.ActiveMQTopic;
import org.easymock.MockControl;
import org.springframework.ws.MockWebServiceMessageFactory;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.MessageEndpoint;
public class MessageEndpointMessageListenerTest extends TestCase {
private static final String REQUEST = " <SOAP-ENV:Envelope\n" +
" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <SOAP-ENV:Body>\n" +
" <m:GetLastTradePrice xmlns:m=\"Some-URI\">\n" + " <symbol>DIS</symbol>\n" +
" </m:GetLastTradePrice>\n" + " </SOAP-ENV:Body>\n" + "</SOAP-ENV:Envelope>";
private WebServiceMessageListener messageListener;
private BytesMessage request;
private MockControl sessionControl;
private Session sessionMock;
protected void setUp() throws Exception {
messageListener = new WebServiceMessageListener();
request = new ActiveMQBytesMessage();
request.writeBytes(REQUEST.getBytes("UTF-8"));
messageListener.setMessageFactory(new MockWebServiceMessageFactory());
sessionControl = MockControl.createControl(Session.class);
sessionMock = (Session) sessionControl.getMock();
}
public void testOnMessageInvalidMessage() throws Exception {
MockControl mockControl = MockControl.createControl(StreamMessage.class);
StreamMessage message = (StreamMessage) mockControl.getMock();
try {
messageListener.onMessage(message, sessionMock);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testOnMessageNoResponse() throws Exception {
MessageEndpoint endpoint = new MessageEndpoint() {
public void invoke(MessageContext messageContext) throws Exception {
}
};
messageListener.setMessageReceiver(endpoint);
request.reset();
messageListener.onMessage(request, sessionMock);
}
public void testOnMessageResponse() throws Exception {
MockControl producerControl = MockControl.createControl(MessageProducer.class);
MessageProducer producerMock = (MessageProducer) producerControl.getMock();
BytesMessage response = new ActiveMQBytesMessage();
String correlationId = "correlationId";
Destination replyTo = new ActiveMQTopic();
request.setJMSCorrelationID(correlationId);
request.setJMSReplyTo(replyTo);
request.reset();
sessionControl.expectAndReturn(sessionMock.createBytesMessage(), response);
sessionControl.expectAndReturn(sessionMock.createProducer(replyTo), producerMock);
producerMock.marshalSendAndReceive(response);
sessionControl.replay();
producerControl.replay();
MessageEndpoint endpoint = new MessageEndpoint() {
public void invoke(MessageContext messageContext) throws Exception {
messageContext.getResponse();
}
};
messageListener.setMessageReceiver(endpoint);
messageListener.onMessage(request, sessionMock);
sessionControl.verify();
producerControl.verify();
assertEquals("Invalid correlationId", correlationId, response.getJMSCorrelationID());
}
}*/

View File

@@ -1,95 +0,0 @@
/*
* 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.jms;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
public class WebServiceMessageListenerIntegrationTest extends AbstractDependencyInjectionSpringContextTests {
private static final String CONTENT =
"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>" + "<SOAP-ENV:Body>\n" +
"<m:GetLastTradePrice xmlns:m='http://www.springframework.org/spring-ws'>\n" +
"<symbol>DIS</symbol>\n" + "</m:GetLastTradePrice>\n" + "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
private JmsTemplate jmsTemplate;
private Queue responseQueue;
private Queue requestQueue;
private Topic requestTopic;
public WebServiceMessageListenerIntegrationTest() {
setAutowireMode(AUTOWIRE_BY_NAME);
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setRequestQueue(Queue requestQueue) {
this.requestQueue = requestQueue;
}
public void setRequestTopic(Topic requestTopic) {
this.requestTopic = requestTopic;
}
public void setResponseQueue(Queue responseQueue) {
this.responseQueue = responseQueue;
}
protected String[] getConfigLocations() {
return new String[]{"classpath:org/springframework/ws/transport/jms/jms-receiver-applicationContext.xml"};
}
public void testReceiveQueue() throws Exception {
final byte[] b = CONTENT.getBytes("UTF-8");
jmsTemplate.send(requestQueue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
BytesMessage request = session.createBytesMessage();
request.setJMSReplyTo(responseQueue);
request.writeBytes(b);
return request;
}
});
BytesMessage response = (BytesMessage) jmsTemplate.receive(responseQueue);
assertNotNull("No response received", response);
}
public void testReceiveTopic() throws Exception {
final byte[] b = CONTENT.getBytes("UTF-8");
jmsTemplate.send(requestTopic, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
BytesMessage request = session.createBytesMessage();
request.writeBytes(b);
return request;
}
});
Thread.sleep(100);
}
}

View File

@@ -1,28 +0,0 @@
/*
* 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.jms.support;
import junit.framework.TestCase;
import org.springframework.ws.transport.jms.support.JmsTransportUtils;
public class JmsTransportUtilsTest extends TestCase {
public void testHeaderToJmsProperty() throws Exception {
String result = JmsTransportUtils.headerToJmsProperty("SOAPAction");
assertEquals("Invalid result", "SOAPJMS_soapAction", result);
}
}

View File

@@ -1,36 +0,0 @@
/*
* 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.mail;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Arjen Poutsma
*/
public class Driver {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml", Driver.class);
context.registerShutdownHook();
System.out.println("Started....");
System.in.read();
}
}

View File

@@ -1,64 +0,0 @@
/*
* 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.mail;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPMessage;
import junit.framework.TestCase;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.ws.transport.WebServiceConnection;
public class MailMessageSenderIntegrationTest extends TestCase {
private MailMessageSender messageSender;
private MessageFactory messageFactory;
private static final String URI = "mailto:ajwpi21@xs4all.nl?subject=SOAP Test";
// private static final String URI = "mailto:revans@interface21.com?subject=Believe me now?";
private static final String SOAP_ACTION = "http://springframework.org/DoIt";
protected void setUp() throws Exception {
messageSender = new MailMessageSender();
messageSender.setFrom("Arjen Poutsma <ajwp@xs4all.nl>");
messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
}
public void testSendAndReceiveQueueNoResponse() throws Exception {
WebServiceConnection connection = null;
try {
connection = messageSender.createConnection(URI);
SOAPMessage saajMessage = messageFactory.createMessage();
saajMessage.getSOAPBody().addBodyElement(new QName("http://springframework.org", "test"));
SoapMessage soapRequest = new SaajSoapMessage(saajMessage);
soapRequest.setSoapAction(SOAP_ACTION);
connection.send(soapRequest);
// SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory));
}
finally {
if (connection != null) {
connection.close();
}
}
}
}

View File

@@ -1,33 +0,0 @@
/*
* 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.tcp;
import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/** @author Arjen Poutsma */
public class Driver {
public static void main(String[] args) throws IOException {
new ClassPathXmlApplicationContext("applicationContext.xml", Driver.class);
System.out.println("Started....");
System.in.read();
}
}

View File

@@ -1,87 +0,0 @@
/*
* 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.tcp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import javax.xml.transform.stream.StreamResult;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.WebServiceMessageSender;
import org.springframework.xml.transform.StringSource;
public class TcpMessageReceiverIntegrationTest extends AbstractDependencyInjectionSpringContextTests {
private WebServiceMessageFactory messageFactory;
private WebServiceMessageSender messageSender;
public void setMessageFactory(WebServiceMessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
public void setMessageSender(WebServiceMessageSender messageSender) {
this.messageSender = messageSender;
}
public static final String REQUEST =
"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'\n" +
" SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>\n" +
" <SOAP-ENV:Body>\n" +
" <m:GetLastTradePrice xmlns:m='http://www.springframework.org/spring-ws'>\n" +
" <symbol>DIS</symbol>\n" + " </m:GetLastTradePrice>\n" +
" </SOAP-ENV:Body>\n" + "</SOAP-ENV:Envelope>";
public void testServer() throws IOException, InterruptedException {
Socket socket = new Socket("localhost", TcpMessageReceiver.DEFAULT_PORT);
Writer writer;
BufferedReader reader;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
writer.write(REQUEST);
writer.flush();
socket.shutdownOutput();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
finally {
socket.close();
}
}
public void testTemplate() throws Exception {
WebServiceTemplate template = new WebServiceTemplate(messageFactory);
template.setMessageSender(messageSender);
template.sendSourceAndReceiveToResult("tcp://localhost", new StringSource(REQUEST),
new StreamResult(System.out));
}
protected String[] getConfigLocations() {
return new String[]{"classpath:/org/springframework/ws/transport/tcp/applicationContext.xml"};
}
}

View File

@@ -1,7 +0,0 @@
log4j.rootCategory=WARN, stdout
log4j.logger.org.springframework.ws=DEBUG
log4j.logger.org.springframework.jms=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

View File

@@ -1,17 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:f123="http://www.fabrikam123.example/svc53">
<S:Header>
<wsa:MessageID>uuid:aaaabbbb-cccc-dddd-eeee-ffffffffffff</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsa:To S:mustUnderstand="1">mailto:joe@fabrikam123.example</wsa:To>
<wsa:Action>http://fabrikam123.example/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f123:Delete>
<maxCount>42</maxCount>
</f123:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,17 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:f123="http://www.fabrikam123.example/svc53">
<S:Header>
<!--<wsa:MessageID>uuid:aaaabbbb-cccc-dddd-eeee-ffffffffffff</wsa:MessageID>-->
<wsa:ReplyTo>
<wsa:Address>http://business456.example/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To S:mustUnderstand="1">mailto:joe@fabrikam123.example</wsa:To>
<wsa:Action>http://fabrikam123.example/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f123:Delete>
<maxCount>42</maxCount>
</f123:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,9 +0,0 @@
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<env:Header>
<wsa:MessageID>uid:1234</wsa:MessageID>
<wsa:RelatesTo>uuid:aaaabbbb-cccc-dddd-eeee-ffffffffffff</wsa:RelatesTo>
<wsa:To env:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
</env:Header>
<env:Body/>
</env:Envelope>

View File

@@ -1,19 +0,0 @@
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<env:Header/>
<env:Body>
<env:Fault>
<env:Code>
<env:Value>env:Sender</env:Value>
<env:Subcode>
<env:Value>wsa:MessageInformationHeaderRequired</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en">
A required message information header, To, MessageID, or Action, is not present.
</env:Text>
</env:Reason>
</env:Fault>
</env:Body>
</env:Envelope>

View File

@@ -1,17 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:f123="http://www.fabrikam123.example/svc53">
<S:Header>
<wsa:MessageID>uuid:aaaabbbb-cccc-dddd-eeee-ffffffffffff</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://example.com/business/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To S:mustUnderstand="1">mailto:joe@fabrikam123.example</wsa:To>
<wsa:Action>http://fabrikam123.example/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f123:Delete>
<maxCount>42</maxCount>
</f123:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,15 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<S:Header>
<wsa:MessageID>http://example.com/someuniquestring</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsa:To>mailto:fabrikam@example.com</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<maxCount>42</maxCount>
</f:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,15 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<S:Header>
<!--<wsa:MessageID>http://example.com/someuniquestring</wsa:MessageID>-->
<wsa:ReplyTo>
<wsa:Address>http://example.com/business/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To>mailto:fabrikam@example.com</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<maxCount>42</maxCount>
</f:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,15 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<S:Header>
<wsa:MessageID>http://example.com/someuniquestring</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://www.w3.org/2005/08/addressing/none</wsa:Address>
</wsa:ReplyTo>
<wsa:To>mailto:fabrikam@example.com</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<maxCount>42</maxCount>
</f:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,8 +0,0 @@
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>
<wsa:MessageID>uid:1234</wsa:MessageID>
<wsa:RelatesTo>http://example.com/someuniquestring</wsa:RelatesTo>
<wsa:To env:mustUnderstand="true">http://www.w3.org/2005/08/addressing/anonymous</wsa:To>
</env:Header>
<env:Body/>
</env:Envelope>

View File

@@ -1,19 +0,0 @@
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<env:Header/>
<env:Body>
<env:Fault>
<env:Code>
<env:Value>env:Sender</env:Value>
<env:Subcode>
<env:Value>wsa:MessageAddressingHeaderRequired</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en">
A required header representing a Message Addressing Property is not present
</env:Text>
</env:Reason>
</env:Fault>
</env:Body>
</env:Envelope>

View File

@@ -1,15 +0,0 @@
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<S:Header>
<wsa:MessageID>http://example.com/someuniquestring</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://example.com/business/client1</wsa:Address>
</wsa:ReplyTo>
<wsa:To>mailto:fabrikam@example.com</wsa:To>
<wsa:Action>http://example.com/fabrikam/mail/Delete</wsa:Action>
</S:Header>
<S:Body>
<f:Delete xmlns:f="http://example.com/fabrikam">
<maxCount>42</maxCount>
</f:Delete>
</S:Body>
</S:Envelope>

View File

@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue">
<property name="physicalName" value="RequestQueue"/>
</bean>
<bean id="requestTopic" class="org.apache.activemq.command.ActiveMQTopic">
<property name="physicalName" value="RequestTopic"/>
</bean>
<bean id="responseQueue" class="org.apache.activemq.command.ActiveMQQueue">
<property name="physicalName" value="ResponseQueue"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="requestQueue"/>
<property name="messageListener" ref="messageListener"/>
</bean>
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="requestTopic"/>
<property name="messageListener" ref="messageListener"/>
</bean>
<bean id="messageListener" class="org.springframework.ws.transport.jms.WebServiceMessageListener">
<property name="messageFactory">
<bean class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
</property>
<property name="messageReceiver" ref="messageReceiver"/>
</bean>
<bean id="messageReceiver" class="org.springframework.ws.transport.SimpleTestingMessageReceiver"/>
</beans>

View File

@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue">
<property name="physicalName" value="RequestQueue"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="requestQueue"/>
</bean>
<bean id="messageSender" class="org.springframework.ws.transport.jms.JmsMessageSender">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="receiveTimeout" value="10"/>
</bean>
</beans>

View File

@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="messagingReceiver" class="org.springframework.ws.transport.mail.MailMessageReceiver">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver">
<bean class="org.springframework.ws.transport.SimpleTestingMessageReceiver"/>
</property>
<property name="monitoringStrategy">
<bean class="org.springframework.ws.transport.mail.DefaultMonitoringStrategy">
<property name="pollingInterval" value="10000"/>
</bean>
</property>
</bean>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="mbeanExporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="spring-ws:service=messagingContainer">
<ref local="messagingReceiver"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="interfaceMappings">
<props>
<prop key="spring-ws:service=messagingContainer">org.springframework.context.Lifecycle</prop>
</props>
</property>
</bean>
</property>
</bean>
</beans>

View File

@@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="messagingReceiver" class="org.springframework.ws.transport.tcp.TcpMessageReceiver">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver">
<bean class="org.springframework.ws.transport.SimpleTestingMessageReceiver"/>
</property>
</bean>
<bean id="tcpSender" class="org.springframework.ws.transport.tcp.TcpMessageSender" />
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<!-- define an MBeanExporter -->
<bean id="mbeanExporter" class="org.springframework.jmx.export.MBeanExporter">
<!-- the beans to be exported to JMX -->
<property name="beans">
<map>
<entry key="spring-ws:service=messagingContainer">
<ref local="messagingReceiver"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="interfaceMappings">
<props>
<prop key="spring-ws:service=messagingContainer">org.springframework.context.Lifecycle</prop>
</props>
</property>
</bean>
</property>
</bean>
</beans>