Converted spaces to tabs

This commit changes leading spaces in all Java source files to tabs, to
be consistent with other Spring projects.
This commit is contained in:
Arjen Poutsma
2015-03-18 09:33:06 +01:00
parent b6500fe5ac
commit 7d64bebd19
824 changed files with 46904 additions and 46904 deletions

View File

@@ -28,13 +28,13 @@ import javax.xml.namespace.QName;
*/
public interface FaultAwareWebServiceMessage extends WebServiceMessage {
/**
* Does this message have a fault?
*
* @return {@code true} if the message has a fault.
* @see #getFaultReason()
*/
boolean hasFault();
/**
* Does this message have a fault?
*
* @return {@code true} if the message has a fault.
* @see #getFaultReason()
*/
boolean hasFault();
/**
* Returns the fault code, if any.
@@ -42,11 +42,11 @@ public interface FaultAwareWebServiceMessage extends WebServiceMessage {
QName getFaultCode();
/**
* Returns the fault reason message.
*
* @return the fault reason message, if any; returns {@code null} when no fault is present.
* @see #hasFault()
*/
String getFaultReason();
/**
* Returns the fault reason message.
*
* @return the fault reason message, if any; returns {@code null} when no fault is present.
* @see #hasFault()
*/
String getFaultReason();
}

View File

@@ -26,7 +26,7 @@ package org.springframework.ws;
@SuppressWarnings("serial")
public final class InvalidXmlException extends WebServiceException {
public InvalidXmlException(String msg, Throwable ex) {
super(msg, ex);
}
public InvalidXmlException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -25,7 +25,7 @@ package org.springframework.ws;
@SuppressWarnings("serial")
public final class NoEndpointFoundException extends WebServiceException {
public NoEndpointFoundException(WebServiceMessage request) {
super("No endpoint can be found for request [" + request + "]");
}
public NoEndpointFoundException(WebServiceMessage request) {
super("No endpoint can be found for request [" + request + "]");
}
}

View File

@@ -27,23 +27,23 @@ import org.springframework.core.NestedRuntimeException;
@SuppressWarnings("serial")
public abstract class WebServiceException extends NestedRuntimeException {
/**
* Create a new instance of the {@code WebServiceException} class.
*
* @param msg the detail message
*/
public WebServiceException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceException} class.
*
* @param msg the detail message
*/
public WebServiceException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceException(String msg, Throwable ex) {
super(msg, ex);
}
/**
* Create a new instance of the {@code WebServiceException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -33,35 +33,35 @@ import javax.xml.transform.Source;
*/
public interface WebServiceMessage {
/**
* Returns the contents of the message as a {@link Source}.
*
* <p>Depending on the implementation, this can be retrieved multiple times, or just
* a single time.
*
* @return the message contents
*/
Source getPayloadSource();
/**
* Returns the contents of the message as a {@link Source}.
*
* <p>Depending on the implementation, this can be retrieved multiple times, or just
* a single time.
*
* @return the message contents
*/
Source getPayloadSource();
/**
* Returns the contents of the message as a {@link Result}.
*
* <p>Calling this method removes the current payload.
*
* <p>Implementations that are read-only will throw an {@link UnsupportedOperationException}.
*
* @return the message contents
* @throws UnsupportedOperationException if the message is read-only
*/
Result getPayloadResult();
/**
* Returns the contents of the message as a {@link Result}.
*
* <p>Calling this method removes the current payload.
*
* <p>Implementations that are read-only will throw an {@link UnsupportedOperationException}.
*
* @return the message contents
* @throws UnsupportedOperationException if the message is read-only
*/
Result getPayloadResult();
/**
* Writes the entire message to the given output stream. <p>If the given stream is an instance of {@link
* org.springframework.ws.transport.TransportOutputStream}, the corresponding headers will be written as well.
*
* @param outputStream the stream to write to
* @throws IOException if an I/O exception occurs
*/
void writeTo(OutputStream outputStream) throws IOException;
/**
* Writes the entire message to the given output stream. <p>If the given stream is an instance of {@link
* org.springframework.ws.transport.TransportOutputStream}, the corresponding headers will be written as well.
*
* @param outputStream the stream to write to
* @throws IOException if an I/O exception occurs
*/
void writeTo(OutputStream outputStream) throws IOException;
}

View File

@@ -25,13 +25,13 @@ package org.springframework.ws;
@SuppressWarnings("serial")
public abstract class WebServiceMessageException extends WebServiceException {
/** Constructor for {@code WebServiceMessageException}. */
public WebServiceMessageException(String msg) {
super(msg);
}
/** Constructor for {@code WebServiceMessageException}. */
public WebServiceMessageException(String msg) {
super(msg);
}
/** Constructor for {@code WebServiceMessageException}. */
public WebServiceMessageException(String msg, Throwable ex) {
super(msg, ex);
}
/** Constructor for {@code WebServiceMessageException}. */
public WebServiceMessageException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -31,24 +31,24 @@ import java.io.InputStream;
*/
public interface WebServiceMessageFactory {
/**
* Creates a new, empty {@code WebServiceMessage}.
*
* @return the empty message
*/
WebServiceMessage createWebServiceMessage();
/**
* Creates a new, empty {@code WebServiceMessage}.
*
* @return the empty message
*/
WebServiceMessage createWebServiceMessage();
/**
* Reads a {@link WebServiceMessage} from the given input stream.
*
* <p>If the given stream is an instance of {@link org.springframework.ws.transport.TransportInputStream
* TransportInputStream}, the headers will be read from the request.
*
* @param inputStream the input stream to read the message from
* @return the created message
* @throws InvalidXmlException if the XML read from the input stream is invalid
* @throws IOException if an I/O exception occurs
*/
WebServiceMessage createWebServiceMessage(InputStream inputStream) throws InvalidXmlException, IOException;
/**
* Reads a {@link WebServiceMessage} from the given input stream.
*
* <p>If the given stream is an instance of {@link org.springframework.ws.transport.TransportInputStream
* TransportInputStream}, the headers will be read from the request.
*
* @param inputStream the input stream to read the message from
* @return the created message
* @throws InvalidXmlException if the XML read from the input stream is invalid
* @throws IOException if an I/O exception occurs
*/
WebServiceMessage createWebServiceMessage(InputStream inputStream) throws InvalidXmlException, IOException;
}

View File

@@ -27,23 +27,23 @@ import org.springframework.ws.WebServiceException;
@SuppressWarnings("serial")
public abstract class WebServiceClientException extends WebServiceException {
/**
* Create a new instance of the {@code WebServiceClientException} class.
*
* @param msg the detail message
*/
public WebServiceClientException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceClientException} class.
*
* @param msg the detail message
*/
public WebServiceClientException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceClientException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceClientException(String msg, Throwable ex) {
super(msg, ex);
}
/**
* Create a new instance of the {@code WebServiceClientException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceClientException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -27,26 +27,26 @@ import org.springframework.ws.FaultAwareWebServiceMessage;
@SuppressWarnings("serial")
public class WebServiceFaultException extends WebServiceClientException {
private final FaultAwareWebServiceMessage faultMessage;
private final FaultAwareWebServiceMessage faultMessage;
/** Create a new instance of the {@code WebServiceFaultException} class. */
public WebServiceFaultException(String msg) {
super(msg);
faultMessage = null;
}
/** Create a new instance of the {@code WebServiceFaultException} class. */
public WebServiceFaultException(String msg) {
super(msg);
faultMessage = null;
}
/**
* Create a new instance of the {@code WebServiceFaultException} class.
*
* @param faultMessage the fault message
*/
public WebServiceFaultException(FaultAwareWebServiceMessage faultMessage) {
super(faultMessage.getFaultReason());
this.faultMessage = faultMessage;
}
/**
* Create a new instance of the {@code WebServiceFaultException} class.
*
* @param faultMessage the fault message
*/
public WebServiceFaultException(FaultAwareWebServiceMessage faultMessage) {
super(faultMessage.getFaultReason());
this.faultMessage = faultMessage;
}
/** Returns the fault message. */
public FaultAwareWebServiceMessage getWebServiceMessage() {
return faultMessage;
}
/** Returns the fault message. */
public FaultAwareWebServiceMessage getWebServiceMessage() {
return faultMessage;
}
}

View File

@@ -27,23 +27,23 @@ import java.io.IOException;
@SuppressWarnings("serial")
public class WebServiceIOException extends WebServiceClientException {
/**
* Create a new instance of the {@code WebServiceIOException} class.
*
* @param msg the detail message
*/
public WebServiceIOException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceIOException} class.
*
* @param msg the detail message
*/
public WebServiceIOException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceIOException} class.
*
* @param msg the detail message
* @param ex the root {@link IOException}
*/
public WebServiceIOException(String msg, IOException ex) {
super(msg, ex);
}
/**
* Create a new instance of the {@code WebServiceIOException} class.
*
* @param msg the detail message
* @param ex the root {@link IOException}
*/
public WebServiceIOException(String msg, IOException ex) {
super(msg, ex);
}
}

View File

@@ -27,23 +27,23 @@ import javax.xml.transform.TransformerException;
@SuppressWarnings("serial")
public class WebServiceTransformerException extends WebServiceClientException {
/**
* Create a new instance of the {@code WebServiceTransformerException} class.
*
* @param msg the detail message
*/
public WebServiceTransformerException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceTransformerException} class.
*
* @param msg the detail message
*/
public WebServiceTransformerException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceTransformerException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceTransformerException(String msg, TransformerException ex) {
super(msg, ex);
}
/**
* Create a new instance of the {@code WebServiceTransformerException} class.
*
* @param msg the detail message
* @param ex the root {@link Throwable exception}
*/
public WebServiceTransformerException(String msg, TransformerException ex) {
super(msg, ex);
}
}

View File

@@ -27,23 +27,23 @@ import org.springframework.ws.transport.TransportException;
@SuppressWarnings("serial")
public class WebServiceTransportException extends WebServiceIOException {
/**
* Create a new instance of the {@code WebServiceTransportException} class.
*
* @param msg the detail message
*/
public WebServiceTransportException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceTransportException} class.
*
* @param msg the detail message
*/
public WebServiceTransportException(String msg) {
super(msg);
}
/**
* Create a new instance of the {@code WebServiceTransportException} class.
*
* @param msg the detail message
* @param ex the root {@link TransportException}
*/
public WebServiceTransportException(String msg, TransportException ex) {
super(msg, ex);
}
/**
* Create a new instance of the {@code WebServiceTransportException} class.
*
* @param msg the detail message
* @param ex the root {@link TransportException}
*/
public WebServiceTransportException(String msg, TransportException ex) {
super(msg, ex);
}
}

View File

@@ -28,11 +28,11 @@ import org.springframework.ws.WebServiceMessage;
*/
public interface FaultMessageResolver {
/**
* Try to resolve the given fault message that got received.
*
* @param message the fault message
*/
void resolveFault(WebServiceMessage message) throws IOException;
/**
* Try to resolve the given fault message that got received.
*
* @param message the fault message
*/
void resolveFault(WebServiceMessage message) throws IOException;
}

View File

@@ -29,14 +29,14 @@ import org.springframework.ws.client.WebServiceFaultException;
*/
public class SimpleFaultMessageResolver implements FaultMessageResolver {
/** Throws a new {@code WebServiceFaultException}. */
@Override
public void resolveFault(WebServiceMessage message) {
if (message instanceof FaultAwareWebServiceMessage) {
throw new WebServiceFaultException((FaultAwareWebServiceMessage) message);
}
else {
throw new WebServiceFaultException("Message has unknown fault: " + message);
}
}
/** Throws a new {@code WebServiceFaultException}. */
@Override
public void resolveFault(WebServiceMessage message) {
if (message instanceof FaultAwareWebServiceMessage) {
throw new WebServiceFaultException((FaultAwareWebServiceMessage) message);
}
else {
throw new WebServiceFaultException("Message has unknown fault: " + message);
}
}
}

View File

@@ -37,14 +37,14 @@ import javax.xml.transform.TransformerException;
*/
public interface SourceExtractor<T> {
/**
* Process the data in the given {@code Source}, creating a corresponding result object.
*
* @param source the message payload to extract data from
* @return an arbitrary result object, or {@code null} if none (the extractor will typically be stateful in the
* latter case)
* @throws IOException in case of I/O errors
*/
T extractData(Source source) throws IOException, TransformerException;
/**
* Process the data in the given {@code Source}, creating a corresponding result object.
*
* @param source the message payload to extract data from
* @return an arbitrary result object, or {@code null} if none (the extractor will typically be stateful in the
* latter case)
* @throws IOException in case of I/O errors
*/
T extractData(Source source) throws IOException, TransformerException;
}

View File

@@ -32,13 +32,13 @@ import org.springframework.ws.WebServiceMessage;
*/
public interface WebServiceMessageCallback {
/**
* Execute any number of operations on the supplied {@code message}.
*
* @param message the message
* @throws IOException in case of I/O errors
* @throws TransformerException in case of transformation errors
*/
void doWithMessage(WebServiceMessage message) throws IOException, TransformerException;
/**
* Execute any number of operations on the supplied {@code message}.
*
* @param message the message
* @throws IOException in case of I/O errors
* @throws TransformerException in case of transformation errors
*/
void doWithMessage(WebServiceMessage message) throws IOException, TransformerException;
}

View File

@@ -37,15 +37,15 @@ import org.springframework.ws.WebServiceMessage;
*/
public interface WebServiceMessageExtractor<T> {
/**
* Process the data in the given {@code WebServiceMessage}, creating a corresponding result object.
*
* @param message the message to extract data from (possibly a {@code SoapMessage})
* @return an arbitrary result object, or {@code null} if none (the extractor will typically be stateful in the
* latter case)
* @throws IOException in case of I/O errors
* @throws TransformerException in case of transformation errors
*/
T extractData(WebServiceMessage message) throws IOException, TransformerException;
/**
* Process the data in the given {@code WebServiceMessage}, creating a corresponding result object.
*
* @param message the message to extract data from (possibly a {@code SoapMessage})
* @return an arbitrary result object, or {@code null} if none (the extractor will typically be stateful in the
* latter case)
* @throws IOException in case of I/O errors
* @throws TransformerException in case of transformation errors
*/
T extractData(WebServiceMessage message) throws IOException, TransformerException;
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -32,262 +32,262 @@ import org.springframework.ws.client.WebServiceClientException;
*/
public interface WebServiceOperations {
/**
* Sends a web service message that can be manipulated with the given callback, reading the result with a
* {@code WebServiceMessageExtractor}.
*
* <p>This will only work with a default uri specified!
*
* @param requestCallback the requestCallback to be used for manipulating the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code WebServiceMessageExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given callback, reading the result with a
* {@code WebServiceMessageExtractor}.
*
* <p>This will only work with a default uri specified!
*
* @param requestCallback the requestCallback to be used for manipulating the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code WebServiceMessageExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given callback, reading the result with a
* {@code WebServiceMessageExtractor}.
*
* @param uri the URI to send the message to
* @param requestCallback the requestCallback to be used for manipulating the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code WebServiceMessageExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendAndReceive(String uri,
WebServiceMessageCallback requestCallback,
WebServiceMessageExtractor<T> responseExtractor) throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given callback, reading the result with a
* {@code WebServiceMessageExtractor}.
*
* @param uri the URI to send the message to
* @param requestCallback the requestCallback to be used for manipulating the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code WebServiceMessageExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendAndReceive(String uri,
WebServiceMessageCallback requestCallback,
WebServiceMessageExtractor<T> responseExtractor) throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given request callback, handling the response with a
* response callback.
*
* <p>This will only work with a default uri specified!
*
* @param requestCallback the callback to be used for manipulating the request message
* @param responseCallback the callback to be used for manipulating the response message
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageCallback responseCallback)
throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given request callback, handling the response with a
* response callback.
*
* <p>This will only work with a default uri specified!
*
* @param requestCallback the callback to be used for manipulating the request message
* @param responseCallback the callback to be used for manipulating the response message
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageCallback responseCallback)
throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given request callback, handling the response with a
* response callback.
*
* @param uri the URI to send the message to
* @param requestCallback the callback to be used for manipulating the request message
* @param responseCallback the callback to be used for manipulating the response message
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendAndReceive(String uri,
WebServiceMessageCallback requestCallback,
WebServiceMessageCallback responseCallback) throws WebServiceClientException;
/**
* Sends a web service message that can be manipulated with the given request callback, handling the response with a
* response callback.
*
* @param uri the URI to send the message to
* @param requestCallback the callback to be used for manipulating the request message
* @param responseCallback the callback to be used for manipulating the response message
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendAndReceive(String uri,
WebServiceMessageCallback requestCallback,
WebServiceMessageCallback responseCallback) throws WebServiceClientException;
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending and receiving marshalled messages
//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending and receiving marshalled messages
//-----------------------------------------------------------------------------------------------------------------
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the object to marshal into the request message payload
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(Object requestPayload) throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the object to marshal into the request message payload
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(Object requestPayload) throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any.
*
* @param uri the URI to send the message to
* @param requestPayload the object to marshal into the request message payload
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(String uri, Object requestPayload)
throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any.
*
* @param uri the URI to send the message to
* @param requestPayload the object to marshal into the request message payload
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(String uri, Object requestPayload)
throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any. The given callback
* allows changing of the request message after the payload has been marshalled to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the object to marshal into the request message payload
* @param requestCallback callback to change message, can be {@code null}
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(Object requestPayload, WebServiceMessageCallback requestCallback)
throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any. The given callback
* allows changing of the request message after the payload has been marshalled to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the object to marshal into the request message payload
* @param requestCallback callback to change message, can be {@code null}
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(Object requestPayload, WebServiceMessageCallback requestCallback)
throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any. The given callback
* allows changing of the request message after the payload has been marshalled to it.
*
* @param uri the URI to send the message to
* @param requestPayload the object to marshal into the request message payload
* @param requestCallback callback to change message, can be {@code null}
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(String uri, Object requestPayload, WebServiceMessageCallback requestCallback)
throws XmlMappingException, WebServiceClientException;
/**
* Sends a web service message that contains the given payload, marshalled by the configured
* {@code Marshaller}. Returns the unmarshalled payload of the response message, if any. The given callback
* allows changing of the request message after the payload has been marshalled to it.
*
* @param uri the URI to send the message to
* @param requestPayload the object to marshal into the request message payload
* @param requestCallback callback to change message, can be {@code null}
* @return the unmarshalled payload of the response message, or {@code null} if no response is given
* @throws XmlMappingException if there is a problem marshalling or unmarshalling
* @throws WebServiceClientException if there is a problem sending or receiving the message
* @see WebServiceTemplate#setMarshaller(org.springframework.oxm.Marshaller)
* @see WebServiceTemplate#setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
Object marshalSendAndReceive(String uri, Object requestPayload, WebServiceMessageCallback requestCallback)
throws XmlMappingException, WebServiceClientException;
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending Sources
//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending Sources
//-----------------------------------------------------------------------------------------------------------------
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(Source requestPayload, SourceExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(Source requestPayload, SourceExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(String uri, Source requestPayload, SourceExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(String uri, Source requestPayload, SourceExtractor<T> responseExtractor)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(Source requestPayload,
WebServiceMessageCallback requestCallback,
SourceExtractor<T> responseExtractor) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(Source requestPayload,
WebServiceMessageCallback requestCallback,
SourceExtractor<T> responseExtractor) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(String uri,
Source requestPayload,
WebServiceMessageCallback requestCallback,
SourceExtractor<T> responseExtractor) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload, reading the result with a
* {@code SourceExtractor}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseExtractor object that will extract results
* @return an arbitrary result object, as returned by the {@code SourceExtractor}
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
<T> T sendSourceAndReceive(String uri,
Source requestPayload,
WebServiceMessageCallback requestCallback,
SourceExtractor<T> responseExtractor) throws WebServiceClientException;
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending Sources and receiving to Results
//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
// Convenience methods for sending Sources and receiving to Results
//-----------------------------------------------------------------------------------------------------------------
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(Source requestPayload, Result responseResult) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(Source requestPayload, Result responseResult) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(String uri, Source requestPayload, Result responseResult)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(String uri, Source requestPayload, Result responseResult)
throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(Source requestPayload,
WebServiceMessageCallback requestCallback,
Result responseResult) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* <p>This will only work with a default uri specified!
*
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(Source requestPayload,
WebServiceMessageCallback requestCallback,
Result responseResult) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(String uri,
Source requestPayload,
WebServiceMessageCallback requestCallback,
Result responseResult) throws WebServiceClientException;
/**
* Sends a web service message that contains the given payload. Writes the response, if any, to the given
* {@code Result}.
*
* <p>The given callback allows changing of the request message after the payload has been written to it.
*
* @param uri the URI to send the message to
* @param requestPayload the payload of the request message
* @param requestCallback callback to change message, can be {@code null}
* @param responseResult the result to write the response payload to
* @return {@code true} if a response was received; {@code false} otherwise
* @throws WebServiceClientException if there is a problem sending or receiving the message
*/
boolean sendSourceAndReceiveToResult(String uri,
Source requestPayload,
WebServiceMessageCallback requestCallback,
Result responseResult) throws WebServiceClientException;
}

View File

@@ -52,144 +52,144 @@ import org.springframework.ws.transport.WebServiceMessageSender;
*/
public abstract class WebServiceGatewaySupport implements InitializingBean {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private WebServiceTemplate webServiceTemplate;
private WebServiceTemplate webServiceTemplate;
/**
* Creates a new instance of the {@code WebServiceGatewaySupport} class, with a default
* {@code WebServiceTemplate}.
*/
protected WebServiceGatewaySupport() {
webServiceTemplate = new WebServiceTemplate();
}
/**
* Creates a new instance of the {@code WebServiceGatewaySupport} class, with a default
* {@code WebServiceTemplate}.
*/
protected WebServiceGatewaySupport() {
webServiceTemplate = new WebServiceTemplate();
}
/**
* Creates a new {@code WebServiceGatewaySupport} instance based on the given message factory.
*
* @param messageFactory the message factory to use
*/
protected WebServiceGatewaySupport(WebServiceMessageFactory messageFactory) {
webServiceTemplate = new WebServiceTemplate(messageFactory);
}
/**
* Creates a new {@code WebServiceGatewaySupport} instance based on the given message factory.
*
* @param messageFactory the message factory to use
*/
protected WebServiceGatewaySupport(WebServiceMessageFactory messageFactory) {
webServiceTemplate = new WebServiceTemplate(messageFactory);
}
/** Returns the {@code WebServiceMessageFactory} used by the gateway. */
public final WebServiceMessageFactory getMessageFactory() {
return webServiceTemplate.getMessageFactory();
}
/** Returns the {@code WebServiceMessageFactory} used by the gateway. */
public final WebServiceMessageFactory getMessageFactory() {
return webServiceTemplate.getMessageFactory();
}
/** Set the {@code WebServiceMessageFactory} to be used by the gateway. */
public final void setMessageFactory(WebServiceMessageFactory messageFactory) {
webServiceTemplate.setMessageFactory(messageFactory);
}
/** Set the {@code WebServiceMessageFactory} to be used by the gateway. */
public final void setMessageFactory(WebServiceMessageFactory messageFactory) {
webServiceTemplate.setMessageFactory(messageFactory);
}
/** Returns the default URI used by the gateway. */
public final String getDefaultUri() {
return webServiceTemplate.getDefaultUri();
}
/** Returns the default URI used by the gateway. */
public final String getDefaultUri() {
return webServiceTemplate.getDefaultUri();
}
/** Sets the default URI used by the gateway. */
public final void setDefaultUri(String uri) {
webServiceTemplate.setDefaultUri(uri);
}
/** Sets the default URI used by the gateway. */
public final void setDefaultUri(String uri) {
webServiceTemplate.setDefaultUri(uri);
}
/** Returns the destination provider used by the gateway. */
public final DestinationProvider getDestinationProvider() {
return webServiceTemplate.getDestinationProvider();
}
/** Returns the destination provider used by the gateway. */
public final DestinationProvider getDestinationProvider() {
return webServiceTemplate.getDestinationProvider();
}
/** Set the destination provider URI used by the gateway. */
public final void setDestinationProvider(DestinationProvider destinationProvider) {
webServiceTemplate.setDestinationProvider(destinationProvider);
}
/** Set the destination provider URI used by the gateway. */
public final void setDestinationProvider(DestinationProvider destinationProvider) {
webServiceTemplate.setDestinationProvider(destinationProvider);
}
/** Sets a single {@code WebServiceMessageSender} to be used by the gateway. */
public final void setMessageSender(WebServiceMessageSender messageSender) {
webServiceTemplate.setMessageSender(messageSender);
}
/** Sets a single {@code WebServiceMessageSender} to be used by the gateway. */
public final void setMessageSender(WebServiceMessageSender messageSender) {
webServiceTemplate.setMessageSender(messageSender);
}
/** Returns the {@code WebServiceMessageSender}s used by the gateway. */
public final WebServiceMessageSender[] getMessageSenders() {
return webServiceTemplate.getMessageSenders();
}
/** Returns the {@code WebServiceMessageSender}s used by the gateway. */
public final WebServiceMessageSender[] getMessageSenders() {
return webServiceTemplate.getMessageSenders();
}
/** Sets multiple {@code WebServiceMessageSender} to be used by the gateway. */
public final void setMessageSenders(WebServiceMessageSender[] messageSenders) {
webServiceTemplate.setMessageSenders(messageSenders);
}
/** Sets multiple {@code WebServiceMessageSender} to be used by the gateway. */
public final void setMessageSenders(WebServiceMessageSender[] messageSenders) {
webServiceTemplate.setMessageSenders(messageSenders);
}
/** Returns the {@code WebServiceTemplate} for the gateway. */
public final WebServiceTemplate getWebServiceTemplate() {
return webServiceTemplate;
}
/** Returns the {@code WebServiceTemplate} for the gateway. */
public final WebServiceTemplate getWebServiceTemplate() {
return webServiceTemplate;
}
/**
* Sets the {@code WebServiceTemplate} to be used by the gateway.
*
* <p>When using this property, the convenience setters ({@link #setMarshaller(Marshaller)}, {@link
* #setUnmarshaller(Unmarshaller)}, {@link #setMessageSender(WebServiceMessageSender)}, {@link
* #setMessageSenders(WebServiceMessageSender[])}, and {@link #setDefaultUri(String)}) should not be set on this
* class, but on the template directly.
*/
public final void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) {
Assert.notNull(webServiceTemplate, "'webServiceTemplate' must not be null");
this.webServiceTemplate = webServiceTemplate;
}
/**
* Sets the {@code WebServiceTemplate} to be used by the gateway.
*
* <p>When using this property, the convenience setters ({@link #setMarshaller(Marshaller)}, {@link
* #setUnmarshaller(Unmarshaller)}, {@link #setMessageSender(WebServiceMessageSender)}, {@link
* #setMessageSenders(WebServiceMessageSender[])}, and {@link #setDefaultUri(String)}) should not be set on this
* class, but on the template directly.
*/
public final void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) {
Assert.notNull(webServiceTemplate, "'webServiceTemplate' must not be null");
this.webServiceTemplate = webServiceTemplate;
}
/** Returns the {@code Marshaller} used by the gateway. */
public final Marshaller getMarshaller() {
return webServiceTemplate.getMarshaller();
}
/** Returns the {@code Marshaller} used by the gateway. */
public final Marshaller getMarshaller() {
return webServiceTemplate.getMarshaller();
}
/**
* Sets the {@code Marshaller} used by the gateway. Setting this property is only required if the marshalling
* functionality of {@code WebServiceTemplate} is to be used.
*
* @see WebServiceTemplate#marshalSendAndReceive
*/
public final void setMarshaller(Marshaller marshaller) {
webServiceTemplate.setMarshaller(marshaller);
}
/**
* Sets the {@code Marshaller} used by the gateway. Setting this property is only required if the marshalling
* functionality of {@code WebServiceTemplate} is to be used.
*
* @see WebServiceTemplate#marshalSendAndReceive
*/
public final void setMarshaller(Marshaller marshaller) {
webServiceTemplate.setMarshaller(marshaller);
}
/** Returns the {@code Unmarshaller} used by the gateway. */
public final Unmarshaller getUnmarshaller() {
return webServiceTemplate.getUnmarshaller();
}
/** Returns the {@code Unmarshaller} used by the gateway. */
public final Unmarshaller getUnmarshaller() {
return webServiceTemplate.getUnmarshaller();
}
/**
* Sets the {@code Unmarshaller} used by the gateway. Setting this property is only required if the marshalling
* functionality of {@code WebServiceTemplate} is to be used.
*
* @see WebServiceTemplate#marshalSendAndReceive
*/
public final void setUnmarshaller(Unmarshaller unmarshaller) {
webServiceTemplate.setUnmarshaller(unmarshaller);
}
/**
* Sets the {@code Unmarshaller} used by the gateway. Setting this property is only required if the marshalling
* functionality of {@code WebServiceTemplate} is to be used.
*
* @see WebServiceTemplate#marshalSendAndReceive
*/
public final void setUnmarshaller(Unmarshaller unmarshaller) {
webServiceTemplate.setUnmarshaller(unmarshaller);
}
/** Returns the {@code ClientInterceptors} used by the template. */
public final ClientInterceptor[] getInterceptors() {
return webServiceTemplate.getInterceptors();
}
/** Returns the {@code ClientInterceptors} used by the template. */
public final ClientInterceptor[] getInterceptors() {
return webServiceTemplate.getInterceptors();
}
/** Sets the {@code ClientInterceptors} used by the gateway. */
public final void setInterceptors(ClientInterceptor[] interceptors) {
webServiceTemplate.setInterceptors(interceptors);
}
/** Sets the {@code ClientInterceptors} used by the gateway. */
public final void setInterceptors(ClientInterceptor[] interceptors) {
webServiceTemplate.setInterceptors(interceptors);
}
@Override
public final void afterPropertiesSet() throws Exception {
webServiceTemplate.afterPropertiesSet();
initGateway();
}
@Override
public final void afterPropertiesSet() throws Exception {
webServiceTemplate.afterPropertiesSet();
initGateway();
}
/**
* Subclasses can override this for custom initialization behavior. Gets called after population of this instance's
* bean properties.
*
* @throws java.lang.Exception if initialization fails
*/
protected void initGateway() throws Exception {
}
/**
* Subclasses can override this for custom initialization behavior. Gets called after population of this instance's
* bean properties.
*
* @throws java.lang.Exception if initialization fails
*/
protected void initGateway() throws Exception {
}
}

View File

@@ -39,85 +39,85 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public abstract class WebServiceAccessor extends TransformerObjectSupport implements InitializingBean {
private WebServiceMessageFactory messageFactory;
private WebServiceMessageFactory messageFactory;
private WebServiceMessageSender[] messageSenders;
private WebServiceMessageSender[] messageSenders;
/** Returns the message factory used for creating messages. */
public WebServiceMessageFactory getMessageFactory() {
return messageFactory;
}
/** Returns the message factory used for creating messages. */
public WebServiceMessageFactory getMessageFactory() {
return messageFactory;
}
/** Sets the message factory used for creating messages. */
public void setMessageFactory(WebServiceMessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
/** Sets the message factory used for creating messages. */
public void setMessageFactory(WebServiceMessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
/** Returns the message senders used for sending messages. */
public WebServiceMessageSender[] getMessageSenders() {
return messageSenders;
}
/** Returns the message senders used for sending messages. */
public WebServiceMessageSender[] getMessageSenders() {
return messageSenders;
}
/**
* Sets the single message sender used for sending messages.
*
* <p>This message sender will be used to resolve an URI to a {@link WebServiceConnection}.
*
* @see #createConnection(URI)
*/
public void setMessageSender(WebServiceMessageSender messageSender) {
Assert.notNull(messageSender, "'messageSender' must not be null");
messageSenders = new WebServiceMessageSender[]{messageSender};
}
/**
* Sets the single message sender used for sending messages.
*
* <p>This message sender will be used to resolve an URI to a {@link WebServiceConnection}.
*
* @see #createConnection(URI)
*/
public void setMessageSender(WebServiceMessageSender messageSender) {
Assert.notNull(messageSender, "'messageSender' must not be null");
messageSenders = new WebServiceMessageSender[]{messageSender};
}
/**
* Sets the message senders used for sending messages.
*
* <p>These message senders will be used to resolve an URI to a {@link WebServiceConnection}.
*
* @see #createConnection(URI)
*/
public void setMessageSenders(WebServiceMessageSender[] messageSenders) {
Assert.notEmpty(messageSenders, "'messageSenders' must not be empty");
this.messageSenders = messageSenders;
}
/**
* Sets the message senders used for sending messages.
*
* <p>These message senders will be used to resolve an URI to a {@link WebServiceConnection}.
*
* @see #createConnection(URI)
*/
public void setMessageSenders(WebServiceMessageSender[] messageSenders) {
Assert.notEmpty(messageSenders, "'messageSenders' must not be empty");
this.messageSenders = messageSenders;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(getMessageFactory(), "Property 'messageFactory' is required");
Assert.notEmpty(getMessageSenders(), "Property 'messageSenders' is required");
}
@Override
public void afterPropertiesSet() {
Assert.notNull(getMessageFactory(), "Property 'messageFactory' is required");
Assert.notEmpty(getMessageSenders(), "Property 'messageSenders' is required");
}
/**
* Creates a connection to the given URI, or throws an exception when it cannot be resolved.
*
* <p>Default implementation iterates over all configured {@link WebServiceMessageSender} objects, and calls {@link
* WebServiceMessageSender#supports(URI)} for each of them. If the sender supports the parameter URI, it creates a
* connection using {@link WebServiceMessageSender#createConnection(URI)} .
*
* @param uri the URI to open a connection to
* @return the created connection
* @throws IllegalArgumentException when the uri cannot be resolved
* @throws IOException when an I/O error occurs
*/
protected WebServiceConnection createConnection(URI uri) throws IOException {
Assert.notEmpty(getMessageSenders(), "Property 'messageSenders' is required");
WebServiceMessageSender[] messageSenders = getMessageSenders();
for (WebServiceMessageSender messageSender : messageSenders) {
if (messageSender.supports(uri)) {
WebServiceConnection connection = messageSender.createConnection(uri);
if (logger.isDebugEnabled()) {
try {
logger.debug("Opening [" + connection + "] to [" + connection.getUri() + "]");
}
catch (URISyntaxException e) {
// ignore
}
}
return connection;
}
}
throw new IllegalArgumentException("Could not resolve [" + uri + "] to a WebServiceMessageSender");
}
/**
* Creates a connection to the given URI, or throws an exception when it cannot be resolved.
*
* <p>Default implementation iterates over all configured {@link WebServiceMessageSender} objects, and calls {@link
* WebServiceMessageSender#supports(URI)} for each of them. If the sender supports the parameter URI, it creates a
* connection using {@link WebServiceMessageSender#createConnection(URI)} .
*
* @param uri the URI to open a connection to
* @return the created connection
* @throws IllegalArgumentException when the uri cannot be resolved
* @throws IOException when an I/O error occurs
*/
protected WebServiceConnection createConnection(URI uri) throws IOException {
Assert.notEmpty(getMessageSenders(), "Property 'messageSenders' is required");
WebServiceMessageSender[] messageSenders = getMessageSenders();
for (WebServiceMessageSender messageSender : messageSenders) {
if (messageSender.supports(uri)) {
WebServiceConnection connection = messageSender.createConnection(uri);
if (logger.isDebugEnabled()) {
try {
logger.debug("Opening [" + connection + "] to [" + connection.getUri() + "]");
}
catch (URISyntaxException e) {
// ignore
}
}
return connection;
}
}
throw new IllegalArgumentException("Could not resolve [" + uri + "] to a WebServiceMessageSender");
}
}

View File

@@ -32,41 +32,41 @@ import org.apache.commons.logging.LogFactory;
*/
public abstract class AbstractCachingDestinationProvider implements DestinationProvider {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private URI cachedUri;
private URI cachedUri;
private boolean cache = true;
private boolean cache = true;
/**
* Set whether to cache resolved destinations. Default is {@code true}. This flag can be turned off to
* re-lookup a destination for each operation, which allows for hot restarting of destinations. This is mainly
* useful during development.
*/
public void setCache(boolean cache) {
this.cache = cache;
}
/**
* Set whether to cache resolved destinations. Default is {@code true}. This flag can be turned off to
* re-lookup a destination for each operation, which allows for hot restarting of destinations. This is mainly
* useful during development.
*/
public void setCache(boolean cache) {
this.cache = cache;
}
@Override
public final URI getDestination() {
if (cache) {
if (cachedUri == null) {
cachedUri = lookupDestination();
}
return cachedUri;
}
else {
return lookupDestination();
}
}
@Override
public final URI getDestination() {
if (cache) {
if (cachedUri == null) {
cachedUri = lookupDestination();
}
return cachedUri;
}
else {
return lookupDestination();
}
}
/**
* Abstract template method that looks up the URI.
*
* <p>If {@linkplain #setCache(boolean) caching} is enabled, this method will only be called once.
*
* @return the destination URI
*/
protected abstract URI lookupDestination();
/**
* Abstract template method that looks up the URI.
*
* <p>If {@linkplain #setCache(boolean) caching} is enabled, this method will only be called once.
*
* @return the destination URI
*/
protected abstract URI lookupDestination();
}

View File

@@ -31,11 +31,11 @@ import java.net.URI;
*/
public interface DestinationProvider {
/**
* Return the destination URI.
*
* @return the destination URI
*/
URI getDestination();
/**
* Return the destination URI.
*
* @return the destination URI
*/
URI getDestination();
}

View File

@@ -27,11 +27,11 @@ import org.springframework.ws.client.WebServiceClientException;
@SuppressWarnings("serial")
public class DestinationProvisionException extends WebServiceClientException {
public DestinationProvisionException(String msg) {
super(msg);
}
public DestinationProvisionException(String msg) {
super(msg);
}
public DestinationProvisionException(String msg, Throwable ex) {
super(msg, ex);
}
public DestinationProvisionException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -48,70 +48,70 @@ import org.springframework.xml.xpath.XPathExpressionFactory;
*/
public class Wsdl11DestinationProvider extends AbstractCachingDestinationProvider {
/** Default XPath expression used for extracting all {@code location} attributes from the WSDL definition. */
public static final String DEFAULT_WSDL_LOCATION_EXPRESSION =
"/wsdl:definitions/wsdl:service/wsdl:port/soap:address/@location";
/** Default XPath expression used for extracting all {@code location} attributes from the WSDL definition. */
public static final String DEFAULT_WSDL_LOCATION_EXPRESSION =
"/wsdl:definitions/wsdl:service/wsdl:port/soap:address/@location";
private static TransformerFactory transformerFactory = TransformerFactory.newInstance();
private static TransformerFactory transformerFactory = TransformerFactory.newInstance();
private Map<String, String> expressionNamespaces = new HashMap<String, String>();
private Map<String, String> expressionNamespaces = new HashMap<String, String>();
private XPathExpression locationXPathExpression;
private XPathExpression locationXPathExpression;
private Resource wsdlResource;
private Resource wsdlResource;
public Wsdl11DestinationProvider() {
expressionNamespaces.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
expressionNamespaces.put("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
expressionNamespaces.put("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/");
public Wsdl11DestinationProvider() {
expressionNamespaces.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
expressionNamespaces.put("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
expressionNamespaces.put("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/");
locationXPathExpression = XPathExpressionFactory
.createXPathExpression(DEFAULT_WSDL_LOCATION_EXPRESSION, expressionNamespaces);
}
locationXPathExpression = XPathExpressionFactory
.createXPathExpression(DEFAULT_WSDL_LOCATION_EXPRESSION, expressionNamespaces);
}
/** Sets a WSDL location from which the service destination {@code URI} will be resolved. */
public void setWsdl(Resource wsdlResource) {
Assert.notNull(wsdlResource, "'wsdl' must not be null");
Assert.isTrue(wsdlResource.exists(), wsdlResource + " does not exist");
this.wsdlResource = wsdlResource;
}
/** Sets a WSDL location from which the service destination {@code URI} will be resolved. */
public void setWsdl(Resource wsdlResource) {
Assert.notNull(wsdlResource, "'wsdl' must not be null");
Assert.isTrue(wsdlResource.exists(), wsdlResource + " does not exist");
this.wsdlResource = wsdlResource;
}
/**
* Sets the XPath expression to use when extracting the service location {@code URI} from a WSDL.
*
* <p>The expression can use the following bound prefixes: <blockquote> <table> <tr><th>Prefix</th><th>Namespace</th></tr>
* <tr><td>{@code wsdl}</td><td>{@code http://schemas.xmlsoap.org/wsdl/}</td></tr>
* <tr><td>{@code soap}</td><td>{@code http://schemas.xmlsoap.org/wsdl/soap/}</td></tr>
* <tr><td>{@code soap12}</td><td>{@code http://schemas.xmlsoap.org/wsdl/soap12/}</td></tr>
* </table></blockquote>
*
* <p>Defaults to {@link #DEFAULT_WSDL_LOCATION_EXPRESSION}.
*/
public void setLocationExpression(String expression) {
Assert.hasText(expression, "'expression' must not be empty");
locationXPathExpression = XPathExpressionFactory
.createXPathExpression(expression, expressionNamespaces);
}
/**
* Sets the XPath expression to use when extracting the service location {@code URI} from a WSDL.
*
* <p>The expression can use the following bound prefixes: <blockquote> <table> <tr><th>Prefix</th><th>Namespace</th></tr>
* <tr><td>{@code wsdl}</td><td>{@code http://schemas.xmlsoap.org/wsdl/}</td></tr>
* <tr><td>{@code soap}</td><td>{@code http://schemas.xmlsoap.org/wsdl/soap/}</td></tr>
* <tr><td>{@code soap12}</td><td>{@code http://schemas.xmlsoap.org/wsdl/soap12/}</td></tr>
* </table></blockquote>
*
* <p>Defaults to {@link #DEFAULT_WSDL_LOCATION_EXPRESSION}.
*/
public void setLocationExpression(String expression) {
Assert.hasText(expression, "'expression' must not be empty");
locationXPathExpression = XPathExpressionFactory
.createXPathExpression(expression, expressionNamespaces);
}
@Override
protected URI lookupDestination() {
try {
DOMResult result = new DOMResult();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new ResourceSource(wsdlResource), result);
Document definitionDocument = (Document) result.getNode();
String location = locationXPathExpression.evaluateAsString(definitionDocument);
if (logger.isDebugEnabled()) {
logger.debug("Found location [" + location + "] in " + wsdlResource);
}
return location != null ? URI.create(location) : null;
}
catch (IOException ex) {
throw new WebServiceIOException("Error extracting location from WSDL [" + wsdlResource + "]", ex);
}
catch (TransformerException ex) {
throw new WebServiceTransformerException("Error extracting location from WSDL [" + wsdlResource + "]", ex);
}
}
@Override
protected URI lookupDestination() {
try {
DOMResult result = new DOMResult();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new ResourceSource(wsdlResource), result);
Document definitionDocument = (Document) result.getNode();
String location = locationXPathExpression.evaluateAsString(definitionDocument);
if (logger.isDebugEnabled()) {
logger.debug("Found location [" + location + "] in " + wsdlResource);
}
return location != null ? URI.create(location) : null;
}
catch (IOException ex) {
throw new WebServiceIOException("Error extracting location from WSDL [" + wsdlResource + "]", ex);
}
catch (TransformerException ex) {
throw new WebServiceTransformerException("Error extracting location from WSDL [" + wsdlResource + "]", ex);
}
}
}

View File

@@ -50,216 +50,216 @@ import org.springframework.xml.xsd.XsdSchemaCollection;
* @since 1.5.4
*/
public abstract class AbstractValidatingInterceptor extends TransformerObjectSupport
implements ClientInterceptor, InitializingBean {
implements ClientInterceptor, InitializingBean {
private String schemaLanguage = XmlValidatorFactory.SCHEMA_W3C_XML;
private String schemaLanguage = XmlValidatorFactory.SCHEMA_W3C_XML;
private Resource[] schemas;
private Resource[] schemas;
private boolean validateRequest = true;
private boolean validateRequest = true;
private boolean validateResponse = false;
private boolean validateResponse = false;
private XmlValidator validator;
private XmlValidator validator;
public String getSchemaLanguage() {
return schemaLanguage;
}
public String getSchemaLanguage() {
return schemaLanguage;
}
/**
* Sets the schema language. Default is the W3C XML Schema: {@code http://www.w3.org/2001/XMLSchema"}.
*
* @see XmlValidatorFactory#SCHEMA_W3C_XML
* @see XmlValidatorFactory#SCHEMA_RELAX_NG
*/
public void setSchemaLanguage(String schemaLanguage) {
this.schemaLanguage = schemaLanguage;
}
/**
* Sets the schema language. Default is the W3C XML Schema: {@code http://www.w3.org/2001/XMLSchema"}.
*
* @see XmlValidatorFactory#SCHEMA_W3C_XML
* @see XmlValidatorFactory#SCHEMA_RELAX_NG
*/
public void setSchemaLanguage(String schemaLanguage) {
this.schemaLanguage = schemaLanguage;
}
/** Returns the schema resources to use for validation. */
public Resource[] getSchemas() {
return schemas;
}
/** Returns the schema resources to use for validation. */
public Resource[] getSchemas() {
return schemas;
}
/**
* Sets the schema resource to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*/
public void setSchema(Resource schema) {
setSchemas(new Resource[]{schema});
}
/**
* Sets the schema resource to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*/
public void setSchema(Resource schema) {
setSchemas(new Resource[]{schema});
}
/**
* Sets the schema resources to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*/
public void setSchemas(Resource[] schemas) {
Assert.notEmpty(schemas, "schemas must not be empty or null");
for (Resource schema : schemas) {
Assert.notNull(schema, "schema must not be null");
Assert.isTrue(schema.exists(), "schema \"" + schema + "\" does not exit");
}
this.schemas = schemas;
}
/**
* Sets the schema resources to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*/
public void setSchemas(Resource[] schemas) {
Assert.notEmpty(schemas, "schemas must not be empty or null");
for (Resource schema : schemas) {
Assert.notNull(schema, "schema must not be null");
Assert.isTrue(schema.exists(), "schema \"" + schema + "\" does not exit");
}
this.schemas = schemas;
}
/**
* Sets the {@link XsdSchema} to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*
* @param schema the xsd schema to use
* @throws java.io.IOException in case of I/O errors
*/
public void setXsdSchema(XsdSchema schema) throws IOException {
this.validator = schema.createValidator();
}
/**
* Sets the {@link XsdSchema} to use for validation. Setting this property, {@link
* #setXsdSchemaCollection(XsdSchemaCollection) xsdSchemaCollection}, {@link #setSchema(Resource) schema}, or {@link
* #setSchemas(Resource[]) schemas} is required.
*
* @param schema the xsd schema to use
* @throws java.io.IOException in case of I/O errors
*/
public void setXsdSchema(XsdSchema schema) throws IOException {
this.validator = schema.createValidator();
}
/**
* Sets the {@link XsdSchemaCollection} to use for validation. Setting this property, {@link
* #setXsdSchema(XsdSchema) xsdSchema}, {@link #setSchema(Resource) schema}, or {@link #setSchemas(Resource[])
* schemas} is required.
*
* @param schemaCollection the xsd schema collection to use
* @throws java.io.IOException in case of I/O errors
*/
public void setXsdSchemaCollection(XsdSchemaCollection schemaCollection) throws IOException {
this.validator = schemaCollection.createValidator();
}
/**
* Sets the {@link XsdSchemaCollection} to use for validation. Setting this property, {@link
* #setXsdSchema(XsdSchema) xsdSchema}, {@link #setSchema(Resource) schema}, or {@link #setSchemas(Resource[])
* schemas} is required.
*
* @param schemaCollection the xsd schema collection to use
* @throws java.io.IOException in case of I/O errors
*/
public void setXsdSchemaCollection(XsdSchemaCollection schemaCollection) throws IOException {
this.validator = schemaCollection.createValidator();
}
/** Indicates whether the request should be validated against the schema. Default is {@code true}. */
public void setValidateRequest(boolean validateRequest) {
this.validateRequest = validateRequest;
}
/** Indicates whether the request should be validated against the schema. Default is {@code true}. */
public void setValidateRequest(boolean validateRequest) {
this.validateRequest = validateRequest;
}
/** Indicates whether the response should be validated against the schema. Default is {@code false}. */
public void setValidateResponse(boolean validateResponse) {
this.validateResponse = validateResponse;
}
/** Indicates whether the response should be validated against the schema. Default is {@code false}. */
public void setValidateResponse(boolean validateResponse) {
this.validateResponse = validateResponse;
}
@Override
public void afterPropertiesSet() throws Exception {
if (validator == null && !ObjectUtils.isEmpty(schemas)) {
Assert.hasLength(schemaLanguage, "schemaLanguage is required");
for (Resource schema : schemas) {
Assert.isTrue(schema.exists(), "schema [" + schema + "] does not exist");
}
if (logger.isInfoEnabled()) {
logger.info("Validating using " + StringUtils.arrayToCommaDelimitedString(schemas));
}
validator = XmlValidatorFactory.createValidator(schemas, schemaLanguage);
}
Assert.notNull(validator, "Setting 'schema', 'schemas', 'xsdSchema', or 'xsdSchemaCollection' is required");
}
@Override
public void afterPropertiesSet() throws Exception {
if (validator == null && !ObjectUtils.isEmpty(schemas)) {
Assert.hasLength(schemaLanguage, "schemaLanguage is required");
for (Resource schema : schemas) {
Assert.isTrue(schema.exists(), "schema [" + schema + "] does not exist");
}
if (logger.isInfoEnabled()) {
logger.info("Validating using " + StringUtils.arrayToCommaDelimitedString(schemas));
}
validator = XmlValidatorFactory.createValidator(schemas, schemaLanguage);
}
Assert.notNull(validator, "Setting 'schema', 'schemas', 'xsdSchema', or 'xsdSchemaCollection' is required");
}
/**
* Validates the request message in the given message context. Validation only occurs if {@link
* #setValidateRequest(boolean) validateRequest} is set to {@code true}, which is the default.
*
* <p>Returns {@code true} if the request is valid, or {@code false} if it isn't.
*
* @param messageContext the message context
* @return {@code true} if the message is valid; {@code false} otherwise
* @see #setValidateRequest(boolean)
*/
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
if (validateRequest) {
Source requestSource = getValidationRequestSource(messageContext.getRequest());
if (requestSource != null) {
SAXParseException[] errors;
try {
errors = validator.validate(requestSource);
}
catch (IOException e) {
throw new WebServiceIOException("Could not validate response: " + e.getMessage(), e);
}
if (!ObjectUtils.isEmpty(errors)) {
return handleRequestValidationErrors(messageContext, errors);
}
else if (logger.isDebugEnabled()) {
logger.debug("Request message validated");
}
}
}
return true;
}
/**
* Validates the request message in the given message context. Validation only occurs if {@link
* #setValidateRequest(boolean) validateRequest} is set to {@code true}, which is the default.
*
* <p>Returns {@code true} if the request is valid, or {@code false} if it isn't.
*
* @param messageContext the message context
* @return {@code true} if the message is valid; {@code false} otherwise
* @see #setValidateRequest(boolean)
*/
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
if (validateRequest) {
Source requestSource = getValidationRequestSource(messageContext.getRequest());
if (requestSource != null) {
SAXParseException[] errors;
try {
errors = validator.validate(requestSource);
}
catch (IOException e) {
throw new WebServiceIOException("Could not validate response: " + e.getMessage(), e);
}
if (!ObjectUtils.isEmpty(errors)) {
return handleRequestValidationErrors(messageContext, errors);
}
else if (logger.isDebugEnabled()) {
logger.debug("Request message validated");
}
}
}
return true;
}
/**
* Template method that is called when the request message contains validation errors.
*
* <p>Default implementation logs all errors, and throws a {@link WebServiceValidationException}. Subclasses can
* override this method to customize this behavior.
*
* @param messageContext the message context
* @param errors the validation errors
* @return {@code true} to continue processing the request, {@code false} otherwise
*/
protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) {
for (SAXParseException error : errors) {
logger.error("XML validation error on request: " + error.getMessage());
}
throw new WebServiceValidationException(errors);
}
/**
* Template method that is called when the request message contains validation errors.
*
* <p>Default implementation logs all errors, and throws a {@link WebServiceValidationException}. Subclasses can
* override this method to customize this behavior.
*
* @param messageContext the message context
* @param errors the validation errors
* @return {@code true} to continue processing the request, {@code false} otherwise
*/
protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) {
for (SAXParseException error : errors) {
logger.error("XML validation error on request: " + error.getMessage());
}
throw new WebServiceValidationException(errors);
}
/**
* Validates the response message in the given message context. Validation only occurs if {@link
* #setValidateResponse(boolean) validateResponse} is set to {@code true}, which is <strong>not</strong> the
* default.
*
* <p>Returns {@code true} if the request is valid, or {@code false} if it isn't.
*
* @param messageContext the message context.
* @return {@code true} if the response is valid; {@code false} otherwise
* @see #setValidateResponse(boolean)
*/
@Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
if (validateResponse) {
Source responseSource = getValidationResponseSource(messageContext.getResponse());
if (responseSource != null) {
SAXParseException[] errors;
try {
errors = validator.validate(responseSource);
}
catch (IOException e) {
throw new WebServiceIOException("Could not validate response: " + e.getMessage(), e);
}
if (!ObjectUtils.isEmpty(errors)) {
return handleResponseValidationErrors(messageContext, errors);
}
else if (logger.isDebugEnabled()) {
logger.debug("Response message validated");
}
}
}
return true;
}
/**
* Validates the response message in the given message context. Validation only occurs if {@link
* #setValidateResponse(boolean) validateResponse} is set to {@code true}, which is <strong>not</strong> the
* default.
*
* <p>Returns {@code true} if the request is valid, or {@code false} if it isn't.
*
* @param messageContext the message context.
* @return {@code true} if the response is valid; {@code false} otherwise
* @see #setValidateResponse(boolean)
*/
@Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
if (validateResponse) {
Source responseSource = getValidationResponseSource(messageContext.getResponse());
if (responseSource != null) {
SAXParseException[] errors;
try {
errors = validator.validate(responseSource);
}
catch (IOException e) {
throw new WebServiceIOException("Could not validate response: " + e.getMessage(), e);
}
if (!ObjectUtils.isEmpty(errors)) {
return handleResponseValidationErrors(messageContext, errors);
}
else if (logger.isDebugEnabled()) {
logger.debug("Response message validated");
}
}
}
return true;
}
/**
* Template method that is called when the response message contains validation errors.
*
* <p>Default implementation logs all errors, and returns {@code false}, i.e. do not cot continue to process the
* respone interceptor chain.
*
* @param messageContext the message context
* @param errors the validation errors
* @return {@code true} to continue the reponse interceptor chain, {@code false} (the default) otherwise
*/
protected boolean handleResponseValidationErrors(MessageContext messageContext, SAXParseException[] errors)
throws WebServiceValidationException {
for (SAXParseException error : errors) {
logger.warn("XML validation error on response: " + error.getMessage());
}
return false;
}
/**
* Template method that is called when the response message contains validation errors.
*
* <p>Default implementation logs all errors, and returns {@code false}, i.e. do not cot continue to process the
* respone interceptor chain.
*
* @param messageContext the message context
* @param errors the validation errors
* @return {@code true} to continue the reponse interceptor chain, {@code false} (the default) otherwise
*/
protected boolean handleResponseValidationErrors(MessageContext messageContext, SAXParseException[] errors)
throws WebServiceValidationException {
for (SAXParseException error : errors) {
logger.warn("XML validation error on response: " + error.getMessage());
}
return false;
}
/** Does nothing by default. Faults are not validated. */
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
return true;
}
/** Does nothing by default. Faults are not validated. */
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
return true;
}
/** Does nothing by default.*/
@Override
@@ -268,18 +268,18 @@ public abstract class AbstractValidatingInterceptor extends TransformerObjectSup
}
/**
* Abstract template method that returns the part of the request message that is to be validated.
*
* @param request the request message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
protected abstract Source getValidationRequestSource(WebServiceMessage request);
* Abstract template method that returns the part of the request message that is to be validated.
*
* @param request the request message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
protected abstract Source getValidationRequestSource(WebServiceMessage request);
/**
* Abstract template method that returns the part of the response message that is to be validated.
*
* @param response the response message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
protected abstract Source getValidationResponseSource(WebServiceMessage response);
/**
* Abstract template method that returns the part of the response message that is to be validated.
*
* @param response the response message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
protected abstract Source getValidationResponseSource(WebServiceMessage response);
}

View File

@@ -43,59 +43,59 @@ import org.springframework.ws.transport.WebServiceConnection;
*/
public interface ClientInterceptor {
/**
* Processes the outgoing request message. Called after payload creation and callback invocation, but before the
* message is sent.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the request endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getRequest()
*/
boolean handleRequest(MessageContext messageContext) throws WebServiceClientException;
/**
* Processes the incoming response message. Called for non-fault response messages before payload handling in the
* {@link org.springframework.ws.client.core.WebServiceTemplate}.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the response endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getResponse()
*/
boolean handleResponse(MessageContext messageContext) throws WebServiceClientException;
/**
* Processes the incoming response fault. Called for response fault messages before payload handling in the {@link
* org.springframework.ws.client.core.WebServiceTemplate}.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the request endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getResponse()
* @see org.springframework.ws.FaultAwareWebServiceMessage#hasFault()
*/
boolean handleFault(MessageContext messageContext) throws WebServiceClientException;
/**
* Processes the outgoing request message. Called after payload creation and callback invocation, but before the
* message is sent.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the request endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getRequest()
*/
boolean handleRequest(MessageContext messageContext) throws WebServiceClientException;
/**
* Callback after completion of request and response (fault) processing. Will be called on any outcome, thus
* Processes the incoming response message. Called for non-fault response messages before payload handling in the
* {@link org.springframework.ws.client.core.WebServiceTemplate}.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the response endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getResponse()
*/
boolean handleResponse(MessageContext messageContext) throws WebServiceClientException;
/**
* Processes the incoming response fault. Called for response fault messages before payload handling in the {@link
* org.springframework.ws.client.core.WebServiceTemplate}.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains the outgoing request message
* @return {@code true} to continue processing of the request interceptors; {@code false} to indicate
* blocking of the request endpoint chain
* @throws WebServiceClientException in case of errors
* @see MessageContext#getResponse()
* @see org.springframework.ws.FaultAwareWebServiceMessage#hasFault()
*/
boolean handleFault(MessageContext messageContext) throws WebServiceClientException;
/**
* Callback after completion of request and response (fault) processing. Will be called on any outcome, thus
* allows for proper resource cleanup.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param ex exception thrown on handler execution, if any
* @throws WebServiceClientException in case of errors
* @since 2.2
*/
void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException;
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param ex exception thrown on handler execution, if any
* @throws WebServiceClientException in case of errors
* @since 2.2
*/
void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException;
}

View File

@@ -41,25 +41,25 @@ import org.springframework.ws.WebServiceMessage;
*/
public class PayloadValidatingInterceptor extends AbstractValidatingInterceptor {
/**
* Returns the part of the request message that is to be validated. Default
*
* @param request the request message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
@Override
protected Source getValidationRequestSource(WebServiceMessage request) {
return request.getPayloadSource();
}
/**
* Returns the part of the request message that is to be validated. Default
*
* @param request the request message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
@Override
protected Source getValidationRequestSource(WebServiceMessage request) {
return request.getPayloadSource();
}
/**
* Returns the part of the response message that is to be validated.
*
* @param response the response message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
@Override
protected Source getValidationResponseSource(WebServiceMessage response) {
return response.getPayloadSource();
}
/**
* Returns the part of the response message that is to be validated.
*
* @param response the response message
* @return the part of the message that is to validated, or {@code null} not to validate anything
*/
@Override
protected Source getValidationResponseSource(WebServiceMessage response) {
return response.getPayloadSource();
}
}

View File

@@ -30,27 +30,27 @@ import org.springframework.ws.client.WebServiceClientException;
@SuppressWarnings("serial")
public class WebServiceValidationException extends WebServiceClientException {
private SAXParseException[] validationErrors;
private SAXParseException[] validationErrors;
/**
* Create a new instance of the {@code WebServiceValidationException} class.
*/
public WebServiceValidationException(SAXParseException[] validationErrors) {
super(createMessage(validationErrors));
this.validationErrors = validationErrors;
}
/**
* Create a new instance of the {@code WebServiceValidationException} class.
*/
public WebServiceValidationException(SAXParseException[] validationErrors) {
super(createMessage(validationErrors));
this.validationErrors = validationErrors;
}
private static String createMessage(SAXParseException[] validationErrors) {
StringBuilder builder = new StringBuilder("XML validation error on response: ");
private static String createMessage(SAXParseException[] validationErrors) {
StringBuilder builder = new StringBuilder("XML validation error on response: ");
for (SAXParseException validationError : validationErrors) {
builder.append(validationError.getMessage());
}
return builder.toString();
}
for (SAXParseException validationError : validationErrors) {
builder.append(validationError.getMessage());
}
return builder.toString();
}
/** Returns the validation errors. */
public SAXParseException[] getValidationErrors() {
return validationErrors;
}
/** Returns the validation errors. */
public SAXParseException[] getValidationErrors() {
return validationErrors;
}
}

View File

@@ -57,158 +57,158 @@ import org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationM
*/
class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
private static final boolean dom4jPresent =
ClassUtils.isPresent("org.dom4j.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean dom4jPresent =
ClassUtils.isPresent("org.dom4j.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean jaxb2Present =
ClassUtils.isPresent("javax.xml.bind.Binder", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean jaxb2Present =
ClassUtils.isPresent("javax.xml.bind.Binder", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean jdomPresent =
ClassUtils.isPresent("org.jdom2.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean jdomPresent =
ClassUtils.isPresent("org.jdom2.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean staxPresent = ClassUtils
.isPresent("javax.xml.stream.XMLInputFactory", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean staxPresent = ClassUtils
.isPresent("javax.xml.stream.XMLInputFactory", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean xomPresent =
ClassUtils.isPresent("nu.xom.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
private static final boolean xomPresent =
ClassUtils.isPresent("nu.xom.Element", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition);
CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition);
registerEndpointMappings(source, parserContext);
registerEndpointMappings(source, parserContext);
registerEndpointAdapters(element, source, parserContext);
registerEndpointAdapters(element, source, parserContext);
registerEndpointExceptionResolvers(source, parserContext);
registerEndpointExceptionResolvers(source, parserContext);
parserContext.popAndRegisterContainingComponent();
parserContext.popAndRegisterContainingComponent();
return null;
}
return null;
}
private void registerEndpointMappings(Object source, ParserContext parserContext) {
RootBeanDefinition payloadRootMappingDef =
createBeanDefinition(PayloadRootAnnotationMethodEndpointMapping.class, source);
payloadRootMappingDef.getPropertyValues().add("order", 0);
parserContext.getReaderContext().registerWithGeneratedName(payloadRootMappingDef);
private void registerEndpointMappings(Object source, ParserContext parserContext) {
RootBeanDefinition payloadRootMappingDef =
createBeanDefinition(PayloadRootAnnotationMethodEndpointMapping.class, source);
payloadRootMappingDef.getPropertyValues().add("order", 0);
parserContext.getReaderContext().registerWithGeneratedName(payloadRootMappingDef);
RootBeanDefinition soapActionMappingDef =
createBeanDefinition(SoapActionAnnotationMethodEndpointMapping.class, source);
soapActionMappingDef.getPropertyValues().add("order", 1);
parserContext.getReaderContext().registerWithGeneratedName(soapActionMappingDef);
RootBeanDefinition soapActionMappingDef =
createBeanDefinition(SoapActionAnnotationMethodEndpointMapping.class, source);
soapActionMappingDef.getPropertyValues().add("order", 1);
parserContext.getReaderContext().registerWithGeneratedName(soapActionMappingDef);
RootBeanDefinition annActionMappingDef =
createBeanDefinition(AnnotationActionEndpointMapping.class, source);
annActionMappingDef.getPropertyValues().add("order", 2);
parserContext.getReaderContext().registerWithGeneratedName(annActionMappingDef);
}
RootBeanDefinition annActionMappingDef =
createBeanDefinition(AnnotationActionEndpointMapping.class, source);
annActionMappingDef.getPropertyValues().add("order", 2);
parserContext.getReaderContext().registerWithGeneratedName(annActionMappingDef);
}
private void registerEndpointAdapters(Element element, Object source, ParserContext parserContext) {
RootBeanDefinition adapterDef = createBeanDefinition(DefaultMethodEndpointAdapter.class, source);
private void registerEndpointAdapters(Element element, Object source, ParserContext parserContext) {
RootBeanDefinition adapterDef = createBeanDefinition(DefaultMethodEndpointAdapter.class, source);
ManagedList<BeanMetadataElement> argumentResolvers = new ManagedList<BeanMetadataElement>();
argumentResolvers.setSource(source);
ManagedList<BeanMetadataElement> argumentResolvers = new ManagedList<BeanMetadataElement>();
argumentResolvers.setSource(source);
ManagedList<BeanMetadataElement> returnValueHandlers = new ManagedList<BeanMetadataElement>();
returnValueHandlers.setSource(source);
ManagedList<BeanMetadataElement> returnValueHandlers = new ManagedList<BeanMetadataElement>();
returnValueHandlers.setSource(source);
argumentResolvers.add(createBeanDefinition(MessageContextMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(XPathParamMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(SoapMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(SoapHeaderElementMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(MessageContextMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(XPathParamMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(SoapMethodArgumentResolver.class, source));
argumentResolvers.add(createBeanDefinition(SoapHeaderElementMethodArgumentResolver.class, source));
RuntimeBeanReference domProcessor = createBeanReference(DomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(domProcessor);
returnValueHandlers.add(domProcessor);
RuntimeBeanReference domProcessor = createBeanReference(DomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(domProcessor);
returnValueHandlers.add(domProcessor);
RuntimeBeanReference sourceProcessor =
createBeanReference(SourcePayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(sourceProcessor);
returnValueHandlers.add(sourceProcessor);
RuntimeBeanReference sourceProcessor =
createBeanReference(SourcePayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(sourceProcessor);
returnValueHandlers.add(sourceProcessor);
if (dom4jPresent) {
RuntimeBeanReference dom4jProcessor =
createBeanReference(Dom4jPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(dom4jProcessor);
returnValueHandlers.add(dom4jProcessor);
}
if (jaxb2Present) {
RuntimeBeanReference xmlRootElementProcessor =
createBeanReference(XmlRootElementPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(xmlRootElementProcessor);
returnValueHandlers.add(xmlRootElementProcessor);
if (dom4jPresent) {
RuntimeBeanReference dom4jProcessor =
createBeanReference(Dom4jPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(dom4jProcessor);
returnValueHandlers.add(dom4jProcessor);
}
if (jaxb2Present) {
RuntimeBeanReference xmlRootElementProcessor =
createBeanReference(XmlRootElementPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(xmlRootElementProcessor);
returnValueHandlers.add(xmlRootElementProcessor);
RuntimeBeanReference jaxbElementProcessor =
createBeanReference(JaxbElementPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(jaxbElementProcessor);
returnValueHandlers.add(jaxbElementProcessor);
}
if (jdomPresent) {
RuntimeBeanReference jdomProcessor =
createBeanReference(JDomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(jdomProcessor);
returnValueHandlers.add(jdomProcessor);
}
if (staxPresent) {
argumentResolvers.add(createBeanDefinition(StaxPayloadMethodArgumentResolver.class, source));
}
if (xomPresent) {
RuntimeBeanReference xomProcessor =
createBeanReference(XomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(xomProcessor);
returnValueHandlers.add(xomProcessor);
}
if (element.hasAttribute("marshaller")) {
RuntimeBeanReference marshallerReference = new RuntimeBeanReference(element.getAttribute("marshaller"));
RuntimeBeanReference unmarshallerReference;
if (element.hasAttribute("unmarshaller")) {
unmarshallerReference = new RuntimeBeanReference(element.getAttribute("unmarshaller"));
}
else {
unmarshallerReference = marshallerReference;
}
RuntimeBeanReference jaxbElementProcessor =
createBeanReference(JaxbElementPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(jaxbElementProcessor);
returnValueHandlers.add(jaxbElementProcessor);
}
if (jdomPresent) {
RuntimeBeanReference jdomProcessor =
createBeanReference(JDomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(jdomProcessor);
returnValueHandlers.add(jdomProcessor);
}
if (staxPresent) {
argumentResolvers.add(createBeanDefinition(StaxPayloadMethodArgumentResolver.class, source));
}
if (xomPresent) {
RuntimeBeanReference xomProcessor =
createBeanReference(XomPayloadMethodProcessor.class, source, parserContext);
argumentResolvers.add(xomProcessor);
returnValueHandlers.add(xomProcessor);
}
if (element.hasAttribute("marshaller")) {
RuntimeBeanReference marshallerReference = new RuntimeBeanReference(element.getAttribute("marshaller"));
RuntimeBeanReference unmarshallerReference;
if (element.hasAttribute("unmarshaller")) {
unmarshallerReference = new RuntimeBeanReference(element.getAttribute("unmarshaller"));
}
else {
unmarshallerReference = marshallerReference;
}
RootBeanDefinition marshallingProcessorDef =
createBeanDefinition(MarshallingPayloadMethodProcessor.class, source);
marshallingProcessorDef.getPropertyValues().add("marshaller", marshallerReference);
marshallingProcessorDef.getPropertyValues().add("unmarshaller", unmarshallerReference);
argumentResolvers.add(marshallingProcessorDef);
returnValueHandlers.add(marshallingProcessorDef);
}
RootBeanDefinition marshallingProcessorDef =
createBeanDefinition(MarshallingPayloadMethodProcessor.class, source);
marshallingProcessorDef.getPropertyValues().add("marshaller", marshallerReference);
marshallingProcessorDef.getPropertyValues().add("unmarshaller", unmarshallerReference);
argumentResolvers.add(marshallingProcessorDef);
returnValueHandlers.add(marshallingProcessorDef);
}
adapterDef.getPropertyValues().add("methodArgumentResolvers", argumentResolvers);
adapterDef.getPropertyValues().add("methodReturnValueHandlers", returnValueHandlers);
adapterDef.getPropertyValues().add("methodArgumentResolvers", argumentResolvers);
adapterDef.getPropertyValues().add("methodReturnValueHandlers", returnValueHandlers);
parserContext.getReaderContext().registerWithGeneratedName(adapterDef);
}
parserContext.getReaderContext().registerWithGeneratedName(adapterDef);
}
private void registerEndpointExceptionResolvers(Object source, ParserContext parserContext) {
RootBeanDefinition annotationResolverDef =
createBeanDefinition(SoapFaultAnnotationExceptionResolver.class, source);
annotationResolverDef.getPropertyValues().add("order", 0);
parserContext.getReaderContext().registerWithGeneratedName(annotationResolverDef);
private void registerEndpointExceptionResolvers(Object source, ParserContext parserContext) {
RootBeanDefinition annotationResolverDef =
createBeanDefinition(SoapFaultAnnotationExceptionResolver.class, source);
annotationResolverDef.getPropertyValues().add("order", 0);
parserContext.getReaderContext().registerWithGeneratedName(annotationResolverDef);
RootBeanDefinition simpleResolverDef =
createBeanDefinition(SimpleSoapExceptionResolver.class, source);
simpleResolverDef.getPropertyValues().add("order", Ordered.LOWEST_PRECEDENCE);
parserContext.getReaderContext().registerWithGeneratedName(simpleResolverDef);
}
RootBeanDefinition simpleResolverDef =
createBeanDefinition(SimpleSoapExceptionResolver.class, source);
simpleResolverDef.getPropertyValues().add("order", Ordered.LOWEST_PRECEDENCE);
parserContext.getReaderContext().registerWithGeneratedName(simpleResolverDef);
}
private RuntimeBeanReference createBeanReference(Class<?> beanClass, Object source, ParserContext parserContext) {
RootBeanDefinition beanDefinition = createBeanDefinition(beanClass, source);
String beanName = parserContext.getReaderContext().registerWithGeneratedName(beanDefinition);
parserContext.registerComponent(new BeanComponentDefinition(beanDefinition, beanName));
return new RuntimeBeanReference(beanName);
}
private RuntimeBeanReference createBeanReference(Class<?> beanClass, Object source, ParserContext parserContext) {
RootBeanDefinition beanDefinition = createBeanDefinition(beanClass, source);
String beanName = parserContext.getReaderContext().registerWithGeneratedName(beanDefinition);
parserContext.registerComponent(new BeanComponentDefinition(beanDefinition, beanName));
return new RuntimeBeanReference(beanName);
}
private RootBeanDefinition createBeanDefinition(Class<?> beanClass, Object source) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSource(source);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return beanDefinition;
}
private RootBeanDefinition createBeanDefinition(Class<?> beanClass, Object source) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSource(source);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return beanDefinition;
}
}

View File

@@ -42,68 +42,68 @@ import org.w3c.dom.Element;
*/
class DynamicWsdlBeanDefinitionParser extends AbstractBeanDefinitionParser {
private static final boolean commonsSchemaPresent = ClassUtils.isPresent("org.apache.ws.commons.schema.XmlSchema",
DynamicWsdlBeanDefinitionParser.class.getClassLoader());
private static final boolean commonsSchemaPresent = ClassUtils.isPresent("org.apache.ws.commons.schema.XmlSchema",
DynamicWsdlBeanDefinitionParser.class.getClassLoader());
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
BeanDefinitionBuilder wsdlBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultWsdl11Definition.class);
wsdlBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
wsdlBuilder.getRawBeanDefinition().setSource(source);
BeanDefinitionBuilder wsdlBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultWsdl11Definition.class);
wsdlBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
wsdlBuilder.getRawBeanDefinition().setSource(source);
addProperty(element, wsdlBuilder, "portTypeName");
addProperty(element, wsdlBuilder, "targetNamespace");
addProperty(element, wsdlBuilder, "requestSuffix");
addProperty(element, wsdlBuilder, "responseSuffix");
addProperty(element, wsdlBuilder, "faultSuffix");
addProperty(element, wsdlBuilder, "createSoap11Binding");
addProperty(element, wsdlBuilder, "createSoap12Binding");
addProperty(element, wsdlBuilder, "transportUri");
addProperty(element, wsdlBuilder, "locationUri");
addProperty(element, wsdlBuilder, "serviceName");
addProperty(element, wsdlBuilder, "portTypeName");
addProperty(element, wsdlBuilder, "targetNamespace");
addProperty(element, wsdlBuilder, "requestSuffix");
addProperty(element, wsdlBuilder, "responseSuffix");
addProperty(element, wsdlBuilder, "faultSuffix");
addProperty(element, wsdlBuilder, "createSoap11Binding");
addProperty(element, wsdlBuilder, "createSoap12Binding");
addProperty(element, wsdlBuilder, "transportUri");
addProperty(element, wsdlBuilder, "locationUri");
addProperty(element, wsdlBuilder, "serviceName");
List<Element> schemas = DomUtils.getChildElementsByTagName(element, "xsd");
if (commonsSchemaPresent) {
RootBeanDefinition collectionDef = createBeanDefinition(CommonsXsdSchemaCollection.class, source);
collectionDef.getPropertyValues().addPropertyValue("inline", "true");
ManagedList<String> xsds = new ManagedList<String>();
xsds.setSource(source);
for (Element schema : schemas) {
xsds.add(schema.getAttribute("location"));
}
collectionDef.getPropertyValues().addPropertyValue("xsds", xsds);
String collectionName = parserContext.getReaderContext().registerWithGeneratedName(collectionDef);
wsdlBuilder.addPropertyReference("schemaCollection", collectionName);
}
else {
if (schemas.size() > 1) {
throw new IllegalArgumentException(
"Multiple <xsd/> elements requires Commons XMLSchema." +
"Please put Commons XMLSchema on the classpath.");
}
RootBeanDefinition schemaDef = createBeanDefinition(SimpleXsdSchema.class, source);
Element schema = schemas.iterator().next();
schemaDef.getPropertyValues().addPropertyValue("xsd", schema.getAttribute("location"));
String schemaName = parserContext.getReaderContext().registerWithGeneratedName(schemaDef);
wsdlBuilder.addPropertyReference("schema", schemaName);
}
return wsdlBuilder.getBeanDefinition();
}
List<Element> schemas = DomUtils.getChildElementsByTagName(element, "xsd");
if (commonsSchemaPresent) {
RootBeanDefinition collectionDef = createBeanDefinition(CommonsXsdSchemaCollection.class, source);
collectionDef.getPropertyValues().addPropertyValue("inline", "true");
ManagedList<String> xsds = new ManagedList<String>();
xsds.setSource(source);
for (Element schema : schemas) {
xsds.add(schema.getAttribute("location"));
}
collectionDef.getPropertyValues().addPropertyValue("xsds", xsds);
String collectionName = parserContext.getReaderContext().registerWithGeneratedName(collectionDef);
wsdlBuilder.addPropertyReference("schemaCollection", collectionName);
}
else {
if (schemas.size() > 1) {
throw new IllegalArgumentException(
"Multiple <xsd/> elements requires Commons XMLSchema." +
"Please put Commons XMLSchema on the classpath.");
}
RootBeanDefinition schemaDef = createBeanDefinition(SimpleXsdSchema.class, source);
Element schema = schemas.iterator().next();
schemaDef.getPropertyValues().addPropertyValue("xsd", schema.getAttribute("location"));
String schemaName = parserContext.getReaderContext().registerWithGeneratedName(schemaDef);
wsdlBuilder.addPropertyReference("schema", schemaName);
}
return wsdlBuilder.getBeanDefinition();
}
private void addProperty(Element element, BeanDefinitionBuilder builder, String propertyName) {
String propertyValue = element.getAttribute(propertyName);
if (StringUtils.hasText(propertyValue)) {
builder.addPropertyValue(propertyName, propertyValue);
}
}
private void addProperty(Element element, BeanDefinitionBuilder builder, String propertyName) {
String propertyValue = element.getAttribute(propertyName);
if (StringUtils.hasText(propertyValue)) {
builder.addPropertyValue(propertyName, propertyValue);
}
}
private RootBeanDefinition createBeanDefinition(Class<?> beanClass, Object source) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSource(source);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return beanDefinition;
}
private RootBeanDefinition createBeanDefinition(Class<?> beanClass, Object source) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSource(source);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return beanDefinition;
}
}

View File

@@ -44,151 +44,151 @@ import org.springframework.ws.soap.server.endpoint.interceptor.SoapActionSmartEn
*/
class InterceptorsBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
CompositeComponentDefinition compDefinition =
new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
parserContext.pushContainingComponent(compDefinition);
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
CompositeComponentDefinition compDefinition =
new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
parserContext.pushContainingComponent(compDefinition);
List<Element> childElements = DomUtils.getChildElements(element);
for (Element childElement : childElements) {
if ("bean".equals(childElement.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(DelegatingSmartSoapEndpointInterceptor.class, childElement,
parserContext);
BeanDefinitionHolder interceptorDef = createInterceptorDefinition(parserContext, childElement);
List<Element> childElements = DomUtils.getChildElements(element);
for (Element childElement : childElements) {
if ("bean".equals(childElement.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(DelegatingSmartSoapEndpointInterceptor.class, childElement,
parserContext);
BeanDefinitionHolder interceptorDef = createInterceptorDefinition(parserContext, childElement);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(childElement.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(DelegatingSmartSoapEndpointInterceptor.class, childElement,
parserContext);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(childElement.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(DelegatingSmartSoapEndpointInterceptor.class, childElement,
parserContext);
BeanReference interceptorRef = createInterceptorReference(parserContext, childElement);
BeanReference interceptorRef = createInterceptorReference(parserContext, childElement);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
registerSmartInterceptor(parserContext, smartInterceptorDef);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("payloadRoot".equals(childElement.getLocalName())) {
List<Element> payloadRootChildren = DomUtils.getChildElements(childElement);
for (Element payloadRootChild : payloadRootChildren) {
if ("bean".equals(payloadRootChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(PayloadRootSmartSoapEndpointInterceptor.class,
childElement, parserContext);
BeanDefinitionHolder interceptorDef =
createInterceptorDefinition(parserContext, payloadRootChild);
}
else if ("payloadRoot".equals(childElement.getLocalName())) {
List<Element> payloadRootChildren = DomUtils.getChildElements(childElement);
for (Element payloadRootChild : payloadRootChildren) {
if ("bean".equals(payloadRootChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(PayloadRootSmartSoapEndpointInterceptor.class,
childElement, parserContext);
BeanDefinitionHolder interceptorDef =
createInterceptorDefinition(parserContext, payloadRootChild);
String namespaceUri = childElement.getAttribute("namespaceUri");
String localPart = childElement.getAttribute("localPart");
String namespaceUri = childElement.getAttribute("namespaceUri");
String localPart = childElement.getAttribute("localPart");
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, namespaceUri);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(2, localPart);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, namespaceUri);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(2, localPart);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(payloadRootChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(PayloadRootSmartSoapEndpointInterceptor.class,
childElement, parserContext);
BeanReference interceptorRef = createInterceptorReference(parserContext, payloadRootChild);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(payloadRootChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(PayloadRootSmartSoapEndpointInterceptor.class,
childElement, parserContext);
BeanReference interceptorRef = createInterceptorReference(parserContext, payloadRootChild);
String namespaceUri = childElement.getAttribute("namespaceUri");
String localPart = childElement.getAttribute("localPart");
String namespaceUri = childElement.getAttribute("namespaceUri");
String localPart = childElement.getAttribute("localPart");
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, namespaceUri);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(2, localPart);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, namespaceUri);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(2, localPart);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
}
}
else if ("soapAction".equals(childElement.getLocalName())) {
List<Element> soapActionChildren = DomUtils.getChildElements(childElement);
for (Element soapActionChild : soapActionChildren) {
if ("bean".equals(soapActionChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(SoapActionSmartEndpointInterceptor.class, childElement,
parserContext);
BeanDefinitionHolder interceptorDef =
createInterceptorDefinition(parserContext, soapActionChild);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
}
}
else if ("soapAction".equals(childElement.getLocalName())) {
List<Element> soapActionChildren = DomUtils.getChildElements(childElement);
for (Element soapActionChild : soapActionChildren) {
if ("bean".equals(soapActionChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(SoapActionSmartEndpointInterceptor.class, childElement,
parserContext);
BeanDefinitionHolder interceptorDef =
createInterceptorDefinition(parserContext, soapActionChild);
String soapAction = childElement.getAttribute("value");
String soapAction = childElement.getAttribute("value");
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, soapAction);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorDef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, soapAction);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(soapActionChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(SoapActionSmartEndpointInterceptor.class, childElement,
parserContext);
BeanReference interceptorRef = createInterceptorReference(parserContext, soapActionChild);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
else if ("ref".equals(soapActionChild.getLocalName())) {
RootBeanDefinition smartInterceptorDef =
createSmartInterceptorDefinition(SoapActionSmartEndpointInterceptor.class, childElement,
parserContext);
BeanReference interceptorRef = createInterceptorReference(parserContext, soapActionChild);
String soapAction = childElement.getAttribute("value");
String soapAction = childElement.getAttribute("value");
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, soapAction);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorRef);
smartInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, soapAction);
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
}
}
}
registerSmartInterceptor(parserContext, smartInterceptorDef);
}
}
}
}
parserContext.popAndRegisterContainingComponent();
return null;
}
parserContext.popAndRegisterContainingComponent();
return null;
}
private void registerSmartInterceptor(ParserContext parserContext, RootBeanDefinition smartInterceptorDef) {
String mappedInterceptorName = parserContext.getReaderContext().registerWithGeneratedName(smartInterceptorDef);
parserContext.registerComponent(new BeanComponentDefinition(smartInterceptorDef, mappedInterceptorName));
}
private void registerSmartInterceptor(ParserContext parserContext, RootBeanDefinition smartInterceptorDef) {
String mappedInterceptorName = parserContext.getReaderContext().registerWithGeneratedName(smartInterceptorDef);
parserContext.registerComponent(new BeanComponentDefinition(smartInterceptorDef, mappedInterceptorName));
}
private BeanDefinitionHolder createInterceptorDefinition(ParserContext parserContext, Element element) {
BeanDefinitionHolder interceptorDef = parserContext.getDelegate().parseBeanDefinitionElement(element);
interceptorDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(element, interceptorDef);
return interceptorDef;
}
private BeanDefinitionHolder createInterceptorDefinition(ParserContext parserContext, Element element) {
BeanDefinitionHolder interceptorDef = parserContext.getDelegate().parseBeanDefinitionElement(element);
interceptorDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(element, interceptorDef);
return interceptorDef;
}
private BeanReference createInterceptorReference(ParserContext parserContext, Element element) {
// A generic reference to any name of any bean.
String refName = element.getAttribute("bean");
if (!StringUtils.hasLength(refName)) {
// A reference to the id of another bean in the same XML file.
refName = element.getAttribute("local");
if (!StringUtils.hasLength(refName)) {
error(parserContext, "Either 'bean' or 'local' is required for <ref> element", element);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error(parserContext, "<ref> element contains empty target attribute", element);
return null;
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(parserContext.extractSource(element));
return ref;
}
private BeanReference createInterceptorReference(ParserContext parserContext, Element element) {
// A generic reference to any name of any bean.
String refName = element.getAttribute("bean");
if (!StringUtils.hasLength(refName)) {
// A reference to the id of another bean in the same XML file.
refName = element.getAttribute("local");
if (!StringUtils.hasLength(refName)) {
error(parserContext, "Either 'bean' or 'local' is required for <ref> element", element);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error(parserContext, "<ref> element contains empty target attribute", element);
return null;
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(parserContext.extractSource(element));
return ref;
}
private RootBeanDefinition createSmartInterceptorDefinition(Class<? extends SmartEndpointInterceptor> interceptorClass,
Element element,
ParserContext parserContext) {
RootBeanDefinition smartInterceptorDef = new RootBeanDefinition(interceptorClass);
smartInterceptorDef.setSource(parserContext.extractSource(element));
smartInterceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return smartInterceptorDef;
}
private RootBeanDefinition createSmartInterceptorDefinition(Class<? extends SmartEndpointInterceptor> interceptorClass,
Element element,
ParserContext parserContext) {
RootBeanDefinition smartInterceptorDef = new RootBeanDefinition(interceptorClass);
smartInterceptorDef.setSource(parserContext.extractSource(element));
smartInterceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
return smartInterceptorDef;
}
private void error(ParserContext parserContext, String message, Object source) {
parserContext.getDelegate().getReaderContext().error(message, source);
}
private void error(ParserContext parserContext, String message, Object source) {
parserContext.getDelegate().getReaderContext().error(message, source);
}
}

View File

@@ -34,39 +34,39 @@ import org.w3c.dom.Element;
@Deprecated
class MarshallingEndpointsBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
private static final String GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter";
private static final String GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter";
private static final boolean genericAdapterPresent =
ClassUtils.isPresent(GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME,
MarshallingEndpointsBeanDefinitionParser.class.getClassLoader());
private static final boolean genericAdapterPresent =
ClassUtils.isPresent(GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME,
MarshallingEndpointsBeanDefinitionParser.class.getClassLoader());
private static final String MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter";
private static final String MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter";
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected String getBeanClassName(Element element) {
if (genericAdapterPresent) {
return GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
return MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
@Override
protected String getBeanClassName(Element element) {
if (genericAdapterPresent) {
return GENERIC_MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
return MARSHALLING_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
String marshallerName = element.getAttribute("marshaller");
if (StringUtils.hasText(marshallerName)) {
beanDefinitionBuilder.addPropertyReference("marshaller", marshallerName);
}
String unmarshallerName = element.getAttribute("unmarshaller");
if (StringUtils.hasText(unmarshallerName)) {
beanDefinitionBuilder.addPropertyReference("unmarshaller", unmarshallerName);
}
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
String marshallerName = element.getAttribute("marshaller");
if (StringUtils.hasText(marshallerName)) {
beanDefinitionBuilder.addPropertyReference("marshaller", marshallerName);
}
String unmarshallerName = element.getAttribute("unmarshaller");
if (StringUtils.hasText(unmarshallerName)) {
beanDefinitionBuilder.addPropertyReference("unmarshaller", unmarshallerName);
}
}
}

View File

@@ -33,39 +33,39 @@ import org.w3c.dom.Element;
*/
class StaticWsdlBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
private static final String CLASS_NAME = "org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition";
private static final String CLASS_NAME = "org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition";
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected String getBeanClassName(Element element) {
return CLASS_NAME;
}
@Override
protected String getBeanClassName(Element element) {
return CLASS_NAME;
}
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
String id = element.getAttribute(ID_ATTRIBUTE);
if (StringUtils.hasLength(id)) {
return id;
}
String location = element.getAttribute("location");
if (StringUtils.hasLength(location)) {
String filename = StringUtils.stripFilenameExtension(StringUtils.getFilename(location));
if (StringUtils.hasLength(filename)) {
return filename;
}
}
return parserContext.getReaderContext().generateBeanName(definition);
}
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
String id = element.getAttribute(ID_ATTRIBUTE);
if (StringUtils.hasLength(id)) {
return id;
}
String location = element.getAttribute("location");
if (StringUtils.hasLength(location)) {
String filename = StringUtils.stripFilenameExtension(StringUtils.getFilename(location));
if (StringUtils.hasLength(filename)) {
return filename;
}
}
return parserContext.getReaderContext().generateBeanName(definition);
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
String location = element.getAttribute("location");
beanDefinitionBuilder.addPropertyValue("wsdl", location);
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
String location = element.getAttribute("location");
beanDefinitionBuilder.addPropertyValue("wsdl", location);
}
}

View File

@@ -27,14 +27,14 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
*/
public class WebServicesNamespaceHandler extends NamespaceHandlerSupport {
@Override
@SuppressWarnings("deprecation")
public void init() {
registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser());
registerBeanDefinitionParser("static-wsdl", new StaticWsdlBeanDefinitionParser());
registerBeanDefinitionParser("dynamic-wsdl", new DynamicWsdlBeanDefinitionParser());
registerBeanDefinitionParser("marshalling-endpoints", new MarshallingEndpointsBeanDefinitionParser());
registerBeanDefinitionParser("xpath-endpoints", new XPathEndpointsBeanDefinitionParser());
}
@Override
@SuppressWarnings("deprecation")
public void init() {
registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser());
registerBeanDefinitionParser("static-wsdl", new StaticWsdlBeanDefinitionParser());
registerBeanDefinitionParser("dynamic-wsdl", new DynamicWsdlBeanDefinitionParser());
registerBeanDefinitionParser("marshalling-endpoints", new MarshallingEndpointsBeanDefinitionParser());
registerBeanDefinitionParser("xpath-endpoints", new XPathEndpointsBeanDefinitionParser());
}
}

View File

@@ -36,31 +36,31 @@ import org.w3c.dom.Element;
@Deprecated
class XPathEndpointsBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
private static final String XPATH_PARAM_ANNOTATION_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.XPathParamAnnotationMethodEndpointAdapter";
private static final String XPATH_PARAM_ANNOTATION_METHOD_ENDPOINT_ADAPTER_CLASS_NAME =
"org.springframework.ws.server.endpoint.adapter.XPathParamAnnotationMethodEndpointAdapter";
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected String getBeanClassName(Element element) {
return XPATH_PARAM_ANNOTATION_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
@Override
protected String getBeanClassName(Element element) {
return XPATH_PARAM_ANNOTATION_METHOD_ENDPOINT_ADAPTER_CLASS_NAME;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
List<Element> namespaceElements = DomUtils.getChildElementsByTagName(element, "namespace");
if (!namespaceElements.isEmpty()) {
Properties namespaces = new Properties();
for (Element namespaceElement : namespaceElements) {
String prefix = namespaceElement.getAttribute("prefix");
String uri = namespaceElement.getAttribute("uri");
namespaces.setProperty(prefix, uri);
}
beanDefinitionBuilder.addPropertyValue("namespaces", namespaces);
}
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder beanDefinitionBuilder) {
List<Element> namespaceElements = DomUtils.getChildElementsByTagName(element, "namespace");
if (!namespaceElements.isEmpty()) {
Properties namespaces = new Properties();
for (Element namespaceElement : namespaceElements) {
String prefix = namespaceElement.getAttribute("prefix");
String uri = namespaceElement.getAttribute("uri");
namespaces.setProperty(prefix, uri);
}
beanDefinitionBuilder.addPropertyValue("namespaces", namespaces);
}
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -48,17 +48,17 @@ import org.springframework.context.annotation.Import;
* &#064;ComponentScan(basePackageClasses = { MyConfiguration.class })
* public class MyConfiguration extends WsConfigurerAdapter {
*
* &#064;Override
* public void addInterceptors(List&lt;EndpointInterceptor&gt; interceptors) {
* interceptors.add(new MyInterceptor());
* }
* &#064;Override
* public void addInterceptors(List&lt;EndpointInterceptor&gt; interceptors) {
* interceptors.add(new MyInterceptor());
* }
*
* &#064;Override
* public void addArgumentResolvers(List&lt;MethodArgumentResolver&gt; argumentResolvers) {
* argumentResolvers.add(new MyArgumentResolver());
* }
* &#064;Override
* public void addArgumentResolvers(List&lt;MethodArgumentResolver&gt; argumentResolvers) {
* argumentResolvers.add(new MyArgumentResolver());
* }
*
* // More overridden methods ...
* // More overridden methods ...
* }
* </pre>
*
@@ -72,17 +72,17 @@ import org.springframework.context.annotation.Import;
* &#064;ComponentScan(basePackageClasses = { MyConfiguration.class })
* public class MyConfiguration extends WsConfigurationSupport {
*
* &#064;Override
* public void addInterceptors(List&lt;EndpointInterceptor&gt; interceptors) {
* interceptors.add(new MyInterceptor());
* }
* &#064;Override
* public void addInterceptors(List&lt;EndpointInterceptor&gt; interceptors) {
* interceptors.add(new MyInterceptor());
* }
*
* &#064;Bean
* &#064;Override
* public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() {
* &#064;Bean
* &#064;Override
* public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() {
* // Create or delegate to "super" to create and
* // customize properties of DefaultMethodEndpointAdapter
* }
* }
* }
* </pre>
*

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -50,28 +50,28 @@ import org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationM
*
* <p>This class registers the following {@link EndpointMapping}s:
* <ul>
* <li>{@link PayloadRootAnnotationMethodEndpointMapping}
* ordered at 0 for mapping requests to {@link PayloadRoot @PayloadRoot} annotated
* controller methods.
* <li>{@link SoapActionAnnotationMethodEndpointMapping}
* ordered at 1 for mapping requests to {@link SoapAction @SoapAction} annotated
* controller methods.
* <li>{@link AnnotationActionEndpointMapping}
* ordered at 2 for mapping requests to {@link Action @Action} annotated
* controller methods.
* <li>{@link PayloadRootAnnotationMethodEndpointMapping}
* ordered at 0 for mapping requests to {@link PayloadRoot @PayloadRoot} annotated
* controller methods.
* <li>{@link SoapActionAnnotationMethodEndpointMapping}
* ordered at 1 for mapping requests to {@link SoapAction @SoapAction} annotated
* controller methods.
* <li>{@link AnnotationActionEndpointMapping}
* ordered at 2 for mapping requests to {@link Action @Action} annotated
* controller methods.
* </ul>
*
* <p>Registers one {@link EndpointAdapter}:
* <ul>
* <li>{@link DefaultMethodEndpointAdapter}
* for processing requests with annotated endpoint methods.
* <li>{@link DefaultMethodEndpointAdapter}
* for processing requests with annotated endpoint methods.
* </ul>
*
* <p>Registers the following {@link EndpointExceptionResolver}s:
* <ul>
* <li>{@link SoapFaultAnnotationExceptionResolver} for handling exceptions
* annotated with {@link SoapFault @SoapFault}.
* <li>{@link SimpleSoapExceptionResolver} for creating default exceptions.
* <li>{@link SoapFaultAnnotationExceptionResolver} for handling exceptions
* annotated with {@link SoapFault @SoapFault}.
* <li>{@link SimpleSoapExceptionResolver} for creating default exceptions.
* </ul>
*
* @see EnableWs
@@ -149,8 +149,8 @@ public class WsConfigurationSupport {
* through annotated endpoint methods. Consider overriding one of these
* other more fine-grained methods:
* <ul>
* <li>{@link #addArgumentResolvers(List)} for adding custom argument resolvers.
* <li>{@link #addReturnValueHandlers(List)} for adding custom return value handlers.
* <li>{@link #addArgumentResolvers(List)} for adding custom argument resolvers.
* <li>{@link #addReturnValueHandlers(List)} for adding custom return value handlers.
* </ul>
*/
@Bean
@@ -174,7 +174,7 @@ public class WsConfigurationSupport {
* Add custom {@link MethodArgumentResolver}s to use in addition to
* the ones registered by default.
* @param argumentResolvers the list of custom converters;
* initially an empty list.
* initially an empty list.
*/
protected void addArgumentResolvers(List<MethodArgumentResolver> argumentResolvers) {
}

View File

@@ -29,41 +29,41 @@ import org.springframework.util.StringUtils;
*/
public abstract class AbstractMessageContext implements MessageContext {
/**
* Keys are {@code Strings}, values are {@code Objects}. Lazily initialized by
* {@code getProperties()}.
*/
private Map<String, Object> properties;
/**
* Keys are {@code Strings}, values are {@code Objects}. Lazily initialized by
* {@code getProperties()}.
*/
private Map<String, Object> properties;
@Override
public boolean containsProperty(String name) {
return getProperties().containsKey(name);
}
@Override
public boolean containsProperty(String name) {
return getProperties().containsKey(name);
}
@Override
public Object getProperty(String name) {
return getProperties().get(name);
}
@Override
public Object getProperty(String name) {
return getProperties().get(name);
}
@Override
public String[] getPropertyNames() {
return StringUtils.toStringArray(getProperties().keySet());
}
@Override
public String[] getPropertyNames() {
return StringUtils.toStringArray(getProperties().keySet());
}
@Override
public void removeProperty(String name) {
getProperties().remove(name);
}
@Override
public void removeProperty(String name) {
getProperties().remove(name);
}
@Override
public void setProperty(String name, Object value) {
getProperties().put(name, value);
}
@Override
public void setProperty(String name, Object value) {
getProperties().put(name, value);
}
private Map<String, Object> getProperties() {
if (properties == null) {
properties = new HashMap<String, Object>();
}
return properties;
}
private Map<String, Object> getProperties() {
if (properties == null) {
properties = new HashMap<String, Object>();
}
return properties;
}
}

View File

@@ -31,70 +31,70 @@ import org.springframework.ws.WebServiceMessageFactory;
*/
public class DefaultMessageContext extends AbstractMessageContext {
private final WebServiceMessageFactory messageFactory;
private final WebServiceMessageFactory messageFactory;
private final WebServiceMessage request;
private final WebServiceMessage request;
private WebServiceMessage response;
private WebServiceMessage response;
/** Construct a new, empty instance of the {@code DefaultMessageContext} with the given message factory. */
public DefaultMessageContext(WebServiceMessageFactory messageFactory) {
this(messageFactory.createWebServiceMessage(), messageFactory);
}
/** Construct a new, empty instance of the {@code DefaultMessageContext} with the given message factory. */
public DefaultMessageContext(WebServiceMessageFactory messageFactory) {
this(messageFactory.createWebServiceMessage(), messageFactory);
}
/**
* Construct a new instance of the {@code DefaultMessageContext} with the given request message and message
* factory.
*/
public DefaultMessageContext(WebServiceMessage request, WebServiceMessageFactory messageFactory) {
Assert.notNull(request, "request must not be null");
Assert.notNull(messageFactory, "messageFactory must not be null");
this.request = request;
this.messageFactory = messageFactory;
}
/**
* Construct a new instance of the {@code DefaultMessageContext} with the given request message and message
* factory.
*/
public DefaultMessageContext(WebServiceMessage request, WebServiceMessageFactory messageFactory) {
Assert.notNull(request, "request must not be null");
Assert.notNull(messageFactory, "messageFactory must not be null");
this.request = request;
this.messageFactory = messageFactory;
}
@Override
public WebServiceMessage getRequest() {
return request;
}
@Override
public WebServiceMessage getRequest() {
return request;
}
@Override
public boolean hasResponse() {
return response != null;
}
@Override
public boolean hasResponse() {
return response != null;
}
@Override
public WebServiceMessage getResponse() {
if (response == null) {
response = messageFactory.createWebServiceMessage();
}
return response;
}
@Override
public WebServiceMessage getResponse() {
if (response == null) {
response = messageFactory.createWebServiceMessage();
}
return response;
}
@Override
public void setResponse(WebServiceMessage response) {
checkForResponse();
this.response = response;
}
@Override
public void setResponse(WebServiceMessage response) {
checkForResponse();
this.response = response;
}
@Override
public void clearResponse() {
response = null;
}
@Override
public void clearResponse() {
response = null;
}
@Override
public void readResponse(InputStream inputStream) throws IOException {
checkForResponse();
response = messageFactory.createWebServiceMessage(inputStream);
}
@Override
public void readResponse(InputStream inputStream) throws IOException {
checkForResponse();
response = messageFactory.createWebServiceMessage(inputStream);
}
public WebServiceMessageFactory getMessageFactory() {
return messageFactory;
}
public WebServiceMessageFactory getMessageFactory() {
return messageFactory;
}
private void checkForResponse() throws IllegalStateException {
if (response != null) {
throw new IllegalStateException("Response message already created");
}
}
private void checkForResponse() throws IllegalStateException {
if (response != null) {
throw new IllegalStateException("Response message already created");
}
}
}

View File

@@ -36,90 +36,90 @@ import org.springframework.ws.server.EndpointInterceptor;
*/
public interface MessageContext {
/**
* Returns the request message.
*
* @return the request message
*/
WebServiceMessage getRequest();
/**
* Returns the request message.
*
* @return the request message
*/
WebServiceMessage getRequest();
/**
* Indicates whether this context has a response.
*
* @return {@code true} if this context has a response; {@code false} otherwise
*/
boolean hasResponse();
/**
* Indicates whether this context has a response.
*
* @return {@code true} if this context has a response; {@code false} otherwise
*/
boolean hasResponse();
/**
* Returns the response message. Creates a new response if no response is present.
*
* @return the response message
* @see #hasResponse()
*/
WebServiceMessage getResponse();
/**
* Returns the response message. Creates a new response if no response is present.
*
* @return the response message
* @see #hasResponse()
*/
WebServiceMessage getResponse();
/**
* Sets the response message.
*
* @param response the response message
* @throws IllegalStateException if a response has already been created
* @since 1.5.0
*/
void setResponse(WebServiceMessage response);
/**
* Sets the response message.
*
* @param response the response message
* @throws IllegalStateException if a response has already been created
* @since 1.5.0
*/
void setResponse(WebServiceMessage response);
/**
* Removes the response message, if any.
*
* @since 1.5.0
*/
void clearResponse();
/**
* Removes the response message, if any.
*
* @since 1.5.0
*/
void clearResponse();
/**
* Reads a response message from the given input stream.
*
* @param inputStream the stream to read the response from
* @throws IOException in case of I/O errors
* @throws IllegalStateException if a response has already been created
*/
void readResponse(InputStream inputStream) throws IOException;
/**
* Reads a response message from the given input stream.
*
* @param inputStream the stream to read the response from
* @throws IOException in case of I/O errors
* @throws IllegalStateException if a response has already been created
*/
void readResponse(InputStream inputStream) throws IOException;
/**
* Sets the name and value of a property associated with the {@code MessageContext}. If the
* {@code MessageContext} contains a value of the same property, the old value is replaced.
*
* @param name name of the property associated with the value
* @param value value of the property
*/
void setProperty(String name, Object value);
/**
* Sets the name and value of a property associated with the {@code MessageContext}. If the
* {@code MessageContext} contains a value of the same property, the old value is replaced.
*
* @param name name of the property associated with the value
* @param value value of the property
*/
void setProperty(String name, Object value);
/**
* Gets the value of a specific property from the {@code MessageContext}.
*
* @param name name of the property whose value is to be retrieved
* @return value of the property
*/
Object getProperty(String name);
/**
* Gets the value of a specific property from the {@code MessageContext}.
*
* @param name name of the property whose value is to be retrieved
* @return value of the property
*/
Object getProperty(String name);
/**
* Removes a property from the {@code MessageContext}.
*
* @param name name of the property to be removed
*/
void removeProperty(String name);
/**
* Removes a property from the {@code MessageContext}.
*
* @param name name of the property to be removed
*/
void removeProperty(String name);
/**
* Check if this message context contains a property with the given name.
*
* @param name the name of the property to look for
* @return {@code true} if the {@code MessageContext} contains the property; {@code false} otherwise
*/
boolean containsProperty(String name);
/**
* Check if this message context contains a property with the given name.
*
* @param name the name of the property to look for
* @return {@code true} if the {@code MessageContext} contains the property; {@code false} otherwise
*/
boolean containsProperty(String name);
/**
* Return the names of all properties in this {@code MessageContext}.
*
* @return the names of all properties in this context, or an empty array if none defined
*/
String[] getPropertyNames();
/**
* Return the names of all properties in this {@code MessageContext}.
*
* @return the names of all properties in this context, or an empty array if none defined
*/
String[] getPropertyNames();
}

View File

@@ -36,69 +36,69 @@ import org.springframework.util.Assert;
*/
public abstract class AbstractMimeMessage implements MimeMessage {
@Override
public final Attachment addAttachment(String contentId, File file) throws AttachmentException {
Assert.hasLength(contentId, "contentId must not be empty");
Assert.notNull(file, "File must not be null");
DataHandler dataHandler = new DataHandler(new FileDataSource(file));
return addAttachment(contentId, dataHandler);
}
@Override
public final Attachment addAttachment(String contentId, File file) throws AttachmentException {
Assert.hasLength(contentId, "contentId must not be empty");
Assert.notNull(file, "File must not be null");
DataHandler dataHandler = new DataHandler(new FileDataSource(file));
return addAttachment(contentId, dataHandler);
}
@Override
public final Attachment addAttachment(String contentId, InputStreamSource inputStreamSource, String contentType) {
Assert.hasLength(contentId, "contentId must not be empty");
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " +
"MIME requires an InputStreamSource that creates a fresh stream for every call.");
}
DataHandler dataHandler = new DataHandler(new InputStreamSourceDataSource(inputStreamSource, contentType));
return addAttachment(contentId, dataHandler);
}
@Override
public final Attachment addAttachment(String contentId, InputStreamSource inputStreamSource, String contentType) {
Assert.hasLength(contentId, "contentId must not be empty");
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " +
"MIME requires an InputStreamSource that creates a fresh stream for every call.");
}
DataHandler dataHandler = new DataHandler(new InputStreamSourceDataSource(inputStreamSource, contentType));
return addAttachment(contentId, dataHandler);
}
/**
* Activation framework {@code DataSource} that wraps a Spring {@code InputStreamSource}.
*
* @author Arjen Poutsma
* @since 1.0.0
*/
private static class InputStreamSourceDataSource implements DataSource {
/**
* Activation framework {@code DataSource} that wraps a Spring {@code InputStreamSource}.
*
* @author Arjen Poutsma
* @since 1.0.0
*/
private static class InputStreamSourceDataSource implements DataSource {
private final InputStreamSource inputStreamSource;
private final InputStreamSource inputStreamSource;
private final String contentType;
private final String contentType;
public InputStreamSourceDataSource(InputStreamSource inputStreamSource, String contentType) {
this.inputStreamSource = inputStreamSource;
this.contentType = contentType;
}
public InputStreamSourceDataSource(InputStreamSource inputStreamSource, String contentType) {
this.inputStreamSource = inputStreamSource;
this.contentType = contentType;
}
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public InputStream getInputStream() throws IOException {
return inputStreamSource.getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
if (inputStreamSource instanceof Resource) {
Resource resource = (Resource) inputStreamSource;
return resource.getFilename();
}
else {
throw new UnsupportedOperationException("DataSource name not available");
}
}
@Override
public String getName() {
if (inputStreamSource instanceof Resource) {
Resource resource = (Resource) inputStreamSource;
return resource.getFilename();
}
else {
throw new UnsupportedOperationException("DataSource name not available");
}
}
}
}
}

View File

@@ -30,40 +30,40 @@ import javax.activation.DataHandler;
*/
public interface Attachment {
/**
* Returns the content identifier of the attachment.
*
* @return the content id, or {@code null} if empty or not defined
*/
String getContentId();
/**
* Returns the content identifier of the attachment.
*
* @return the content id, or {@code null} if empty or not defined
*/
String getContentId();
/**
* Returns the content type of the attachment.
*
* @return the content type, or {@code null} if empty or not defined
*/
String getContentType();
/**
* Returns the content type of the attachment.
*
* @return the content type, or {@code null} if empty or not defined
*/
String getContentType();
/**
* Return an {@code InputStream} to read the contents of the attachment from. The user is responsible for
* closing the stream.
*
* @return the contents of the file as stream, or an empty stream if empty
* @throws IOException in case of access I/O errors
*/
InputStream getInputStream() throws IOException;
/**
* Return an {@code InputStream} to read the contents of the attachment from. The user is responsible for
* closing the stream.
*
* @return the contents of the file as stream, or an empty stream if empty
* @throws IOException in case of access I/O errors
*/
InputStream getInputStream() throws IOException;
/**
* Returns the size of the attachment in bytes. Returns {@code -1} if the size cannot be determined.
*
* @return the size of the attachment, {@code 0} if empty, or {@code -1} if the size cannot be determined
*/
long getSize();
/**
* Returns the size of the attachment in bytes. Returns {@code -1} if the size cannot be determined.
*
* @return the size of the attachment, {@code 0} if empty, or {@code -1} if the size cannot be determined
*/
long getSize();
/**
* Returns the data handler of the attachment.
*
* @return the data handler of the attachment
*/
DataHandler getDataHandler();
/**
* Returns the data handler of the attachment.
*
* @return the data handler of the attachment
*/
DataHandler getDataHandler();
}

View File

@@ -28,16 +28,16 @@ import org.springframework.ws.WebServiceMessageException;
@SuppressWarnings("serial")
public class AttachmentException extends WebServiceMessageException {
public AttachmentException(String msg) {
super(msg);
}
public AttachmentException(String msg) {
super(msg);
}
public AttachmentException(String msg, Throwable ex) {
super(msg, ex);
}
public AttachmentException(String msg, Throwable ex) {
super(msg, ex);
}
public AttachmentException(Throwable ex) {
super("Could not access body: " + ex.getMessage(), ex);
}
public AttachmentException(Throwable ex) {
super("Could not access body: " + ex.getMessage(), ex);
}
}

View File

@@ -33,75 +33,75 @@ import org.springframework.ws.WebServiceMessage;
*/
public interface MimeMessage extends WebServiceMessage {
/**
* Indicates whether this message is a XOP package.
*
* @return {@code true} when the constraints specified in <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#identifying_xop_documents">Identifying
* XOP Documents</a> are met.
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/
boolean isXopPackage();
/**
* Indicates whether this message is a XOP package.
*
* @return {@code true} when the constraints specified in <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#identifying_xop_documents">Identifying
* XOP Documents</a> are met.
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/
boolean isXopPackage();
/**
* Turns this message into a XOP package.
*
* @return {@code true} when the message is a XOP package
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/
boolean convertToXopPackage();
/**
* Turns this message into a XOP package.
*
* @return {@code true} when the message is a XOP package
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#xop_packages">XOP Packages</a>
*/
boolean convertToXopPackage();
/**
* Returns the {@link Attachment} with the specified content Id.
*
* @return the attachment with the specified content id; or {@code null} if it cannot be found
* @throws AttachmentException in case of errors
*/
Attachment getAttachment(String contentId) throws AttachmentException;
/**
* Returns the {@link Attachment} with the specified content Id.
*
* @return the attachment with the specified content id; or {@code null} if it cannot be found
* @throws AttachmentException in case of errors
*/
Attachment getAttachment(String contentId) throws AttachmentException;
/**
* Returns an {@code Iterator} over all {@link Attachment} objects that are part of this message.
*
* @return an iterator over all attachments
* @throws AttachmentException in case of errors
* @see Attachment
*/
Iterator<Attachment> getAttachments() throws AttachmentException;
/**
* Returns an {@code Iterator} over all {@link Attachment} objects that are part of this message.
*
* @return an iterator over all attachments
* @throws AttachmentException in case of errors
* @see Attachment
*/
Iterator<Attachment> getAttachments() throws AttachmentException;
/**
* Add an attachment to the message, taking the content from a {@link File}.
*
* <p>The content type will be determined by the name of the given content file. Do not use this for temporary files
* with arbitrary filenames (possibly ending in ".tmp" or the like)!
*
* @param contentId the content Id of the attachment
* @param file the file to take the content from
* @return the added attachment
* @throws AttachmentException in case of errors
*/
Attachment addAttachment(String contentId, File file) throws AttachmentException;
/**
* Add an attachment to the message, taking the content from a {@link File}.
*
* <p>The content type will be determined by the name of the given content file. Do not use this for temporary files
* with arbitrary filenames (possibly ending in ".tmp" or the like)!
*
* @param contentId the content Id of the attachment
* @param file the file to take the content from
* @return the added attachment
* @throws AttachmentException in case of errors
*/
Attachment addAttachment(String contentId, File file) throws AttachmentException;
/**
* Add an attachment to the message, taking the content from an {@link InputStreamSource}.
*
* <p>Note that the stream returned by the source needs to be a <em>fresh one on each call</em>, as underlying
* implementations can invoke {@link InputStreamSource#getInputStream()} multiple times.
*
* @param contentId the content Id of the attachment
* @param inputStreamSource the resource to take the content from (all of Spring's Resource implementations can be
* passed in here)
* @param contentType the content type to use for the element
* @return the added attachment
* @throws AttachmentException in case of errors
* @see org.springframework.core.io.Resource
*/
Attachment addAttachment(String contentId, InputStreamSource inputStreamSource, String contentType);
/**
* Add an attachment to the message, taking the content from an {@link InputStreamSource}.
*
* <p>Note that the stream returned by the source needs to be a <em>fresh one on each call</em>, as underlying
* implementations can invoke {@link InputStreamSource#getInputStream()} multiple times.
*
* @param contentId the content Id of the attachment
* @param inputStreamSource the resource to take the content from (all of Spring's Resource implementations can be
* passed in here)
* @param contentType the content type to use for the element
* @return the added attachment
* @throws AttachmentException in case of errors
* @see org.springframework.core.io.Resource
*/
Attachment addAttachment(String contentId, InputStreamSource inputStreamSource, String contentType);
/**
* Add an attachment to the message, taking the content from a {@link DataHandler}.
*
* @param dataHandler the data handler to take the content from
* @return the added attachment
* @throws AttachmentException in case of errors
*/
Attachment addAttachment(String contentId, DataHandler dataHandler);
/**
* Add an attachment to the message, taking the content from a {@link DataHandler}.
*
* @param dataHandler the data handler to take the content from
* @return the added attachment
* @throws AttachmentException in case of errors
*/
Attachment addAttachment(String contentId, DataHandler dataHandler);
}

View File

@@ -27,11 +27,11 @@ import org.springframework.ws.WebServiceMessageException;
@SuppressWarnings("serial")
public abstract class PoxMessageException extends WebServiceMessageException {
public PoxMessageException(String msg) {
super(msg);
}
public PoxMessageException(String msg) {
super(msg);
}
public PoxMessageException(String msg, Throwable ex) {
super(msg, ex);
}
public PoxMessageException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -45,74 +45,74 @@ import org.springframework.xml.namespace.QNameUtils;
*/
public class DomPoxMessage implements PoxMessage {
private final String contentType;
private final String contentType;
private final Document document;
private final Document document;
private final Transformer transformer;
private final Transformer transformer;
/**
* Constructs a new instance of the {@code DomPoxMessage} with the given document.
*
* @param document the document to base the message on
*/
public DomPoxMessage(Document document, Transformer transformer, String contentType) {
Assert.notNull(document, "'document' must not be null");
Assert.notNull(transformer, "'transformer' must not be null");
Assert.hasLength(contentType, "'contentType' must not be empty");
this.document = document;
this.transformer = transformer;
this.contentType = contentType;
}
/**
* Constructs a new instance of the {@code DomPoxMessage} with the given document.
*
* @param document the document to base the message on
*/
public DomPoxMessage(Document document, Transformer transformer, String contentType) {
Assert.notNull(document, "'document' must not be null");
Assert.notNull(transformer, "'transformer' must not be null");
Assert.hasLength(contentType, "'contentType' must not be empty");
this.document = document;
this.transformer = transformer;
this.contentType = contentType;
}
/** Returns the document underlying this message. */
public Document getDocument() {
return document;
}
/** Returns the document underlying this message. */
public Document getDocument() {
return document;
}
@Override
public Result getPayloadResult() {
NodeList children = document.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
document.removeChild(children.item(i));
}
return new DOMResult(document);
}
@Override
public Result getPayloadResult() {
NodeList children = document.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
document.removeChild(children.item(i));
}
return new DOMResult(document);
}
@Override
public Source getPayloadSource() {
return new DOMSource(document);
}
@Override
public Source getPayloadSource() {
return new DOMSource(document);
}
public boolean hasFault() {
return false;
}
public boolean hasFault() {
return false;
}
public String getFaultReason() {
return null;
}
public String getFaultReason() {
return null;
}
public String toString() {
StringBuilder builder = new StringBuilder("DomPoxMessage ");
Element root = document.getDocumentElement();
if (root != null) {
builder.append(' ');
builder.append(QNameUtils.getQNameForNode(root));
}
return builder.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder("DomPoxMessage ");
Element root = document.getDocumentElement();
if (root != null) {
builder.append(' ');
builder.append(QNameUtils.getQNameForNode(root));
}
return builder.toString();
}
@Override
public void writeTo(OutputStream outputStream) throws IOException {
try {
if (outputStream instanceof TransportOutputStream) {
TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream;
transportOutputStream.addHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType);
}
transformer.transform(getPayloadSource(), new StreamResult(outputStream));
}
catch (TransformerException ex) {
throw new DomPoxMessageException("Could write document: " + ex.getMessage(), ex);
}
}
@Override
public void writeTo(OutputStream outputStream) throws IOException {
try {
if (outputStream instanceof TransportOutputStream) {
TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream;
transportOutputStream.addHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType);
}
transformer.transform(getPayloadSource(), new StreamResult(outputStream));
}
catch (TransformerException ex) {
throw new DomPoxMessageException("Could write document: " + ex.getMessage(), ex);
}
}
}

View File

@@ -27,11 +27,11 @@ import org.springframework.ws.pox.PoxMessageException;
@SuppressWarnings("serial")
public class DomPoxMessageException extends PoxMessageException {
public DomPoxMessageException(String msg) {
super(msg);
}
public DomPoxMessageException(String msg) {
super(msg);
}
public DomPoxMessageException(String msg, Throwable ex) {
super(msg, ex);
}
public DomPoxMessageException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -39,34 +39,34 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public class DomPoxMessageFactory extends TransformerObjectSupport implements WebServiceMessageFactory {
/** The default content type for the POX messages. */
public static final String DEFAULT_CONTENT_TYPE = "application/xml";
/** The default content type for the POX messages. */
public static final String DEFAULT_CONTENT_TYPE = "application/xml";
private DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private String contentType = DEFAULT_CONTENT_TYPE;
private String contentType = DEFAULT_CONTENT_TYPE;
public DomPoxMessageFactory() {
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setExpandEntityReferences(false);
}
public DomPoxMessageFactory() {
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setExpandEntityReferences(false);
}
/** Sets the content-type for the {@link DomPoxMessage}. */
public void setContentType(String contentType) {
Assert.hasLength(contentType, "'contentType' must not be empty");
this.contentType = contentType;
}
/** Sets the content-type for the {@link DomPoxMessage}. */
public void setContentType(String contentType) {
Assert.hasLength(contentType, "'contentType' must not be empty");
this.contentType = contentType;
}
/** Set whether or not the XML parser should be XML namespace aware. Default is {@code true}. */
public void setNamespaceAware(boolean namespaceAware) {
documentBuilderFactory.setNamespaceAware(namespaceAware);
}
/** Set whether or not the XML parser should be XML namespace aware. Default is {@code true}. */
public void setNamespaceAware(boolean namespaceAware) {
documentBuilderFactory.setNamespaceAware(namespaceAware);
}
/** Set if the XML parser should validate the document. Default is {@code false}. */
public void setValidating(boolean validating) {
documentBuilderFactory.setValidating(validating);
}
/** Set if the XML parser should validate the document. Default is {@code false}. */
public void setValidating(boolean validating) {
documentBuilderFactory.setValidating(validating);
}
/**
* Set if the XML parser should expand entity reference nodes. Default is
@@ -76,36 +76,36 @@ public class DomPoxMessageFactory extends TransformerObjectSupport implements We
documentBuilderFactory.setExpandEntityReferences(expandEntityRef);
}
@Override
public DomPoxMessage createWebServiceMessage() {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document request = documentBuilder.newDocument();
return new DomPoxMessage(request, createTransformer(), contentType);
}
catch (ParserConfigurationException ex) {
throw new DomPoxMessageException("Could not create message context", ex);
}
catch (TransformerConfigurationException ex) {
throw new DomPoxMessageException("Could not create transformer", ex);
}
}
@Override
public DomPoxMessage createWebServiceMessage() {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document request = documentBuilder.newDocument();
return new DomPoxMessage(request, createTransformer(), contentType);
}
catch (ParserConfigurationException ex) {
throw new DomPoxMessageException("Could not create message context", ex);
}
catch (TransformerConfigurationException ex) {
throw new DomPoxMessageException("Could not create transformer", ex);
}
}
@Override
public DomPoxMessage createWebServiceMessage(InputStream inputStream) throws IOException {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document request = documentBuilder.parse(inputStream);
return new DomPoxMessage(request, createTransformer(), contentType);
}
catch (ParserConfigurationException ex) {
throw new DomPoxMessageException("Could not create message context", ex);
}
catch (SAXException ex) {
throw new DomPoxMessageException("Could not parse request message", ex);
}
catch (TransformerConfigurationException ex) {
throw new DomPoxMessageException("Could not create transformer", ex);
}
}
@Override
public DomPoxMessage createWebServiceMessage(InputStream inputStream) throws IOException {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document request = documentBuilder.parse(inputStream);
return new DomPoxMessage(request, createTransformer(), contentType);
}
catch (ParserConfigurationException ex) {
throw new DomPoxMessageException("Could not create message context", ex);
}
catch (SAXException ex) {
throw new DomPoxMessageException("Could not parse request message", ex);
}
catch (TransformerConfigurationException ex) {
throw new DomPoxMessageException("Could not create transformer", ex);
}
}
}

View File

@@ -32,23 +32,23 @@ import org.springframework.ws.context.MessageContext;
*/
public interface EndpointAdapter {
/**
* Does this {@code EndpointAdapter} support the given {@code endpoint}?
*
* <p>Typical {@code EndpointAdapters} will base the decision on the endpoint type.
*
* @param endpoint endpoint object to check
* @return {@code true} if this {@code EndpointAdapter} supports the supplied {@code endpoint}
*/
boolean supports(Object endpoint);
/**
* Does this {@code EndpointAdapter} support the given {@code endpoint}?
*
* <p>Typical {@code EndpointAdapters} will base the decision on the endpoint type.
*
* @param endpoint endpoint object to check
* @return {@code true} if this {@code EndpointAdapter} supports the supplied {@code endpoint}
*/
boolean supports(Object endpoint);
/**
* Use the given {@code endpoint} to handle the request.
*
* @param messageContext the current message context
* @param endpoint the endpoint to use. This object must have previously been passed to the {@link
* #supports(Object)} method of this interface, which must have returned {@code true}
* @throws Exception in case of errors
*/
void invoke(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Use the given {@code endpoint} to handle the request.
*
* @param messageContext the current message context
* @param endpoint the endpoint to use. This object must have previously been passed to the {@link
* #supports(Object)} method of this interface, which must have returned {@code true}
* @throws Exception in case of errors
*/
void invoke(MessageContext messageContext, Object endpoint) throws Exception;
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -26,13 +26,13 @@ import org.springframework.ws.context.MessageContext;
*/
public interface EndpointExceptionResolver {
/**
* Try to resolve the given exception that got thrown during on endpoint execution.
*
* @param messageContext current message context
* @param endpoint the executed endpoint, or null if none chosen at the time of the exception
* @param ex the exception that got thrown during endpoint execution
* @return {@code true} if resolved; {@code false} otherwise
*/
boolean resolveException(MessageContext messageContext, Object endpoint, Exception ex);
/**
* Try to resolve the given exception that got thrown during on endpoint execution.
*
* @param messageContext current message context
* @param endpoint the executed endpoint, or null if none chosen at the time of the exception
* @param ex the exception that got thrown during endpoint execution
* @return {@code true} if resolved; {@code false} otherwise
*/
boolean resolveException(MessageContext messageContext, Object endpoint, Exception ex);
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -42,75 +42,75 @@ import org.springframework.ws.context.MessageContext;
*/
public interface EndpointInterceptor {
/**
* Processes the incoming request message. Called after {@link EndpointMapping} determined an appropriate endpoint
* object, but before {@link EndpointAdapter} invokes the endpoint.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can decide to abort the chain, typically
* creating a custom response.
*
* @param messageContext contains the incoming request message
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the request interceptor chain; {@code false} to indicate
* blocking of the request endpoint chain, <em>without invoking the endpoint</em>
* @throws Exception in case of errors
* @see MessageContext#getRequest()
*/
boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Processes the incoming request message. Called after {@link EndpointMapping} determined an appropriate endpoint
* object, but before {@link EndpointAdapter} invokes the endpoint.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can decide to abort the chain, typically
* creating a custom response.
*
* @param messageContext contains the incoming request message
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the request interceptor chain; {@code false} to indicate
* blocking of the request endpoint chain, <em>without invoking the endpoint</em>
* @throws Exception in case of errors
* @see MessageContext#getRequest()
*/
boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Processes the outgoing response message. Called after {@link EndpointAdapter} actually invoked the endpoint. Can
* manipulate the response, if any, by adding new headers, etc.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can post-process an invocation, getting
* applied in inverse order of the execution chain.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the response interceptor chain; {@code false} to indicate
* blocking of the response endpoint chain.
* @throws Exception in case of errors
* @see MessageContext#getRequest()
* @see MessageContext#hasResponse()
* @see MessageContext#getResponse()
*/
boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Processes the outgoing response message. Called after {@link EndpointAdapter} actually invoked the endpoint. Can
* manipulate the response, if any, by adding new headers, etc.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can post-process an invocation, getting
* applied in inverse order of the execution chain.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the response interceptor chain; {@code false} to indicate
* blocking of the response endpoint chain.
* @throws Exception in case of errors
* @see MessageContext#getRequest()
* @see MessageContext#hasResponse()
* @see MessageContext#getResponse()
*/
boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Processes the outgoing response fault. Called after {@link EndpointAdapter} actually invoked the endpoint. Can
* manipulate the response, if any, by adding new headers, etc.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can post-process an invocation, getting
* applied in inverse order of the execution chain.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the response interceptor chain; {@code false} to indicate
* blocking of the response handler chain.
*/
boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Processes the outgoing response fault. Called after {@link EndpointAdapter} actually invoked the endpoint. Can
* manipulate the response, if any, by adding new headers, etc.
*
* <p>{@link MessageDispatcher} processes an endpoint in an invocation chain, consisting of any number of interceptors,
* with the endpoint itself at the end. With this method, each interceptor can post-process an invocation, getting
* applied in inverse order of the execution chain.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param endpoint chosen endpoint to invoke
* @return {@code true} to continue processing of the response interceptor chain; {@code false} to indicate
* blocking of the response handler chain.
*/
boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception;
/**
* Callback after completion of request and response (fault) processing. Will be called on any outcome of endpoint
* invocation, thus allows for proper resource cleanup.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* <p>As with the {@link #handleResponse} method, the method will be invoked on each interceptor in the chain in
* reverse order, so the first interceptor will be the last to be invoked.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param endpoint chosen endpoint to invoke
* @param ex exception thrown on handler execution, if any
* @throws Exception in case of errors
* @since 2.0.2
*/
void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception;
/**
* Callback after completion of request and response (fault) processing. Will be called on any outcome of endpoint
* invocation, thus allows for proper resource cleanup.
*
* <p>Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed.
*
* <p>As with the {@link #handleResponse} method, the method will be invoked on each interceptor in the chain in
* reverse order, so the first interceptor will be the last to be invoked.
*
* @param messageContext contains both request and response messages, the response should contains a Fault
* @param endpoint chosen endpoint to invoke
* @param ex exception thrown on handler execution, if any
* @throws Exception in case of errors
* @since 2.0.2
*/
void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception;
}

View File

@@ -25,46 +25,46 @@ package org.springframework.ws.server;
*/
public class EndpointInvocationChain {
private Object endpoint;
private Object endpoint;
private EndpointInterceptor[] interceptors;
private EndpointInterceptor[] interceptors;
/**
* Create new {@code EndpointInvocationChain}.
*
* @param endpoint the endpoint object to invoke
*/
public EndpointInvocationChain(Object endpoint) {
this.endpoint = endpoint;
}
/**
* Create new {@code EndpointInvocationChain}.
*
* @param endpoint the endpoint object to invoke
*/
public EndpointInvocationChain(Object endpoint) {
this.endpoint = endpoint;
}
/**
* Create new {@code EndpointInvocationChain}.
*
* @param endpoint the endpoint object to invoke
* @param interceptors the array of interceptors to apply
*/
public EndpointInvocationChain(Object endpoint, EndpointInterceptor[] interceptors) {
this.endpoint = endpoint;
this.interceptors = interceptors;
}
/**
* Create new {@code EndpointInvocationChain}.
*
* @param endpoint the endpoint object to invoke
* @param interceptors the array of interceptors to apply
*/
public EndpointInvocationChain(Object endpoint, EndpointInterceptor[] interceptors) {
this.endpoint = endpoint;
this.interceptors = interceptors;
}
/**
* Returns the endpoint object to invoke.
*
* @return the endpoint object
*/
public Object getEndpoint() {
return endpoint;
}
/**
* Returns the endpoint object to invoke.
*
* @return the endpoint object
*/
public Object getEndpoint() {
return endpoint;
}
/**
* Returns the array of interceptors to apply before the handler executes.
*
* @return the array of interceptors
*/
public EndpointInterceptor[] getInterceptors() {
return interceptors;
}
/**
* Returns the array of interceptors to apply before the handler executes.
*
* @return the array of interceptors
*/
public EndpointInterceptor[] getInterceptors() {
return interceptors;
}
}

View File

@@ -38,22 +38,22 @@ import org.springframework.ws.context.MessageContext;
*/
public interface EndpointMapping {
/**
* Returns an endpoint and any interceptors for this message context. The choice may be made on message contents,
* transport request url, a routing table, or any factor the implementing class chooses.
*
* <p>The returned {@code EndpointExecutionChain} contains an endpoint Object, rather than even a tag interface,
* so that endpoints are not constrained in any way. For example, a {@code EndpointAdapter} could be written to
* allow another framework's endpoint objects to be used.
*
* <p>Returns {@code null} if no match was found. This is by design. The {@code MessageDispatcher} will query
* all registered {@code EndpointMapping} beans to find a match, and only decide there is an error if none can
* find an endpoint.
*
* @return a HandlerExecutionChain instance containing endpoint object and any interceptors, or {@code null} if
* no mapping is found
* @throws Exception if there is an internal error
*/
EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception;
/**
* Returns an endpoint and any interceptors for this message context. The choice may be made on message contents,
* transport request url, a routing table, or any factor the implementing class chooses.
*
* <p>The returned {@code EndpointExecutionChain} contains an endpoint Object, rather than even a tag interface,
* so that endpoints are not constrained in any way. For example, a {@code EndpointAdapter} could be written to
* allow another framework's endpoint objects to be used.
*
* <p>Returns {@code null} if no match was found. This is by design. The {@code MessageDispatcher} will query
* all registered {@code EndpointMapping} beans to find a match, and only decide there is an error if none can
* find an endpoint.
*
* @return a HandlerExecutionChain instance containing endpoint object and any interceptors, or {@code null} if
* no mapping is found
* @throws Exception if there is an internal error
*/
EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception;
}

View File

@@ -78,408 +78,408 @@ import org.springframework.ws.transport.WebServiceMessageReceiver;
*/
public class MessageDispatcher implements WebServiceMessageReceiver, BeanNameAware, ApplicationContextAware {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Log category to use when no mapped endpoint is found for a request. */
public static final String ENDPOINT_NOT_FOUND_LOG_CATEGORY = "org.springframework.ws.server.EndpointNotFound";
/** Log category to use when no mapped endpoint is found for a request. */
public static final String ENDPOINT_NOT_FOUND_LOG_CATEGORY = "org.springframework.ws.server.EndpointNotFound";
/** Additional logger to use when no mapped endpoint is found for a request. */
protected static final Log endpointNotFoundLogger =
LogFactory.getLog(MessageDispatcher.ENDPOINT_NOT_FOUND_LOG_CATEGORY);
/** Additional logger to use when no mapped endpoint is found for a request. */
protected static final Log endpointNotFoundLogger =
LogFactory.getLog(MessageDispatcher.ENDPOINT_NOT_FOUND_LOG_CATEGORY);
/** Log category to use for message tracing. */
public static final String MESSAGE_TRACING_LOG_CATEGORY = "org.springframework.ws.server.MessageTracing";
/** Log category to use for message tracing. */
public static final String MESSAGE_TRACING_LOG_CATEGORY = "org.springframework.ws.server.MessageTracing";
/** Additional logger to use for sent message tracing. */
protected static final Log sentMessageTracingLogger =
LogFactory.getLog(MessageDispatcher.MESSAGE_TRACING_LOG_CATEGORY + ".sent");
/** Additional logger to use for sent message tracing. */
protected static final Log sentMessageTracingLogger =
LogFactory.getLog(MessageDispatcher.MESSAGE_TRACING_LOG_CATEGORY + ".sent");
/** Additional logger to use for received message tracing. */
protected static final Log receivedMessageTracingLogger =
LogFactory.getLog(MessageDispatcher.MESSAGE_TRACING_LOG_CATEGORY + ".received");
/** Additional logger to use for received message tracing. */
protected static final Log receivedMessageTracingLogger =
LogFactory.getLog(MessageDispatcher.MESSAGE_TRACING_LOG_CATEGORY + ".received");
private final DefaultStrategiesHelper defaultStrategiesHelper;
private final DefaultStrategiesHelper defaultStrategiesHelper;
/** The registered bean name for this dispatcher. */
private String beanName;
/** The registered bean name for this dispatcher. */
private String beanName;
/** List of EndpointAdapters used in this dispatcher. */
private List<EndpointAdapter> endpointAdapters;
/** List of EndpointAdapters used in this dispatcher. */
private List<EndpointAdapter> endpointAdapters;
/** List of EndpointExceptionResolvers used in this dispatcher. */
private List<EndpointExceptionResolver> endpointExceptionResolvers;
/** List of EndpointExceptionResolvers used in this dispatcher. */
private List<EndpointExceptionResolver> endpointExceptionResolvers;
/** List of EndpointMappings used in this dispatcher. */
private List<EndpointMapping> endpointMappings;
/** List of EndpointMappings used in this dispatcher. */
private List<EndpointMapping> endpointMappings;
/** Initializes a new instance of the {@code MessageDispatcher}. */
public MessageDispatcher() {
defaultStrategiesHelper = new DefaultStrategiesHelper(getClass());
}
/** Initializes a new instance of the {@code MessageDispatcher}. */
public MessageDispatcher() {
defaultStrategiesHelper = new DefaultStrategiesHelper(getClass());
}
/** Returns the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */
public List<EndpointAdapter> getEndpointAdapters() {
return endpointAdapters;
}
/** Returns the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */
public List<EndpointAdapter> getEndpointAdapters() {
return endpointAdapters;
}
/** Sets the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */
public void setEndpointAdapters(List<EndpointAdapter> endpointAdapters) {
this.endpointAdapters = endpointAdapters;
}
/** Sets the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */
public void setEndpointAdapters(List<EndpointAdapter> endpointAdapters) {
this.endpointAdapters = endpointAdapters;
}
/** Returns the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */
public List<EndpointExceptionResolver> getEndpointExceptionResolvers() {
return endpointExceptionResolvers;
}
/** Returns the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */
public List<EndpointExceptionResolver> getEndpointExceptionResolvers() {
return endpointExceptionResolvers;
}
/** Sets the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */
public void setEndpointExceptionResolvers(List<EndpointExceptionResolver> endpointExceptionResolvers) {
this.endpointExceptionResolvers = endpointExceptionResolvers;
}
/** Sets the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */
public void setEndpointExceptionResolvers(List<EndpointExceptionResolver> endpointExceptionResolvers) {
this.endpointExceptionResolvers = endpointExceptionResolvers;
}
/** Returns the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */
public List<EndpointMapping> getEndpointMappings() {
return endpointMappings;
}
/** Returns the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */
public List<EndpointMapping> getEndpointMappings() {
return endpointMappings;
}
/** Sets the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */
public void setEndpointMappings(List<EndpointMapping> endpointMappings) {
this.endpointMappings = endpointMappings;
}
/** Sets the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */
public void setEndpointMappings(List<EndpointMapping> endpointMappings) {
this.endpointMappings = endpointMappings;
}
@Override
public final void setBeanName(String beanName) {
this.beanName = beanName;
}
@Override
public final void setBeanName(String beanName) {
this.beanName = beanName;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
initEndpointAdapters(applicationContext);
initEndpointExceptionResolvers(applicationContext);
initEndpointMappings(applicationContext);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
initEndpointAdapters(applicationContext);
initEndpointExceptionResolvers(applicationContext);
initEndpointMappings(applicationContext);
}
@Override
public void receive(MessageContext messageContext) throws Exception {
// Let's keep a reference to the request content as it came in, it might be changed by interceptors in dispatch()
String requestContent = "";
if (receivedMessageTracingLogger.isTraceEnabled() || sentMessageTracingLogger.isTraceEnabled()) {
requestContent = getMessageContent(messageContext.getRequest());
}
if (receivedMessageTracingLogger.isTraceEnabled()) {
receivedMessageTracingLogger.trace("Received request [" + requestContent + "]");
}
else if (receivedMessageTracingLogger.isDebugEnabled()) {
receivedMessageTracingLogger.debug("Received request [" + messageContext.getRequest() + "]");
}
dispatch(messageContext);
if (messageContext.hasResponse()) {
WebServiceMessage response = messageContext.getResponse();
if (sentMessageTracingLogger.isTraceEnabled()) {
String responseContent = getMessageContent(response);
sentMessageTracingLogger.trace("Sent response [" + responseContent + "] for request [" +
requestContent + "]");
}
else if (sentMessageTracingLogger.isDebugEnabled()) {
sentMessageTracingLogger.debug("Sent response [" + response + "] for request [" +
messageContext.getRequest() + "]");
}
}
else if (sentMessageTracingLogger.isDebugEnabled()) {
sentMessageTracingLogger
.debug("MessageDispatcher with name '" + beanName + "' sends no response for request [" +
messageContext.getRequest() + "]");
}
}
@Override
public void receive(MessageContext messageContext) throws Exception {
// Let's keep a reference to the request content as it came in, it might be changed by interceptors in dispatch()
String requestContent = "";
if (receivedMessageTracingLogger.isTraceEnabled() || sentMessageTracingLogger.isTraceEnabled()) {
requestContent = getMessageContent(messageContext.getRequest());
}
if (receivedMessageTracingLogger.isTraceEnabled()) {
receivedMessageTracingLogger.trace("Received request [" + requestContent + "]");
}
else if (receivedMessageTracingLogger.isDebugEnabled()) {
receivedMessageTracingLogger.debug("Received request [" + messageContext.getRequest() + "]");
}
dispatch(messageContext);
if (messageContext.hasResponse()) {
WebServiceMessage response = messageContext.getResponse();
if (sentMessageTracingLogger.isTraceEnabled()) {
String responseContent = getMessageContent(response);
sentMessageTracingLogger.trace("Sent response [" + responseContent + "] for request [" +
requestContent + "]");
}
else if (sentMessageTracingLogger.isDebugEnabled()) {
sentMessageTracingLogger.debug("Sent response [" + response + "] for request [" +
messageContext.getRequest() + "]");
}
}
else if (sentMessageTracingLogger.isDebugEnabled()) {
sentMessageTracingLogger
.debug("MessageDispatcher with name '" + beanName + "' sends no response for request [" +
messageContext.getRequest() + "]");
}
}
private String getMessageContent(WebServiceMessage message) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
message.writeTo(bos);
return bos.toString("UTF-8");
}
private String getMessageContent(WebServiceMessage message) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
message.writeTo(bos);
return bos.toString("UTF-8");
}
/**
* Dispatches the request in the given MessageContext according to the configuration.
*
* @param messageContext the message context
* @throws org.springframework.ws.NoEndpointFoundException
* thrown when an endpoint cannot be resolved for the incoming message
*/
protected final void dispatch(MessageContext messageContext) throws Exception {
EndpointInvocationChain mappedEndpoint = null;
int interceptorIndex = -1;
try {
try {
// Determine endpoint for the current context
mappedEndpoint = getEndpoint(messageContext);
if (mappedEndpoint == null || mappedEndpoint.getEndpoint() == null) {
throw new NoEndpointFoundException(messageContext.getRequest());
}
if (!handleRequest(mappedEndpoint, messageContext)) {
return;
}
// Apply handleRequest of registered interceptors
if (mappedEndpoint.getInterceptors() != null) {
for (int i = 0; i < mappedEndpoint.getInterceptors().length; i++) {
EndpointInterceptor interceptor = mappedEndpoint.getInterceptors()[i];
interceptorIndex = i;
if (!interceptor.handleRequest(messageContext, mappedEndpoint.getEndpoint())) {
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, null);
return;
}
}
}
// Actually invoke the endpoint
EndpointAdapter endpointAdapter = getEndpointAdapter(mappedEndpoint.getEndpoint());
endpointAdapter.invoke(messageContext, mappedEndpoint.getEndpoint());
/**
* Dispatches the request in the given MessageContext according to the configuration.
*
* @param messageContext the message context
* @throws org.springframework.ws.NoEndpointFoundException
* thrown when an endpoint cannot be resolved for the incoming message
*/
protected final void dispatch(MessageContext messageContext) throws Exception {
EndpointInvocationChain mappedEndpoint = null;
int interceptorIndex = -1;
try {
try {
// Determine endpoint for the current context
mappedEndpoint = getEndpoint(messageContext);
if (mappedEndpoint == null || mappedEndpoint.getEndpoint() == null) {
throw new NoEndpointFoundException(messageContext.getRequest());
}
if (!handleRequest(mappedEndpoint, messageContext)) {
return;
}
// Apply handleRequest of registered interceptors
if (mappedEndpoint.getInterceptors() != null) {
for (int i = 0; i < mappedEndpoint.getInterceptors().length; i++) {
EndpointInterceptor interceptor = mappedEndpoint.getInterceptors()[i];
interceptorIndex = i;
if (!interceptor.handleRequest(messageContext, mappedEndpoint.getEndpoint())) {
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, null);
return;
}
}
}
// Actually invoke the endpoint
EndpointAdapter endpointAdapter = getEndpointAdapter(mappedEndpoint.getEndpoint());
endpointAdapter.invoke(messageContext, mappedEndpoint.getEndpoint());
// Apply handleResponse methods of registered interceptors
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
}
catch (NoEndpointFoundException ex) {
// No triggering of interceptors if no endpoint is found
if (endpointNotFoundLogger.isWarnEnabled()) {
endpointNotFoundLogger.warn("No endpoint mapping found for [" + messageContext.getRequest() + "]");
}
throw ex;
}
catch (Exception ex) {
Object endpoint = mappedEndpoint != null ? mappedEndpoint.getEndpoint() : null;
processEndpointException(messageContext, endpoint, ex);
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
}
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, null);
}
catch (NoEndpointFoundException ex) {
throw ex;
}
catch (Exception ex) {
// Apply handleResponse methods of registered interceptors
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
}
catch (NoEndpointFoundException ex) {
// No triggering of interceptors if no endpoint is found
if (endpointNotFoundLogger.isWarnEnabled()) {
endpointNotFoundLogger.warn("No endpoint mapping found for [" + messageContext.getRequest() + "]");
}
throw ex;
}
catch (Exception ex) {
Object endpoint = mappedEndpoint != null ? mappedEndpoint.getEndpoint() : null;
processEndpointException(messageContext, endpoint, ex);
triggerHandleResponse(mappedEndpoint, interceptorIndex, messageContext);
}
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, null);
}
catch (NoEndpointFoundException ex) {
throw ex;
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, ex);
throw ex;
}
}
triggerAfterCompletion(mappedEndpoint, interceptorIndex, messageContext, ex);
throw ex;
}
}
/**
* Returns the endpoint for this request. All endpoint mappings are tried, in order.
*
* @return the {@code EndpointInvocationChain}, or {@code null} if no endpoint could be found.
*/
protected EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception {
for (EndpointMapping endpointMapping : getEndpointMappings()) {
EndpointInvocationChain endpoint = endpointMapping.getEndpoint(messageContext);
if (endpoint != null) {
if (logger.isDebugEnabled()) {
logger.debug("Endpoint mapping [" + endpointMapping + "] maps request to endpoint [" +
endpoint.getEndpoint() + "]");
}
return endpoint;
}
else if (logger.isDebugEnabled()) {
logger.debug("Endpoint mapping [" + endpointMapping + "] has no mapping for request");
}
}
return null;
}
/**
* Returns the endpoint for this request. All endpoint mappings are tried, in order.
*
* @return the {@code EndpointInvocationChain}, or {@code null} if no endpoint could be found.
*/
protected EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception {
for (EndpointMapping endpointMapping : getEndpointMappings()) {
EndpointInvocationChain endpoint = endpointMapping.getEndpoint(messageContext);
if (endpoint != null) {
if (logger.isDebugEnabled()) {
logger.debug("Endpoint mapping [" + endpointMapping + "] maps request to endpoint [" +
endpoint.getEndpoint() + "]");
}
return endpoint;
}
else if (logger.isDebugEnabled()) {
logger.debug("Endpoint mapping [" + endpointMapping + "] has no mapping for request");
}
}
return null;
}
/**
* Returns the {@code EndpointAdapter} for the given endpoint.
*
* @param endpoint the endpoint to find an adapter for
* @return the adapter
*/
protected EndpointAdapter getEndpointAdapter(Object endpoint) {
for (EndpointAdapter endpointAdapter : getEndpointAdapters()) {
if (logger.isDebugEnabled()) {
logger.debug("Testing endpoint adapter [" + endpointAdapter + "]");
}
if (endpointAdapter.supports(endpoint)) {
return endpointAdapter;
}
}
throw new IllegalStateException("No adapter for endpoint [" + endpoint + "]: Is your endpoint annotated with " +
"@Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?");
}
/**
* Returns the {@code EndpointAdapter} for the given endpoint.
*
* @param endpoint the endpoint to find an adapter for
* @return the adapter
*/
protected EndpointAdapter getEndpointAdapter(Object endpoint) {
for (EndpointAdapter endpointAdapter : getEndpointAdapters()) {
if (logger.isDebugEnabled()) {
logger.debug("Testing endpoint adapter [" + endpointAdapter + "]");
}
if (endpointAdapter.supports(endpoint)) {
return endpointAdapter;
}
}
throw new IllegalStateException("No adapter for endpoint [" + endpoint + "]: Is your endpoint annotated with " +
"@Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?");
}
/**
* Callback for pre-processing of given invocation chain and message context. Gets called before invocation of
* {@code handleRequest} on the interceptors.
*
* <p>Default implementation does nothing, and returns {@code true}.
*
* @param mappedEndpoint the mapped {@code EndpointInvocationChain}
* @param messageContext the message context
* @return {@code true} if processing should continue; {@code false} otherwise
*/
protected boolean handleRequest(EndpointInvocationChain mappedEndpoint, MessageContext messageContext) {
return true;
}
/**
* Callback for pre-processing of given invocation chain and message context. Gets called before invocation of
* {@code handleRequest} on the interceptors.
*
* <p>Default implementation does nothing, and returns {@code true}.
*
* @param mappedEndpoint the mapped {@code EndpointInvocationChain}
* @param messageContext the message context
* @return {@code true} if processing should continue; {@code false} otherwise
*/
protected boolean handleRequest(EndpointInvocationChain mappedEndpoint, MessageContext messageContext) {
return true;
}
/**
* Determine an error {@code SOAPMessage} response via the registered {@code EndpointExceptionResolvers}.
* Most likely, the response contains a {@code SOAPFault}. If no suitable resolver was found, the exception is
* rethrown.
*
* @param messageContext current SOAPMessage request
* @param endpoint the executed endpoint, or null if none chosen at the time of the exception
* @param ex the exception that got thrown during handler execution
* @throws Exception if no suitable resolver is found
*/
protected void processEndpointException(MessageContext messageContext, Object endpoint, Exception ex)
throws Exception {
if (!CollectionUtils.isEmpty(getEndpointExceptionResolvers())) {
for (EndpointExceptionResolver resolver : getEndpointExceptionResolvers()) {
if (resolver.resolveException(messageContext, endpoint, ex)) {
if (logger.isDebugEnabled()) {
logger.debug("Endpoint invocation resulted in exception - responding with Fault", ex);
}
return;
}
}
}
// exception not resolved
throw ex;
}
/**
* Determine an error {@code SOAPMessage} response via the registered {@code EndpointExceptionResolvers}.
* Most likely, the response contains a {@code SOAPFault}. If no suitable resolver was found, the exception is
* rethrown.
*
* @param messageContext current SOAPMessage request
* @param endpoint the executed endpoint, or null if none chosen at the time of the exception
* @param ex the exception that got thrown during handler execution
* @throws Exception if no suitable resolver is found
*/
protected void processEndpointException(MessageContext messageContext, Object endpoint, Exception ex)
throws Exception {
if (!CollectionUtils.isEmpty(getEndpointExceptionResolvers())) {
for (EndpointExceptionResolver resolver : getEndpointExceptionResolvers()) {
if (resolver.resolveException(messageContext, endpoint, ex)) {
if (logger.isDebugEnabled()) {
logger.debug("Endpoint invocation resulted in exception - responding with Fault", ex);
}
return;
}
}
}
// exception not resolved
throw ex;
}
/**
* Trigger handleResponse or handleFault on the mapped EndpointInterceptors. Will just invoke said method on all
* interceptors whose handleRequest invocation returned {@code true}, in addition to the last interceptor who
* returned {@code false}.
*
* @param mappedEndpoint the mapped EndpointInvocationChain
* @param interceptorIndex index of last interceptor that was called
* @param messageContext the message context, whose request and response are filled
* @see EndpointInterceptor#handleResponse(MessageContext,Object)
* @see EndpointInterceptor#handleFault(MessageContext, Object)
*/
private void triggerHandleResponse(EndpointInvocationChain mappedEndpoint,
int interceptorIndex,
MessageContext messageContext) throws Exception {
if (mappedEndpoint != null && messageContext.hasResponse() &&
!ObjectUtils.isEmpty(mappedEndpoint.getInterceptors())) {
boolean hasFault = false;
WebServiceMessage response = messageContext.getResponse();
if (response instanceof FaultAwareWebServiceMessage) {
hasFault = ((FaultAwareWebServiceMessage) response).hasFault();
}
boolean resume = true;
for (int i = interceptorIndex; resume && i >= 0; i--) {
EndpointInterceptor interceptor = mappedEndpoint.getInterceptors()[i];
if (!hasFault) {
resume = interceptor.handleResponse(messageContext, mappedEndpoint.getEndpoint());
}
else {
resume = interceptor.handleFault(messageContext, mappedEndpoint.getEndpoint());
}
}
}
}
/**
* Trigger handleResponse or handleFault on the mapped EndpointInterceptors. Will just invoke said method on all
* interceptors whose handleRequest invocation returned {@code true}, in addition to the last interceptor who
* returned {@code false}.
*
* @param mappedEndpoint the mapped EndpointInvocationChain
* @param interceptorIndex index of last interceptor that was called
* @param messageContext the message context, whose request and response are filled
* @see EndpointInterceptor#handleResponse(MessageContext,Object)
* @see EndpointInterceptor#handleFault(MessageContext, Object)
*/
private void triggerHandleResponse(EndpointInvocationChain mappedEndpoint,
int interceptorIndex,
MessageContext messageContext) throws Exception {
if (mappedEndpoint != null && messageContext.hasResponse() &&
!ObjectUtils.isEmpty(mappedEndpoint.getInterceptors())) {
boolean hasFault = false;
WebServiceMessage response = messageContext.getResponse();
if (response instanceof FaultAwareWebServiceMessage) {
hasFault = ((FaultAwareWebServiceMessage) response).hasFault();
}
boolean resume = true;
for (int i = interceptorIndex; resume && i >= 0; i--) {
EndpointInterceptor interceptor = mappedEndpoint.getInterceptors()[i];
if (!hasFault) {
resume = interceptor.handleResponse(messageContext, mappedEndpoint.getEndpoint());
}
else {
resume = interceptor.handleFault(messageContext, mappedEndpoint.getEndpoint());
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped EndpointInterceptors.
* Will just invoke afterCompletion for all interceptors whose handleRequest invocation
* has successfully completed and returned true, in addition to the last interceptor who
* returned {@code false}.
*
* @param mappedEndpoint the mapped EndpointInvocationChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or {@code null} if none
* @see EndpointInterceptor#afterCompletion
*/
private void triggerAfterCompletion(EndpointInvocationChain mappedEndpoint,
int interceptorIndex,
MessageContext messageContext,
Exception ex) throws Exception {
/**
* Trigger afterCompletion callbacks on the mapped EndpointInterceptors.
* Will just invoke afterCompletion for all interceptors whose handleRequest invocation
* has successfully completed and returned true, in addition to the last interceptor who
* returned {@code false}.
*
* @param mappedEndpoint the mapped EndpointInvocationChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or {@code null} if none
* @see EndpointInterceptor#afterCompletion
*/
private void triggerAfterCompletion(EndpointInvocationChain mappedEndpoint,
int interceptorIndex,
MessageContext messageContext,
Exception ex) throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedEndpoint != null) {
EndpointInterceptor[] interceptors = mappedEndpoint.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
EndpointInterceptor interceptor = interceptors[i];
try {
interceptor.afterCompletion(messageContext, mappedEndpoint.getEndpoint(), ex);
}
catch (Throwable ex2) {
logger.error("EndpointInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
// Apply afterCompletion methods of registered interceptors.
if (mappedEndpoint != null) {
EndpointInterceptor[] interceptors = mappedEndpoint.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
EndpointInterceptor interceptor = interceptors[i];
try {
interceptor.afterCompletion(messageContext, mappedEndpoint.getEndpoint(), ex);
}
catch (Throwable ex2) {
logger.error("EndpointInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Initialize the {@code EndpointAdapters} used by this class. If no adapter beans are explicitly set by using
* the {@code endpointAdapters} property, we use the default strategies.
*
* @see #setEndpointAdapters(java.util.List)
*/
private void initEndpointAdapters(ApplicationContext applicationContext) throws BeansException {
if (endpointAdapters == null) {
Map<String, EndpointAdapter> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointAdapters = new ArrayList<EndpointAdapter>(matchingBeans.values());
Collections.sort(endpointAdapters, new OrderComparator());
}
else {
endpointAdapters =
defaultStrategiesHelper.getDefaultStrategies(EndpointAdapter.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointAdapters found, using defaults");
}
}
}
}
/**
* Initialize the {@code EndpointAdapters} used by this class. If no adapter beans are explicitly set by using
* the {@code endpointAdapters} property, we use the default strategies.
*
* @see #setEndpointAdapters(java.util.List)
*/
private void initEndpointAdapters(ApplicationContext applicationContext) throws BeansException {
if (endpointAdapters == null) {
Map<String, EndpointAdapter> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointAdapters = new ArrayList<EndpointAdapter>(matchingBeans.values());
Collections.sort(endpointAdapters, new OrderComparator());
}
else {
endpointAdapters =
defaultStrategiesHelper.getDefaultStrategies(EndpointAdapter.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointAdapters found, using defaults");
}
}
}
}
/**
* Initialize the {@code EndpointExceptionResolver} used by this class. If no resolver beans are explicitly set
* by using the {@code endpointExceptionResolvers} property, we use the default strategies.
*
* @see #setEndpointExceptionResolvers(java.util.List)
*/
private void initEndpointExceptionResolvers(ApplicationContext applicationContext) throws BeansException {
if (endpointExceptionResolvers == null) {
Map<String, EndpointExceptionResolver> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointExceptionResolvers = new ArrayList<EndpointExceptionResolver>(matchingBeans.values());
Collections.sort(endpointExceptionResolvers, new OrderComparator());
}
else {
endpointExceptionResolvers = defaultStrategiesHelper
.getDefaultStrategies(EndpointExceptionResolver.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointExceptionResolvers found, using defaults");
}
}
}
}
/**
* Initialize the {@code EndpointExceptionResolver} used by this class. If no resolver beans are explicitly set
* by using the {@code endpointExceptionResolvers} property, we use the default strategies.
*
* @see #setEndpointExceptionResolvers(java.util.List)
*/
private void initEndpointExceptionResolvers(ApplicationContext applicationContext) throws BeansException {
if (endpointExceptionResolvers == null) {
Map<String, EndpointExceptionResolver> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointExceptionResolvers = new ArrayList<EndpointExceptionResolver>(matchingBeans.values());
Collections.sort(endpointExceptionResolvers, new OrderComparator());
}
else {
endpointExceptionResolvers = defaultStrategiesHelper
.getDefaultStrategies(EndpointExceptionResolver.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointExceptionResolvers found, using defaults");
}
}
}
}
/**
* Initialize the {@code EndpointMappings} used by this class. If no mapping beans are explictely set by using
* the {@code endpointMappings} property, we use the default strategies.
*
* @see #setEndpointMappings(java.util.List)
*/
private void initEndpointMappings(ApplicationContext applicationContext) throws BeansException {
if (endpointMappings == null) {
Map<String, EndpointMapping> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointMappings = new ArrayList<EndpointMapping>(matchingBeans.values());
Collections.sort(endpointMappings, new OrderComparator());
}
else {
endpointMappings =
defaultStrategiesHelper.getDefaultStrategies(EndpointMapping.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointMappings found, using defaults");
}
}
}
}
/**
* Initialize the {@code EndpointMappings} used by this class. If no mapping beans are explictely set by using
* the {@code endpointMappings} property, we use the default strategies.
*
* @see #setEndpointMappings(java.util.List)
*/
private void initEndpointMappings(ApplicationContext applicationContext) throws BeansException {
if (endpointMappings == null) {
Map<String, EndpointMapping> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, EndpointMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
endpointMappings = new ArrayList<EndpointMapping>(matchingBeans.values());
Collections.sort(endpointMappings, new OrderComparator());
}
else {
endpointMappings =
defaultStrategiesHelper.getDefaultStrategies(EndpointMapping.class, applicationContext);
if (logger.isDebugEnabled()) {
logger.debug("No EndpointMappings found, using defaults");
}
}
}
}
}

View File

@@ -26,13 +26,13 @@ import org.springframework.ws.context.MessageContext;
*/
public interface SmartEndpointInterceptor extends EndpointInterceptor {
/**
* Indicates whether this interceptor should intercept the given message context.
*
* @param messageContext contains the incoming request message
* @param endpoint chosen endpoint to invoke
* @return {@code true} to indicate that this interceptor applies; {@code false} otherwise
*/
boolean shouldIntercept(MessageContext messageContext, Object endpoint);
/**
* Indicates whether this interceptor should intercept the given message context.
*
* @param messageContext contains the incoming request message
* @param endpoint chosen endpoint to invoke
* @return {@code true} to indicate that this interceptor applies; {@code false} otherwise
*/
boolean shouldIntercept(MessageContext messageContext, Object endpoint);
}

View File

@@ -45,72 +45,72 @@ import org.springframework.xml.transform.TransformerObjectSupport;
@Deprecated
public abstract class AbstractDom4jPayloadEndpoint extends TransformerObjectSupport implements PayloadEndpoint {
private boolean alwaysTransform = false;
private boolean alwaysTransform = false;
/**
* Set if the request {@link Source} should always be transformed into a new {@link DocumentResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
/**
* Set if the request {@link Source} should always be transformed into a new {@link DocumentResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = null;
if (request != null) {
DocumentResult dom4jResult = new DocumentResult();
transform(request, dom4jResult);
requestElement = dom4jResult.getDocument().getRootElement();
}
Document responseDocument = DocumentHelper.createDocument();
Element responseElement = invokeInternal(requestElement, responseDocument);
return responseElement != null ? new DocumentSource(responseElement) : null;
}
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = null;
if (request != null) {
DocumentResult dom4jResult = new DocumentResult();
transform(request, dom4jResult);
requestElement = dom4jResult.getDocument().getRootElement();
}
Document responseDocument = DocumentHelper.createDocument();
Element responseElement = invokeInternal(requestElement, responseDocument);
return responseElement != null ? new DocumentSource(responseElement) : null;
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link javax.xml.transform.dom.DOMSource}, and uses a
* {@link org.jdom.input.DOMBuilder} to create a JDOM {@link org.jdom.Element}. In all other cases, or when
* {@linkplain #setAlwaysTransform(boolean) alwaysTransform} is {@code true}, the source is transformed into a
* {@link org.jdom.transform.JDOMResult}, which is more expensive. If the passed source is {@code null}, {@code
* null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @return the document element
* @throws javax.xml.transform.TransformerException
* in case of errors
*/
protected Element getDocumentElement(Source source) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
if (node.getNodeType() == Node.DOCUMENT_NODE) {
DOMReader domReader = new DOMReader();
Document document = domReader.read((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
DocumentResult dom4jResult = new DocumentResult();
transform(source, dom4jResult);
return dom4jResult.getDocument().getRootElement();
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link javax.xml.transform.dom.DOMSource}, and uses a
* {@link org.jdom.input.DOMBuilder} to create a JDOM {@link org.jdom.Element}. In all other cases, or when
* {@linkplain #setAlwaysTransform(boolean) alwaysTransform} is {@code true}, the source is transformed into a
* {@link org.jdom.transform.JDOMResult}, which is more expensive. If the passed source is {@code null}, {@code
* null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @return the document element
* @throws javax.xml.transform.TransformerException
* in case of errors
*/
protected Element getDocumentElement(Source source) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
if (node.getNodeType() == Node.DOCUMENT_NODE) {
DOMReader domReader = new DOMReader();
Document document = domReader.read((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
DocumentResult dom4jResult = new DocumentResult();
transform(source, dom4jResult);
return dom4jResult.getDocument().getRootElement();
}
/**
* Template method. Subclasses must implement this. Offers the request payload as a dom4j {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* <p>The given dom4j {@code Document} is to be used for constructing a response element, by using
* {@code addElement}.
*
* @param requestElement the contents of the SOAP message as dom4j elements
* @param responseDocument a dom4j document to be used for constructing a response
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement, Document responseDocument) throws Exception;
/**
* Template method. Subclasses must implement this. Offers the request payload as a dom4j {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* <p>The given dom4j {@code Document} is to be used for constructing a response element, by using
* {@code addElement}.
*
* @param requestElement the contents of the SOAP message as dom4j elements
* @param responseDocument a dom4j document to be used for constructing a response
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement, Document responseDocument) throws Exception;
}

View File

@@ -48,25 +48,25 @@ import org.springframework.xml.transform.TransformerObjectSupport;
@Deprecated
public abstract class AbstractDomPayloadEndpoint extends TransformerObjectSupport implements PayloadEndpoint {
private DocumentBuilderFactory documentBuilderFactory;
private DocumentBuilderFactory documentBuilderFactory;
private boolean validating = false;
private boolean validating = false;
private boolean namespaceAware = true;
private boolean namespaceAware = true;
private boolean expandEntityReferences = false;
private boolean alwaysTransform = false;
private boolean alwaysTransform = false;
/** Set whether or not the XML parser should be XML namespace aware. Default is {@code true}. */
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/** Set whether or not the XML parser should be XML namespace aware. Default is {@code true}. */
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/** Set if the XML parser should validate the document. Default is {@code false}. */
public void setValidating(boolean validating) {
this.validating = validating;
}
/** Set if the XML parser should validate the document. Default is {@code false}. */
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Set if the XML parser should expand entity reference nodes. Default is
@@ -77,102 +77,102 @@ public abstract class AbstractDomPayloadEndpoint extends TransformerObjectSuppor
}
/**
* Set if the request {@link Source} should always be transformed into a new {@link DOMResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
/**
* Set if the request {@link Source} should always be transformed into a new {@link DOMResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
@Override
public final Source invoke(Source request) throws Exception {
if (documentBuilderFactory == null) {
documentBuilderFactory = createDocumentBuilderFactory();
}
DocumentBuilder documentBuilder = createDocumentBuilder(documentBuilderFactory);
Element requestElement = getDocumentElement(request, documentBuilder);
Document responseDocument = documentBuilder.newDocument();
Element responseElement = invokeInternal(requestElement, responseDocument);
return responseElement != null ? new DOMSource(responseElement) : null;
}
@Override
public final Source invoke(Source request) throws Exception {
if (documentBuilderFactory == null) {
documentBuilderFactory = createDocumentBuilderFactory();
}
DocumentBuilder documentBuilder = createDocumentBuilder(documentBuilderFactory);
Element requestElement = getDocumentElement(request, documentBuilder);
Document responseDocument = documentBuilder.newDocument();
Element responseElement = invokeInternal(requestElement, responseDocument);
return responseElement != null ? new DOMSource(responseElement) : null;
}
/**
* Create a {@code DocumentBuilder} that this endpoint will use for parsing XML documents. Can be overridden in
* subclasses, adding further initialization of the builder.
*
* @param factory the {@code DocumentBuilderFactory} that the DocumentBuilder should be created with
* @return the {@code DocumentBuilder}
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
throws ParserConfigurationException {
return factory.newDocumentBuilder();
}
/**
* Create a {@code DocumentBuilder} that this endpoint will use for parsing XML documents. Can be overridden in
* subclasses, adding further initialization of the builder.
*
* @param factory the {@code DocumentBuilderFactory} that the DocumentBuilder should be created with
* @return the {@code DocumentBuilder}
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
throws ParserConfigurationException {
return factory.newDocumentBuilder();
}
/**
* Create a {@code DocumentBuilderFactory} that this endpoint will use for constructing XML documents. Can be
* overridden in subclasses, adding further initialization of the factory. The resulting
* {@code DocumentBuilderFactory} is cached, so this method will only be called once.
*
* @return the DocumentBuilderFactory
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
factory.setNamespaceAware(namespaceAware);
factory.setExpandEntityReferences(expandEntityReferences);
return factory;
}
/**
* Create a {@code DocumentBuilderFactory} that this endpoint will use for constructing XML documents. Can be
* overridden in subclasses, adding further initialization of the factory. The resulting
* {@code DocumentBuilderFactory} is cached, so this method will only be called once.
*
* @return the DocumentBuilderFactory
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
factory.setNamespaceAware(namespaceAware);
factory.setExpandEntityReferences(expandEntityReferences);
return factory;
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link DOMSource}, and returns the {@linkplain
* DOMSource#getNode() node} of that. In all other cases, or when {@linkplain #setAlwaysTransform(boolean)
* alwaysTransform} is {@code true}, the source is transformed into a {@link DOMResult}, which is more expensive. If
* the passed source is {@code null}, {@code null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @param documentBuilder the document builder to be used for transformations
* @return the document element
* @throws TransformerException in case of errors
*/
protected Element getDocumentElement(Source source, DocumentBuilder documentBuilder) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return (Element) node;
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
return ((Document) node).getDocumentElement();
}
}
// we have no other option than to transform
Document requestDocument = documentBuilder.newDocument();
DOMResult domResult = new DOMResult(requestDocument);
transform(source, domResult);
return requestDocument.getDocumentElement();
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link DOMSource}, and returns the {@linkplain
* DOMSource#getNode() node} of that. In all other cases, or when {@linkplain #setAlwaysTransform(boolean)
* alwaysTransform} is {@code true}, the source is transformed into a {@link DOMResult}, which is more expensive. If
* the passed source is {@code null}, {@code null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @param documentBuilder the document builder to be used for transformations
* @return the document element
* @throws TransformerException in case of errors
*/
protected Element getDocumentElement(Source source, DocumentBuilder documentBuilder) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return (Element) node;
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
return ((Document) node).getDocumentElement();
}
}
// we have no other option than to transform
Document requestDocument = documentBuilder.newDocument();
DOMResult domResult = new DOMResult(requestDocument);
transform(source, domResult);
return requestDocument.getDocumentElement();
}
/**
* Template method that subclasses must implement to process the request.
*
* <p>Offers the request payload as a DOM {@code Element}, and allows subclasses to return a response
* {@code Element}.
*
* <p>The given DOM {@code Document} is to be used for constructing {@code Node}s, by using the various
* {@code create} methods.
*
* @param requestElement the contents of the SOAP message as DOM elements
* @param responseDocument a DOM document to be used for constructing {@code Node}s
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement, Document responseDocument) throws Exception;
/**
* Template method that subclasses must implement to process the request.
*
* <p>Offers the request payload as a DOM {@code Element}, and allows subclasses to return a response
* {@code Element}.
*
* <p>The given DOM {@code Document} is to be used for constructing {@code Node}s, by using the various
* {@code create} methods.
*
* @param requestElement the contents of the SOAP message as DOM elements
* @param responseDocument a DOM document to be used for constructing {@code Node}s
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement, Document responseDocument) throws Exception;
}

View File

@@ -36,117 +36,117 @@ import org.springframework.ws.server.EndpointExceptionResolver;
*/
public abstract class AbstractEndpointExceptionResolver implements EndpointExceptionResolver, Ordered {
/** Shared {@link Log} for subclasses to use. */
protected final Log logger = LogFactory.getLog(getClass());
/** Shared {@link Log} for subclasses to use. */
protected final Log logger = LogFactory.getLog(getClass());
private int order = Integer.MAX_VALUE; // default: same as non-Ordered
private int order = Integer.MAX_VALUE; // default: same as non-Ordered
private Set<?> mappedEndpoints;
private Set<?> mappedEndpoints;
private Log warnLogger;
private Log warnLogger;
/**
* Specify the set of endpoints that this exception resolver should map. <p>The exception mappings and the default
* fault will only apply to the specified endpoints.
*
* <p>If no endpoints are set, both the exception mappings and the default fault will apply to all handlers. This means
* that a specified default fault will be used as fallback for all exceptions; any further
* {@code EndpointExceptionResolvers} in the chain will be ignored in this case.
*/
public void setMappedEndpoints(Set<?> mappedEndpoints) {
this.mappedEndpoints = mappedEndpoints;
}
/**
* Specify the set of endpoints that this exception resolver should map. <p>The exception mappings and the default
* fault will only apply to the specified endpoints.
*
* <p>If no endpoints are set, both the exception mappings and the default fault will apply to all handlers. This means
* that a specified default fault will be used as fallback for all exceptions; any further
* {@code EndpointExceptionResolvers} in the chain will be ignored in this case.
*/
public void setMappedEndpoints(Set<?> mappedEndpoints) {
this.mappedEndpoints = mappedEndpoints;
}
/**
* Set the log category for warn logging. The name will be passed to the underlying logger implementation through
* Commons Logging, getting interpreted as log category according to the logger's configuration.
*
* <p>Default is no warn logging. Specify this setting to activate warn logging into a specific category.
* Alternatively, override the {@link #logException} method for custom logging.
*
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setWarnLogCategory(String loggerName) {
this.warnLogger = LogFactory.getLog(loggerName);
}
/**
* Set the log category for warn logging. The name will be passed to the underlying logger implementation through
* Commons Logging, getting interpreted as log category according to the logger's configuration.
*
* <p>Default is no warn logging. Specify this setting to activate warn logging into a specific category.
* Alternatively, override the {@link #logException} method for custom logging.
*
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setWarnLogCategory(String loggerName) {
this.warnLogger = LogFactory.getLog(loggerName);
}
/**
* Specify the order value for this mapping.
*
* <p>Default value is {@link Integer#MAX_VALUE}, meaning that it's non-ordered.
*
* @see org.springframework.core.Ordered#getOrder()
*/
public final void setOrder(int order) {
this.order = order;
}
/**
* Specify the order value for this mapping.
*
* <p>Default value is {@link Integer#MAX_VALUE}, meaning that it's non-ordered.
*
* @see org.springframework.core.Ordered#getOrder()
*/
public final void setOrder(int order) {
this.order = order;
}
@Override
public final int getOrder() {
return order;
}
@Override
public final int getOrder() {
return order;
}
/**
* Default implementation that checks whether the given {@code endpoint} is in the set of {@link
* #setMappedEndpoints mapped endpoints}.
*
* @see #resolveExceptionInternal(MessageContext,Object,Exception)
*/
@Override
public final boolean resolveException(MessageContext messageContext, Object endpoint, Exception ex) {
Object mappedEndpoint = endpoint instanceof MethodEndpoint ? ((MethodEndpoint) endpoint).getBean() : endpoint;
if (mappedEndpoints != null && !mappedEndpoints.contains(mappedEndpoint)) {
return false;
}
// Log exception, both at debug log level and at warn level, if desired.
if (logger.isDebugEnabled()) {
logger.debug("Resolving exception from endpoint [" + endpoint + "]: " + ex);
}
logException(ex, messageContext);
return resolveExceptionInternal(messageContext, endpoint, ex);
}
/**
* Default implementation that checks whether the given {@code endpoint} is in the set of {@link
* #setMappedEndpoints mapped endpoints}.
*
* @see #resolveExceptionInternal(MessageContext,Object,Exception)
*/
@Override
public final boolean resolveException(MessageContext messageContext, Object endpoint, Exception ex) {
Object mappedEndpoint = endpoint instanceof MethodEndpoint ? ((MethodEndpoint) endpoint).getBean() : endpoint;
if (mappedEndpoints != null && !mappedEndpoints.contains(mappedEndpoint)) {
return false;
}
// Log exception, both at debug log level and at warn level, if desired.
if (logger.isDebugEnabled()) {
logger.debug("Resolving exception from endpoint [" + endpoint + "]: " + ex);
}
logException(ex, messageContext);
return resolveExceptionInternal(messageContext, endpoint, ex);
}
/**
* Log the given exception at warn level, provided that warn logging has been activated through the {@link
* #setWarnLogCategory "warnLogCategory"} property.
*
* <p>Calls {@link #buildLogMessage} in order to determine the concrete message to log. Always passes the full
* exception to the logger.
*
* @param ex the exception that got thrown during handler execution
* @param messageContext current message context request
* @see #setWarnLogCategory
* @see #buildLogMessage
* @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
protected void logException(Exception ex, MessageContext messageContext) {
if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
this.warnLogger.warn(buildLogMessage(ex, messageContext), ex);
}
}
/**
* Log the given exception at warn level, provided that warn logging has been activated through the {@link
* #setWarnLogCategory "warnLogCategory"} property.
*
* <p>Calls {@link #buildLogMessage} in order to determine the concrete message to log. Always passes the full
* exception to the logger.
*
* @param ex the exception that got thrown during handler execution
* @param messageContext current message context request
* @see #setWarnLogCategory
* @see #buildLogMessage
* @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
protected void logException(Exception ex, MessageContext messageContext) {
if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
this.warnLogger.warn(buildLogMessage(ex, messageContext), ex);
}
}
/**
* Build a log message for the given exception, occured during processing the given message context.
*
* @param ex the exception that got thrown during handler execution
* @param messageContext the message context
* @return the log message to use
*/
protected String buildLogMessage(Exception ex, MessageContext messageContext) {
return "Endpoint execution resulted in exception";
}
/**
* Build a log message for the given exception, occured during processing the given message context.
*
* @param ex the exception that got thrown during handler execution
* @param messageContext the message context
* @return the log message to use
*/
protected String buildLogMessage(Exception ex, MessageContext messageContext) {
return "Endpoint execution resulted in exception";
}
/**
* Template method for resolving exceptions that is called by {@link #resolveException}.
*
* @param messageContext current message context
* @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception
* @param ex the exception that got thrown during endpoint execution
* @return {@code true} if resolved; {@code false} otherwise
* @see #resolveException(MessageContext,Object,Exception)
*/
protected abstract boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex);
/**
* Template method for resolving exceptions that is called by {@link #resolveException}.
*
* @param messageContext current message context
* @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception
* @param ex the exception that got thrown during endpoint execution
* @return {@code true} if resolved; {@code false} otherwise
* @see #resolveException(MessageContext,Object,Exception)
*/
protected abstract boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex);
}

View File

@@ -45,63 +45,63 @@ import org.springframework.xml.transform.TransformerObjectSupport;
@Deprecated
public abstract class AbstractJDomPayloadEndpoint extends TransformerObjectSupport implements PayloadEndpoint {
private boolean alwaysTransform = false;
private boolean alwaysTransform = false;
/**
* Set if the request {@link Source} should always be transformed into a new {@link JDOMResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
/**
* Set if the request {@link Source} should always be transformed into a new {@link JDOMResult}.
*
* <p>Default is {@code false}, which is faster.
*/
public void setAlwaysTransform(boolean alwaysTransform) {
this.alwaysTransform = alwaysTransform;
}
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = getDocumentElement(request);
Element responseElement = invokeInternal(requestElement);
return responseElement != null ? new JDOMSource(responseElement) : null;
}
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = getDocumentElement(request);
Element responseElement = invokeInternal(requestElement);
return responseElement != null ? new JDOMSource(responseElement) : null;
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link DOMSource}, and uses a {@link DOMBuilder} to create
* a JDOM {@link Element}. In all other cases, or when {@linkplain #setAlwaysTransform(boolean) alwaysTransform} is
* {@code true}, the source is transformed into a {@link JDOMResult}, which is more expensive. If the passed source
* is {@code null}, {@code null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @return the document element
* @throws TransformerException in case of errors
*/
protected Element getDocumentElement(Source source) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
DOMBuilder domBuilder = new DOMBuilder();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return domBuilder.build((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = domBuilder.build((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
JDOMResult jdomResult = new JDOMResult();
transform(source, jdomResult);
return jdomResult.getDocument().getRootElement();
}
/**
* Returns the payload element of the given source.
*
* <p>Default implementation checks whether the source is a {@link DOMSource}, and uses a {@link DOMBuilder} to create
* a JDOM {@link Element}. In all other cases, or when {@linkplain #setAlwaysTransform(boolean) alwaysTransform} is
* {@code true}, the source is transformed into a {@link JDOMResult}, which is more expensive. If the passed source
* is {@code null}, {@code null} is returned.
*
* @param source the source to return the root element of; can be {@code null}
* @return the document element
* @throws TransformerException in case of errors
*/
protected Element getDocumentElement(Source source) throws TransformerException {
if (source == null) {
return null;
}
if (!alwaysTransform && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
DOMBuilder domBuilder = new DOMBuilder();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return domBuilder.build((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = domBuilder.build((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
JDOMResult jdomResult = new JDOMResult();
transform(source, jdomResult);
return jdomResult.getDocument().getRootElement();
}
/**
* Template method. Subclasses must implement this. Offers the request payload as a JDOM {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* @param requestElement the contents of the SOAP message as JDOM element
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement) throws Exception;
/**
* Template method. Subclasses must implement this. Offers the request payload as a JDOM {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* @param requestElement the contents of the SOAP message as JDOM element
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement) throws Exception;
}

View File

@@ -42,137 +42,137 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public abstract class AbstractLoggingInterceptor extends TransformerObjectSupport implements EndpointInterceptor {
/**
* The default {@code Log} instance used to write trace messages. This instance is mapped to the implementing
* {@code Class}.
*/
protected transient Log logger = LogFactory.getLog(getClass());
/**
* The default {@code Log} instance used to write trace messages. This instance is mapped to the implementing
* {@code Class}.
*/
protected transient Log logger = LogFactory.getLog(getClass());
private boolean logRequest = true;
private boolean logRequest = true;
private boolean logResponse = true;
private boolean logResponse = true;
/** Indicates whether the request should be logged. Default is {@code true}. */
public final void setLogRequest(boolean logRequest) {
this.logRequest = logRequest;
}
/** Indicates whether the request should be logged. Default is {@code true}. */
public final void setLogRequest(boolean logRequest) {
this.logRequest = logRequest;
}
/** Indicates whether the response should be logged. Default is {@code true}. */
public final void setLogResponse(boolean logResponse) {
this.logResponse = logResponse;
}
/** Indicates whether the response should be logged. Default is {@code true}. */
public final void setLogResponse(boolean logResponse) {
this.logResponse = logResponse;
}
/**
* Set the name of the logger to use. The name will be passed to the underlying logger implementation through
* Commons Logging, getting interpreted as log category according to the logger's configuration.
*
* <p>This can be specified to not log into the category of a class but rather into a specific named category.
*
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setLoggerName(String loggerName) {
this.logger = LogFactory.getLog(loggerName);
}
/**
* Set the name of the logger to use. The name will be passed to the underlying logger implementation through
* Commons Logging, getting interpreted as log category according to the logger's configuration.
*
* <p>This can be specified to not log into the category of a class but rather into a specific named category.
*
* @see org.apache.commons.logging.LogFactory#getLog(String)
* @see org.apache.log4j.Logger#getLogger(String)
* @see java.util.logging.Logger#getLogger(String)
*/
public void setLoggerName(String loggerName) {
this.logger = LogFactory.getLog(loggerName);
}
/**
* Logs the request message payload. Logging only occurs if {@code logRequest} is set to {@code true},
* which is the default.
*
* @param messageContext the message context
* @return {@code true}
* @throws TransformerException when the payload cannot be transformed to a string
*/
@Override
public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws TransformerException {
if (logRequest && isLogEnabled()) {
logMessageSource("Request: ", getSource(messageContext.getRequest()));
}
return true;
}
/**
* Logs the request message payload. Logging only occurs if {@code logRequest} is set to {@code true},
* which is the default.
*
* @param messageContext the message context
* @return {@code true}
* @throws TransformerException when the payload cannot be transformed to a string
*/
@Override
public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws TransformerException {
if (logRequest && isLogEnabled()) {
logMessageSource("Request: ", getSource(messageContext.getRequest()));
}
return true;
}
/**
* Logs the response message payload. Logging only occurs if {@code logResponse} is set to {@code true},
* which is the default.
*
* @param messageContext the message context
* @return {@code true}
* @throws TransformerException when the payload cannot be transformed to a string
*/
@Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
if (logResponse && isLogEnabled()) {
logMessageSource("Response: ", getSource(messageContext.getResponse()));
}
return true;
}
/**
* Logs the response message payload. Logging only occurs if {@code logResponse} is set to {@code true},
* which is the default.
*
* @param messageContext the message context
* @return {@code true}
* @throws TransformerException when the payload cannot be transformed to a string
*/
@Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
if (logResponse && isLogEnabled()) {
logMessageSource("Response: ", getSource(messageContext.getResponse()));
}
return true;
}
/** Does nothing by default. Faults are not logged. */
@Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
/** Does nothing by default. Faults are not logged. */
@Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
/** Does nothing by default*/
@Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) {
}
/** Does nothing by default*/
@Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) {
}
/**
* Determine whether the {@link #logger} field is enabled.
*
* <p>Default is {@code true} when the "debug" level is enabled. Subclasses can override this to change the level
* under which logging occurs.
*/
protected boolean isLogEnabled() {
return logger.isDebugEnabled();
}
/**
* Determine whether the {@link #logger} field is enabled.
*
* <p>Default is {@code true} when the "debug" level is enabled. Subclasses can override this to change the level
* under which logging occurs.
*/
protected boolean isLogEnabled() {
return logger.isDebugEnabled();
}
private Transformer createNonIndentingTransformer() throws TransformerConfigurationException {
Transformer transformer = createTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
return transformer;
}
private Transformer createNonIndentingTransformer() throws TransformerConfigurationException {
Transformer transformer = createTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
return transformer;
}
/**
* Logs the given {@link Source source} to the {@link #logger}, using the message as a prefix.
*
* <p>By default, this message creates a string representation of the given source, and delegates to {@link
* #logMessage(String)}.
*
* @param logMessage the log message
* @param source the source to be logged
* @throws TransformerException in case of errors
*/
protected void logMessageSource(String logMessage, Source source) throws TransformerException {
if (source != null) {
Transformer transformer = createNonIndentingTransformer();
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String message = logMessage + writer.toString();
logMessage(message);
}
}
/**
* Logs the given {@link Source source} to the {@link #logger}, using the message as a prefix.
*
* <p>By default, this message creates a string representation of the given source, and delegates to {@link
* #logMessage(String)}.
*
* @param logMessage the log message
* @param source the source to be logged
* @throws TransformerException in case of errors
*/
protected void logMessageSource(String logMessage, Source source) throws TransformerException {
if (source != null) {
Transformer transformer = createNonIndentingTransformer();
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String message = logMessage + writer.toString();
logMessage(message);
}
}
/**
* Logs the given string message.
*
* <p>By default, this method uses a "debug" level of logging. Subclasses can override this method to change the level
* of logging used by the logger.
*
* @param message the message
*/
protected void logMessage(String message) {
logger.debug(message);
}
/**
* Logs the given string message.
*
* <p>By default, this method uses a "debug" level of logging. Subclasses can override this method to change the level
* of logging used by the logger.
*
* @param message the message
*/
protected void logMessage(String message) {
logger.debug(message);
}
/**
* Abstract template method that returns the {@code Source} for the given {@code WebServiceMessage}.
*
* @param message the message
* @return the source of the message
*/
protected abstract Source getSource(WebServiceMessage message);
/**
* Abstract template method that returns the {@code Source} for the given {@code WebServiceMessage}.
*
* @param message the message
* @return the source of the message
*/
protected abstract Source getSource(WebServiceMessage message);
}

View File

@@ -46,167 +46,167 @@ import org.springframework.ws.support.MarshallingUtils;
@Deprecated
public abstract class AbstractMarshallingPayloadEndpoint implements MessageEndpoint, InitializingBean {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private Marshaller marshaller;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private Unmarshaller unmarshaller;
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint}. The {@link Marshaller} and {@link Unmarshaller}
* must be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
protected AbstractMarshallingPayloadEndpoint() {
}
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint}. The {@link Marshaller} and {@link Unmarshaller}
* must be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
protected AbstractMarshallingPayloadEndpoint() {
}
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint} with the given marshaller. The given {@link
* Marshaller} should also implements the {@link Unmarshaller}, since it is used for both marshalling and
* unmarshalling. If it is not, 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} does not implement the {@link Unmarshaller}
* interface
* @see #AbstractMarshallingPayloadEndpoint(Marshaller,Unmarshaller)
*/
protected AbstractMarshallingPayloadEndpoint(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 explicitly by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor.");
}
else {
setMarshaller(marshaller);
setUnmarshaller((Unmarshaller) marshaller);
}
}
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint} with the given marshaller. The given {@link
* Marshaller} should also implements the {@link Unmarshaller}, since it is used for both marshalling and
* unmarshalling. If it is not, 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} does not implement the {@link Unmarshaller}
* interface
* @see #AbstractMarshallingPayloadEndpoint(Marshaller,Unmarshaller)
*/
protected AbstractMarshallingPayloadEndpoint(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 explicitly by using the " +
"AbstractMarshallingPayloadEndpoint(Marshaller, Unmarshaller) constructor.");
}
else {
setMarshaller(marshaller);
setUnmarshaller((Unmarshaller) marshaller);
}
}
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
protected AbstractMarshallingPayloadEndpoint(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
setMarshaller(marshaller);
setUnmarshaller(unmarshaller);
}
/**
* Creates a new {@code AbstractMarshallingPayloadEndpoint} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
protected AbstractMarshallingPayloadEndpoint(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
setMarshaller(marshaller);
setUnmarshaller(unmarshaller);
}
/** Returns the marshaller used for transforming objects into XML. */
public Marshaller getMarshaller() {
return marshaller;
}
/** Returns the marshaller used for transforming objects into XML. */
public Marshaller getMarshaller() {
return marshaller;
}
/** Sets the marshaller used for transforming objects into XML. */
public final void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Sets the marshaller used for transforming objects into XML. */
public final void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Returns the unmarshaller used for transforming XML into objects. */
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/** Returns the unmarshaller used for transforming XML into objects. */
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/** Sets the unmarshaller used for transforming XML into objects. */
public final void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
/** Sets the unmarshaller used for transforming XML into objects. */
public final void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
@Override
public void afterPropertiesSet() throws Exception {
afterMarshallerSet();
}
@Override
public void afterPropertiesSet() throws Exception {
afterMarshallerSet();
}
@Override
public final void invoke(MessageContext messageContext) throws Exception {
WebServiceMessage request = messageContext.getRequest();
Object requestObject = unmarshalRequest(request);
if (onUnmarshalRequest(messageContext, requestObject)) {
Object responseObject = invokeInternal(requestObject);
if (responseObject != null) {
WebServiceMessage response = messageContext.getResponse();
marshalResponse(responseObject, response);
onMarshalResponse(messageContext, requestObject, responseObject);
}
}
}
@Override
public final void invoke(MessageContext messageContext) throws Exception {
WebServiceMessage request = messageContext.getRequest();
Object requestObject = unmarshalRequest(request);
if (onUnmarshalRequest(messageContext, requestObject)) {
Object responseObject = invokeInternal(requestObject);
if (responseObject != null) {
WebServiceMessage response = messageContext.getResponse();
marshalResponse(responseObject, response);
onMarshalResponse(messageContext, requestObject, responseObject);
}
}
}
private Object unmarshalRequest(WebServiceMessage request) throws IOException {
Unmarshaller unmarshaller = getUnmarshaller();
Assert.notNull(unmarshaller, "No unmarshaller registered. Check configuration of endpoint.");
Object requestObject = MarshallingUtils.unmarshal(unmarshaller, request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + requestObject + "]");
}
return requestObject;
}
private Object unmarshalRequest(WebServiceMessage request) throws IOException {
Unmarshaller unmarshaller = getUnmarshaller();
Assert.notNull(unmarshaller, "No unmarshaller registered. Check configuration of endpoint.");
Object requestObject = MarshallingUtils.unmarshal(unmarshaller, request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + requestObject + "]");
}
return requestObject;
}
/**
* Callback for post-processing in terms of unmarshalling. Called on each message request, after standard
* unmarshalling.
*
* <p>Default implementation returns {@code true}.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @return {@code true} to continue and call {@link #invokeInternal(Object)}; {@code false} otherwise
*/
protected boolean onUnmarshalRequest(MessageContext messageContext, Object requestObject) throws Exception {
return true;
}
/**
* Callback for post-processing in terms of unmarshalling. Called on each message request, after standard
* unmarshalling.
*
* <p>Default implementation returns {@code true}.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @return {@code true} to continue and call {@link #invokeInternal(Object)}; {@code false} otherwise
*/
protected boolean onUnmarshalRequest(MessageContext messageContext, Object requestObject) throws Exception {
return true;
}
private void marshalResponse(Object responseObject, WebServiceMessage response) throws IOException {
Marshaller marshaller = getMarshaller();
Assert.notNull(marshaller, "No marshaller registered. Check configuration of endpoint.");
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + responseObject + "] to response payload");
}
MarshallingUtils.marshal(marshaller, responseObject, response);
}
private void marshalResponse(Object responseObject, WebServiceMessage response) throws IOException {
Marshaller marshaller = getMarshaller();
Assert.notNull(marshaller, "No marshaller registered. Check configuration of endpoint.");
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + responseObject + "] to response payload");
}
MarshallingUtils.marshal(marshaller, responseObject, response);
}
/**
* Callback for post-processing in terms of marshalling. Called on each message request, after standard marshalling
* of the response. Only invoked when {@link #invokeInternal(Object)} returns an object.
*
* <p>Default implementation is empty.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @param responseObject the object marshalled to the {@link MessageContext#getResponse()} request}
*/
protected void onMarshalResponse(MessageContext messageContext, Object requestObject, Object responseObject) {
}
/**
* Callback for post-processing in terms of marshalling. Called on each message request, after standard marshalling
* of the response. Only invoked when {@link #invokeInternal(Object)} returns an object.
*
* <p>Default implementation is empty.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @param responseObject the object marshalled to the {@link MessageContext#getResponse()} request}
*/
protected void onMarshalResponse(MessageContext messageContext, Object requestObject, Object responseObject) {
}
/**
* Template method that gets called after the marshaller and unmarshaller have been set.
*
* <p>The default implementation does nothing.
*
* @deprecated as of Spring Web Services 1.5: {@link #afterPropertiesSet()} is no longer final, so this can safely
* be overridden in subclasses
*/
@Deprecated
public void afterMarshallerSet() throws Exception {
}
/**
* Template method that gets called after the marshaller and unmarshaller have been set.
*
* <p>The default implementation does nothing.
*
* @deprecated as of Spring Web Services 1.5: {@link #afterPropertiesSet()} is no longer final, so this can safely
* be overridden in subclasses
*/
@Deprecated
public void afterMarshallerSet() throws Exception {
}
/**
* Template method that subclasses must implement to process a request.
*
* <p>The unmarshalled request object is passed as a parameter, and the returned object is marshalled to a response. If
* no response is required, return {@code null}.
*
* @param requestObject the unmarshalled message payload as an object
* @return the object to be marshalled as response, or {@code null} if a response is not required
*/
protected abstract Object invokeInternal(Object requestObject) throws Exception;
/**
* Template method that subclasses must implement to process a request.
*
* <p>The unmarshalled request object is passed as a parameter, and the returned object is marshalled to a response. If
* no response is required, return {@code null}.
*
* @param requestObject the unmarshalled message payload as an object
* @return the object to be marshalled as response, or {@code null} if a response is not required
*/
protected abstract Object invokeInternal(Object requestObject) throws Exception;
}

View File

@@ -40,43 +40,43 @@ import org.springframework.xml.transform.TransformerObjectSupport;
@Deprecated
public abstract class AbstractSaxPayloadEndpoint extends TransformerObjectSupport implements PayloadEndpoint {
/**
* Invokes the provided {@code ContentHandler} on the given request. After parsing has been done, the provided
* response is returned.
*
* @see #createContentHandler()
* @see #getResponse(org.xml.sax.ContentHandler)
*/
@Override
public final Source invoke(Source request) throws Exception {
ContentHandler contentHandler = null;
if (request != null) {
contentHandler = createContentHandler();
SAXResult result = new SAXResult(contentHandler);
transform(request, result);
}
return getResponse(contentHandler);
}
/**
* Invokes the provided {@code ContentHandler} on the given request. After parsing has been done, the provided
* response is returned.
*
* @see #createContentHandler()
* @see #getResponse(org.xml.sax.ContentHandler)
*/
@Override
public final Source invoke(Source request) throws Exception {
ContentHandler contentHandler = null;
if (request != null) {
contentHandler = createContentHandler();
SAXResult result = new SAXResult(contentHandler);
transform(request, result);
}
return getResponse(contentHandler);
}
/**
* Returns the SAX {@code ContentHandler} used to parse the incoming request payload. A new instance should be
* created for each call, because of thread-safety. The content handler can be used to hold request-specific state.
*
* <p>If an incoming message does not contain a payload, this method will not be invoked.
*
* @return a SAX content handler to be used for parsing
*/
protected abstract ContentHandler createContentHandler() throws Exception;
/**
* Returns the SAX {@code ContentHandler} used to parse the incoming request payload. A new instance should be
* created for each call, because of thread-safety. The content handler can be used to hold request-specific state.
*
* <p>If an incoming message does not contain a payload, this method will not be invoked.
*
* @return a SAX content handler to be used for parsing
*/
protected abstract ContentHandler createContentHandler() throws Exception;
/**
* Returns the response to be given, if any. This method is called after the request payload has been parsed using
* the SAX {@code ContentHandler}. The passed {@code ContentHandler} is created by {@link
* #createContentHandler()}: it can be used to hold request-specific state.
*
* <p>If an incoming message does not contain a payload, this method will be invoked with {@code null} as content
* handler.
*
* @param contentHandler the content handler used to parse the request
*/
protected abstract Source getResponse(ContentHandler contentHandler) throws Exception;
/**
* Returns the response to be given, if any. This method is called after the request payload has been parsed using
* the SAX {@code ContentHandler}. The passed {@code ContentHandler} is created by {@link
* #createContentHandler()}: it can be used to hold request-specific state.
*
* <p>If an incoming message does not contain a payload, this method will be invoked with {@code null} as content
* handler.
*
* @param contentHandler the content handler used to parse the request
*/
protected abstract Source getResponse(ContentHandler contentHandler) throws Exception;
}

View File

@@ -42,7 +42,7 @@ import org.springframework.ws.context.MessageContext;
*
* @author Arjen Poutsma
* @see #invokeInternal(javax.xml.stream.XMLEventReader,javax.xml.stream.util.XMLEventConsumer,
* javax.xml.stream.XMLEventFactory)
* javax.xml.stream.XMLEventFactory)
* @see XMLEventReader
* @see XMLEventWriter
* @since 1.0.0
@@ -51,199 +51,199 @@ import org.springframework.ws.context.MessageContext;
@Deprecated
public abstract class AbstractStaxEventPayloadEndpoint extends AbstractStaxPayloadEndpoint implements MessageEndpoint {
private XMLEventFactory eventFactory;
private XMLEventFactory eventFactory;
@Override
public final void invoke(MessageContext messageContext) throws Exception {
XMLEventReader eventReader = getEventReader(messageContext.getRequest().getPayloadSource());
XMLEventWriter streamWriter = new ResponseCreatingEventWriter(messageContext);
invokeInternal(eventReader, streamWriter, getEventFactory());
streamWriter.flush();
}
@Override
public final void invoke(MessageContext messageContext) throws Exception {
XMLEventReader eventReader = getEventReader(messageContext.getRequest().getPayloadSource());
XMLEventWriter streamWriter = new ResponseCreatingEventWriter(messageContext);
invokeInternal(eventReader, streamWriter, getEventFactory());
streamWriter.flush();
}
/**
* Create a {@code XMLEventFactory} that this endpoint will use to create {@code XMLEvent}s. Can be
* overridden in subclasses, adding further initialization of the factory. The resulting
* {@code XMLEventFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLEventFactory}
*/
protected XMLEventFactory createXmlEventFactory() {
return XMLEventFactory.newInstance();
}
/**
* Create a {@code XMLEventFactory} that this endpoint will use to create {@code XMLEvent}s. Can be
* overridden in subclasses, adding further initialization of the factory. The resulting
* {@code XMLEventFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLEventFactory}
*/
protected XMLEventFactory createXmlEventFactory() {
return XMLEventFactory.newInstance();
}
/** Returns an {@code XMLEventFactory} to read XML from. */
private XMLEventFactory getEventFactory() {
if (eventFactory == null) {
eventFactory = createXmlEventFactory();
}
return eventFactory;
}
/** Returns an {@code XMLEventFactory} to read XML from. */
private XMLEventFactory getEventFactory() {
if (eventFactory == null) {
eventFactory = createXmlEventFactory();
}
return eventFactory;
}
private XMLEventReader getEventReader(Source source) throws XMLStreamException, TransformerException {
if (source == null) {
return null;
}
XMLEventReader eventReader = null;
if (StaxUtils.isStaxSource(source)) {
eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader == null) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader != null) {
try {
eventReader = getInputFactory().createXMLEventReader(streamReader);
}
catch (XMLStreamException ex) {
eventReader = null;
}
}
}
}
if (eventReader == null) {
try {
eventReader = getInputFactory().createXMLEventReader(source);
}
catch (XMLStreamException ex) {
eventReader = null;
}
catch (UnsupportedOperationException ex) {
eventReader = null;
}
}
if (eventReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(source, new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
eventReader = getInputFactory().createXMLEventReader(is);
}
return eventReader;
}
private XMLEventReader getEventReader(Source source) throws XMLStreamException, TransformerException {
if (source == null) {
return null;
}
XMLEventReader eventReader = null;
if (StaxUtils.isStaxSource(source)) {
eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader == null) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader != null) {
try {
eventReader = getInputFactory().createXMLEventReader(streamReader);
}
catch (XMLStreamException ex) {
eventReader = null;
}
}
}
}
if (eventReader == null) {
try {
eventReader = getInputFactory().createXMLEventReader(source);
}
catch (XMLStreamException ex) {
eventReader = null;
}
catch (UnsupportedOperationException ex) {
eventReader = null;
}
}
if (eventReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(source, new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
eventReader = getInputFactory().createXMLEventReader(is);
}
return eventReader;
}
private XMLEventWriter getEventWriter(Result result) {
XMLEventWriter eventWriter = null;
if (StaxUtils.isStaxResult(result)) {
eventWriter = StaxUtils.getXMLEventWriter(result);
}
if (eventWriter == null) {
try {
eventWriter = getOutputFactory().createXMLEventWriter(result);
}
catch (XMLStreamException ex) {
// ignore
}
}
return eventWriter;
}
private XMLEventWriter getEventWriter(Result result) {
XMLEventWriter eventWriter = null;
if (StaxUtils.isStaxResult(result)) {
eventWriter = StaxUtils.getXMLEventWriter(result);
}
if (eventWriter == null) {
try {
eventWriter = getOutputFactory().createXMLEventWriter(result);
}
catch (XMLStreamException ex) {
// ignore
}
}
return eventWriter;
}
/**
* Template method. Subclasses must implement this. Offers the request payload as a {@code XMLEventReader}, and
* a {@code XMLEventWriter} to write the response payload to.
*
* @param eventReader the reader to read the payload events from
* @param eventWriter the writer to write payload events to
* @param eventFactory an {@code XMLEventFactory} that can be used to create events
*/
protected abstract void invokeInternal(XMLEventReader eventReader,
XMLEventConsumer eventWriter,
XMLEventFactory eventFactory) throws Exception;
/**
* Template method. Subclasses must implement this. Offers the request payload as a {@code XMLEventReader}, and
* a {@code XMLEventWriter} to write the response payload to.
*
* @param eventReader the reader to read the payload events from
* @param eventWriter the writer to write payload events to
* @param eventFactory an {@code XMLEventFactory} that can be used to create events
*/
protected abstract void invokeInternal(XMLEventReader eventReader,
XMLEventConsumer eventWriter,
XMLEventFactory eventFactory) throws Exception;
/**
* Implementation of the {@code XMLEventWriter} interface that creates a response
* {@code WebServiceMessage} as soon as any method is called, thus lazily creating the response.
*/
private class ResponseCreatingEventWriter implements XMLEventWriter {
/**
* Implementation of the {@code XMLEventWriter} interface that creates a response
* {@code WebServiceMessage} as soon as any method is called, thus lazily creating the response.
*/
private class ResponseCreatingEventWriter implements XMLEventWriter {
private XMLEventWriter eventWriter;
private XMLEventWriter eventWriter;
private MessageContext messageContext;
private MessageContext messageContext;
private ByteArrayOutputStream os;
private ByteArrayOutputStream os;
public ResponseCreatingEventWriter(MessageContext messageContext) {
this.messageContext = messageContext;
}
public ResponseCreatingEventWriter(MessageContext messageContext) {
this.messageContext = messageContext;
}
@Override
public NamespaceContext getNamespaceContext() {
return eventWriter.getNamespaceContext();
}
@Override
public NamespaceContext getNamespaceContext() {
return eventWriter.getNamespaceContext();
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
createEventWriter();
eventWriter.setNamespaceContext(context);
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
createEventWriter();
eventWriter.setNamespaceContext(context);
}
@Override
public void add(XMLEventReader reader) throws XMLStreamException {
createEventWriter();
while (reader.hasNext()) {
add(reader.nextEvent());
}
}
@Override
public void add(XMLEventReader reader) throws XMLStreamException {
createEventWriter();
while (reader.hasNext()) {
add(reader.nextEvent());
}
}
@Override
public void add(XMLEvent event) throws XMLStreamException {
createEventWriter();
eventWriter.add(event);
if (event.isEndDocument()) {
if (os != null) {
eventWriter.flush();
// if we used an output stream cache, we have to transform it to the response again
try {
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
transform(new StreamSource(is), messageContext.getResponse().getPayloadResult());
}
catch (TransformerException ex) {
throw new XMLStreamException(ex);
}
}
}
}
@Override
public void add(XMLEvent event) throws XMLStreamException {
createEventWriter();
eventWriter.add(event);
if (event.isEndDocument()) {
if (os != null) {
eventWriter.flush();
// if we used an output stream cache, we have to transform it to the response again
try {
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
transform(new StreamSource(is), messageContext.getResponse().getPayloadResult());
}
catch (TransformerException ex) {
throw new XMLStreamException(ex);
}
}
}
}
@Override
public void close() throws XMLStreamException {
if (eventWriter != null) {
eventWriter.close();
}
}
@Override
public void close() throws XMLStreamException {
if (eventWriter != null) {
eventWriter.close();
}
}
@Override
public void flush() throws XMLStreamException {
if (eventWriter != null) {
eventWriter.flush();
}
}
@Override
public void flush() throws XMLStreamException {
if (eventWriter != null) {
eventWriter.flush();
}
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
createEventWriter();
return eventWriter.getPrefix(uri);
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
createEventWriter();
return eventWriter.getPrefix(uri);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
createEventWriter();
eventWriter.setDefaultNamespace(uri);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
createEventWriter();
eventWriter.setDefaultNamespace(uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
createEventWriter();
eventWriter.setPrefix(prefix, uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
createEventWriter();
eventWriter.setPrefix(prefix, uri);
}
private void createEventWriter() throws XMLStreamException {
if (eventWriter == null) {
WebServiceMessage response = messageContext.getResponse();
eventWriter = getEventWriter(response.getPayloadResult());
if (eventWriter == null) {
// as a final resort, use a stream, and transform that at endDocument()
os = new ByteArrayOutputStream();
eventWriter = getOutputFactory().createXMLEventWriter(os);
}
}
}
}
private void createEventWriter() throws XMLStreamException {
if (eventWriter == null) {
WebServiceMessage response = messageContext.getResponse();
eventWriter = getEventWriter(response.getPayloadResult());
if (eventWriter == null) {
// as a final resort, use a stream, and transform that at endDocument()
os = new ByteArrayOutputStream();
eventWriter = getOutputFactory().createXMLEventWriter(os);
}
}
}
}
}

View File

@@ -35,45 +35,45 @@ import org.springframework.xml.transform.TransformerObjectSupport;
@SuppressWarnings("Since15")
public abstract class AbstractStaxPayloadEndpoint extends TransformerObjectSupport {
private XMLInputFactory inputFactory;
private XMLInputFactory inputFactory;
private XMLOutputFactory outputFactory;
private XMLOutputFactory outputFactory;
/** Returns an {@code XMLInputFactory} to read XML from. */
protected final XMLInputFactory getInputFactory() {
if (inputFactory == null) {
inputFactory = createXmlInputFactory();
}
return inputFactory;
}
/** Returns an {@code XMLInputFactory} to read XML from. */
protected final XMLInputFactory getInputFactory() {
if (inputFactory == null) {
inputFactory = createXmlInputFactory();
}
return inputFactory;
}
/** Returns an {@code XMLOutputFactory} to write XML to. */
protected final XMLOutputFactory getOutputFactory() {
if (outputFactory == null) {
outputFactory = createXmlOutputFactory();
}
return outputFactory;
}
/** Returns an {@code XMLOutputFactory} to write XML to. */
protected final XMLOutputFactory getOutputFactory() {
if (outputFactory == null) {
outputFactory = createXmlOutputFactory();
}
return outputFactory;
}
/**
* Create a {@code XMLInputFactory} that this endpoint will use to create {@code XMLStreamReader}s or
* {@code XMLEventReader}. Can be overridden in subclasses, adding further initialization of the factory. The
* resulting {@code XMLInputFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLInputFactory}
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
/**
* Create a {@code XMLInputFactory} that this endpoint will use to create {@code XMLStreamReader}s or
* {@code XMLEventReader}. Can be overridden in subclasses, adding further initialization of the factory. The
* resulting {@code XMLInputFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLInputFactory}
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
/**
* Create a {@code XMLOutputFactory} that this endpoint will use to create {@code XMLStreamWriters}s or
* {@code XMLEventWriters}. Can be overridden in subclasses, adding further initialization of the factory. The
* resulting {@code XMLOutputFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLOutputFactory}
*/
protected XMLOutputFactory createXmlOutputFactory() {
return XMLOutputFactory.newInstance();
}
/**
* Create a {@code XMLOutputFactory} that this endpoint will use to create {@code XMLStreamWriters}s or
* {@code XMLEventWriters}. Can be overridden in subclasses, adding further initialization of the factory. The
* resulting {@code XMLOutputFactory} is cached, so this method will only be called once.
*
* @return the created {@code XMLOutputFactory}
*/
protected XMLOutputFactory createXmlOutputFactory() {
return XMLOutputFactory.newInstance();
}
}

View File

@@ -48,313 +48,313 @@ import org.springframework.ws.context.MessageContext;
@SuppressWarnings("Since15")
public abstract class AbstractStaxStreamPayloadEndpoint extends AbstractStaxPayloadEndpoint implements MessageEndpoint {
@Override
public final void invoke(MessageContext messageContext) throws Exception {
XMLStreamReader streamReader = getStreamReader(messageContext.getRequest().getPayloadSource());
XMLStreamWriter streamWriter = new ResponseCreatingStreamWriter(messageContext);
invokeInternal(streamReader, streamWriter);
streamWriter.close();
}
@Override
public final void invoke(MessageContext messageContext) throws Exception {
XMLStreamReader streamReader = getStreamReader(messageContext.getRequest().getPayloadSource());
XMLStreamWriter streamWriter = new ResponseCreatingStreamWriter(messageContext);
invokeInternal(streamReader, streamWriter);
streamWriter.close();
}
private XMLStreamReader getStreamReader(Source source) throws XMLStreamException, TransformerException {
if (source == null) {
return null;
}
XMLStreamReader streamReader = null;
if (StaxUtils.isStaxSource(source)) {
streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader == null) {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader != null) {
try {
streamReader = StaxUtils.createEventStreamReader(eventReader);
}
catch (XMLStreamException ex) {
streamReader = null;
}
}
}
private XMLStreamReader getStreamReader(Source source) throws XMLStreamException, TransformerException {
if (source == null) {
return null;
}
XMLStreamReader streamReader = null;
if (StaxUtils.isStaxSource(source)) {
streamReader = StaxUtils.getXMLStreamReader(source);
if (streamReader == null) {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(source);
if (eventReader != null) {
try {
streamReader = StaxUtils.createEventStreamReader(eventReader);
}
catch (XMLStreamException ex) {
streamReader = null;
}
}
}
}
if (streamReader == null) {
try {
streamReader = getInputFactory().createXMLStreamReader(source);
}
catch (XMLStreamException ex) {
streamReader = null;
}
catch (UnsupportedOperationException ex) {
streamReader = null;
}
}
if (streamReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(source, new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
streamReader = getInputFactory().createXMLStreamReader(is);
}
return streamReader;
}
}
if (streamReader == null) {
try {
streamReader = getInputFactory().createXMLStreamReader(source);
}
catch (XMLStreamException ex) {
streamReader = null;
}
catch (UnsupportedOperationException ex) {
streamReader = null;
}
}
if (streamReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayOutputStream os = new ByteArrayOutputStream();
transform(source, new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
streamReader = getInputFactory().createXMLStreamReader(is);
}
return streamReader;
}
private XMLStreamWriter getStreamWriter(Result result) {
XMLStreamWriter streamWriter = null;
if (StaxUtils.isStaxResult(result)) {
streamWriter = StaxUtils.getXMLStreamWriter(result);
}
if (streamWriter == null) {
try {
streamWriter = getOutputFactory().createXMLStreamWriter(result);
}
catch (XMLStreamException ex) {
// ignore
}
}
return streamWriter;
}
private XMLStreamWriter getStreamWriter(Result result) {
XMLStreamWriter streamWriter = null;
if (StaxUtils.isStaxResult(result)) {
streamWriter = StaxUtils.getXMLStreamWriter(result);
}
if (streamWriter == null) {
try {
streamWriter = getOutputFactory().createXMLStreamWriter(result);
}
catch (XMLStreamException ex) {
// ignore
}
}
return streamWriter;
}
/**
* Template method. Subclasses must implement this. Offers the request payload as a {@code XMLStreamReader},
* and a {@code XMLStreamWriter} to write the response payload to.
*
* @param streamReader the reader to read the payload from
* @param streamWriter the writer to write the payload to
*/
protected abstract void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception;
/**
* Template method. Subclasses must implement this. Offers the request payload as a {@code XMLStreamReader},
* and a {@code XMLStreamWriter} to write the response payload to.
*
* @param streamReader the reader to read the payload from
* @param streamWriter the writer to write the payload to
*/
protected abstract void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception;
/**
* Implementation of the {@code XMLStreamWriter} interface that creates a response
* {@code WebServiceMessage} as soon as any method is called, thus lazily creating the response.
*/
private class ResponseCreatingStreamWriter implements XMLStreamWriter {
/**
* Implementation of the {@code XMLStreamWriter} interface that creates a response
* {@code WebServiceMessage} as soon as any method is called, thus lazily creating the response.
*/
private class ResponseCreatingStreamWriter implements XMLStreamWriter {
private MessageContext messageContext;
private MessageContext messageContext;
private XMLStreamWriter streamWriter;
private XMLStreamWriter streamWriter;
private ByteArrayOutputStream os;
private ByteArrayOutputStream os;
private ResponseCreatingStreamWriter(MessageContext messageContext) {
this.messageContext = messageContext;
}
private ResponseCreatingStreamWriter(MessageContext messageContext) {
this.messageContext = messageContext;
}
@Override
public NamespaceContext getNamespaceContext() {
return streamWriter.getNamespaceContext();
}
@Override
public NamespaceContext getNamespaceContext() {
return streamWriter.getNamespaceContext();
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
createStreamWriter();
streamWriter.setNamespaceContext(context);
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
createStreamWriter();
streamWriter.setNamespaceContext(context);
}
@Override
public void close() throws XMLStreamException {
if (streamWriter != null) {
streamWriter.close();
if (os != null) {
streamWriter.flush();
// if we used an output stream cache, we have to transform it to the response again
try {
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
transform(new StreamSource(is), messageContext.getResponse().getPayloadResult());
os = null;
}
catch (TransformerException ex) {
throw new XMLStreamException(ex);
}
}
streamWriter = null;
}
@Override
public void close() throws XMLStreamException {
if (streamWriter != null) {
streamWriter.close();
if (os != null) {
streamWriter.flush();
// if we used an output stream cache, we have to transform it to the response again
try {
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
transform(new StreamSource(is), messageContext.getResponse().getPayloadResult());
os = null;
}
catch (TransformerException ex) {
throw new XMLStreamException(ex);
}
}
streamWriter = null;
}
}
}
@Override
public void flush() throws XMLStreamException {
if (streamWriter != null) {
streamWriter.flush();
}
}
@Override
public void flush() throws XMLStreamException {
if (streamWriter != null) {
streamWriter.flush();
}
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
createStreamWriter();
return streamWriter.getPrefix(uri);
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
createStreamWriter();
return streamWriter.getPrefix(uri);
}
@Override
public Object getProperty(String name) throws IllegalArgumentException {
return streamWriter.getProperty(name);
}
@Override
public Object getProperty(String name) throws IllegalArgumentException {
return streamWriter.getProperty(name);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
createStreamWriter();
streamWriter.setDefaultNamespace(uri);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
createStreamWriter();
streamWriter.setDefaultNamespace(uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
createStreamWriter();
streamWriter.setPrefix(prefix, uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
createStreamWriter();
streamWriter.setPrefix(prefix, uri);
}
@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(localName, value);
}
@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(localName, value);
}
@Override
public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(namespaceURI, localName, value);
}
@Override
public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(namespaceURI, localName, value);
}
@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(prefix, namespaceURI, localName, value);
}
@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
createStreamWriter();
streamWriter.writeAttribute(prefix, namespaceURI, localName, value);
}
@Override
public void writeCData(String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCData(data);
}
@Override
public void writeCData(String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCData(data);
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCharacters(text);
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCharacters(text);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCharacters(text, start, len);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
createStreamWriter();
streamWriter.writeCharacters(text, start, len);
}
@Override
public void writeComment(String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeComment(data);
}
@Override
public void writeComment(String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeComment(data);
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
createStreamWriter();
streamWriter.writeDTD(dtd);
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
createStreamWriter();
streamWriter.writeDTD(dtd);
}
@Override
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeDefaultNamespace(namespaceURI);
}
@Override
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeDefaultNamespace(namespaceURI);
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(localName);
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(localName);
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(namespaceURI, localName);
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(namespaceURI, localName);
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(prefix, localName, namespaceURI);
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEmptyElement(prefix, localName, namespaceURI);
}
@Override
public void writeEndDocument() throws XMLStreamException {
createStreamWriter();
streamWriter.writeEndDocument();
}
@Override
public void writeEndDocument() throws XMLStreamException {
createStreamWriter();
streamWriter.writeEndDocument();
}
@Override
public void writeEndElement() throws XMLStreamException {
createStreamWriter();
streamWriter.writeEndElement();
}
@Override
public void writeEndElement() throws XMLStreamException {
createStreamWriter();
streamWriter.writeEndElement();
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEntityRef(name);
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
createStreamWriter();
streamWriter.writeEntityRef(name);
}
@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeNamespace(prefix, namespaceURI);
}
@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeNamespace(prefix, namespaceURI);
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
createStreamWriter();
streamWriter.writeProcessingInstruction(target);
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
createStreamWriter();
streamWriter.writeProcessingInstruction(target);
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeProcessingInstruction(target, data);
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
createStreamWriter();
streamWriter.writeProcessingInstruction(target, data);
}
@Override
public void writeStartDocument() throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument();
}
@Override
public void writeStartDocument() throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument();
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument(version);
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument(version);
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument(encoding, version);
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartDocument(encoding, version);
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(localName);
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(localName);
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(namespaceURI, localName);
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(namespaceURI, localName);
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(prefix, localName, namespaceURI);
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
createStreamWriter();
streamWriter.writeStartElement(prefix, localName, namespaceURI);
}
private void createStreamWriter() throws XMLStreamException {
if (streamWriter == null) {
WebServiceMessage response = messageContext.getResponse();
streamWriter = getStreamWriter(response.getPayloadResult());
if (streamWriter == null) {
// as a final resort, use a stream, and transform that at endDocument()
os = new ByteArrayOutputStream();
streamWriter = getOutputFactory().createXMLStreamWriter(os);
}
}
}
}
private void createStreamWriter() throws XMLStreamException {
if (streamWriter == null) {
WebServiceMessage response = messageContext.getResponse();
streamWriter = getStreamWriter(response.getPayloadResult());
if (streamWriter == null) {
// as a final resort, use a stream, and transform that at endDocument()
os = new ByteArrayOutputStream();
streamWriter = getOutputFactory().createXMLStreamWriter(os);
}
}
}
}
}

View File

@@ -34,71 +34,71 @@ import org.springframework.ws.context.MessageContext;
@Deprecated
public abstract class AbstractValidatingMarshallingPayloadEndpoint extends AbstractMarshallingPayloadEndpoint {
/** Default request object name used for validating request objects. */
public static final String DEFAULT_REQUEST_NAME = "request";
/** Default request object name used for validating request objects. */
public static final String DEFAULT_REQUEST_NAME = "request";
private String requestName = DEFAULT_REQUEST_NAME;
private String requestName = DEFAULT_REQUEST_NAME;
private Validator[] validators;
private Validator[] validators;
/** Return the name of the request object for validation error codes. */
public String getRequestName() {
return requestName;
}
/** Return the name of the request object for validation error codes. */
public String getRequestName() {
return requestName;
}
/** Set the name of the request object user for validation errors. */
public void setRequestName(String requestName) {
this.requestName = requestName;
}
/** Set the name of the request object user for validation errors. */
public void setRequestName(String requestName) {
this.requestName = requestName;
}
/** Return the primary Validator for this controller. */
public Validator getValidator() {
Validator[] validators = getValidators();
return (validators != null && validators.length > 0 ? validators[0] : null);
}
/** Return the primary Validator for this controller. */
public Validator getValidator() {
Validator[] validators = getValidators();
return (validators != null && validators.length > 0 ? validators[0] : null);
}
/**
* Set the primary {@link Validator} for this endpoint. The {@link Validator} is must support the unmarshalled
* class. If there are one or more existing validators set already when this method is called, only the specified
* validator will be kept. Use {@link #setValidators(Validator[])} to set multiple validators.
*/
public void setValidator(Validator validator) {
this.validators = new Validator[]{validator};
}
/**
* Set the primary {@link Validator} for this endpoint. The {@link Validator} is must support the unmarshalled
* class. If there are one or more existing validators set already when this method is called, only the specified
* validator will be kept. Use {@link #setValidators(Validator[])} to set multiple validators.
*/
public void setValidator(Validator validator) {
this.validators = new Validator[]{validator};
}
/** Return the Validators for this controller. */
public Validator[] getValidators() {
return validators;
}
/** Return the Validators for this controller. */
public Validator[] getValidators() {
return validators;
}
/** Set the Validators for this controller. The Validator must support the specified command class. */
public void setValidators(Validator[] validators) {
this.validators = validators;
}
/** Set the Validators for this controller. The Validator must support the specified command class. */
public void setValidators(Validator[] validators) {
this.validators = validators;
}
@Override
protected boolean onUnmarshalRequest(MessageContext messageContext, Object requestObject) throws Exception {
Validator[] validators = getValidators();
if (validators != null) {
Errors errors = new BindException(requestObject, getRequestName());
for (Validator validator : validators) {
ValidationUtils.invokeValidator(validator, requestObject, errors);
}
if (errors.hasErrors()) {
return onValidationErrors(messageContext, requestObject, errors);
}
}
return true;
}
@Override
protected boolean onUnmarshalRequest(MessageContext messageContext, Object requestObject) throws Exception {
Validator[] validators = getValidators();
if (validators != null) {
Errors errors = new BindException(requestObject, getRequestName());
for (Validator validator : validators) {
ValidationUtils.invokeValidator(validator, requestObject, errors);
}
if (errors.hasErrors()) {
return onValidationErrors(messageContext, requestObject, errors);
}
}
return true;
}
/**
* Callback for post-processing validation errors. Called when validator(s) have been specified, and validation
* fails.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @param errors validation errors holder
* @return {@code true} to continue and call {@link #invokeInternal(Object)}; {@code false} otherwise
*/
protected abstract boolean onValidationErrors(MessageContext messageContext, Object requestObject, Errors errors);
/**
* Callback for post-processing validation errors. Called when validator(s) have been specified, and validation
* fails.
*
* @param messageContext the message context
* @param requestObject the object unmarshalled from the {@link MessageContext#getRequest() request}
* @param errors validation errors holder
* @return {@code true} to continue and call {@link #invokeInternal(Object)}; {@code false} otherwise
*/
protected abstract boolean onValidationErrors(MessageContext messageContext, Object requestObject, Errors errors);
}

View File

@@ -66,273 +66,273 @@ import org.springframework.xml.transform.TraxUtils;
@SuppressWarnings("Since15")
public abstract class AbstractXomPayloadEndpoint extends TransformerObjectSupport implements PayloadEndpoint {
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = null;
if (request != null) {
XomSourceCallback sourceCallback = new XomSourceCallback();
try {
TraxUtils.doWithSource(request, sourceCallback);
}
catch (XomParsingException ex) {
throw (ParsingException) ex.getCause();
}
requestElement = sourceCallback.element;
}
Element responseElement = invokeInternal(requestElement);
return responseElement != null ? convertResponse(responseElement) : null;
}
@Override
public final Source invoke(Source request) throws Exception {
Element requestElement = null;
if (request != null) {
XomSourceCallback sourceCallback = new XomSourceCallback();
try {
TraxUtils.doWithSource(request, sourceCallback);
}
catch (XomParsingException ex) {
throw (ParsingException) ex.getCause();
}
requestElement = sourceCallback.element;
}
Element responseElement = invokeInternal(requestElement);
return responseElement != null ? convertResponse(responseElement) : null;
}
private Source convertResponse(Element responseElement) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Serializer serializer = createSerializer(os);
Document document = responseElement.getDocument();
if (document == null) {
document = new Document(responseElement);
}
serializer.write(document);
byte[] bytes = os.toByteArray();
return new StreamSource(new ByteArrayInputStream(bytes));
}
private Source convertResponse(Element responseElement) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Serializer serializer = createSerializer(os);
Document document = responseElement.getDocument();
if (document == null) {
document = new Document(responseElement);
}
serializer.write(document);
byte[] bytes = os.toByteArray();
return new StreamSource(new ByteArrayInputStream(bytes));
}
/**
* Creates a {@link Serializer} to be used for writing the response to.
*
* <p>Default implementation uses the UTF-8 encoding and does not set any options, but this may be changed in
* subclasses.
*
* @param outputStream the output stream to serialize to
* @return the serializer
*/
protected Serializer createSerializer(OutputStream outputStream) {
return new Serializer(outputStream);
}
/**
* Creates a {@link Serializer} to be used for writing the response to.
*
* <p>Default implementation uses the UTF-8 encoding and does not set any options, but this may be changed in
* subclasses.
*
* @param outputStream the output stream to serialize to
* @return the serializer
*/
protected Serializer createSerializer(OutputStream outputStream) {
return new Serializer(outputStream);
}
/**
* Template method. Subclasses must implement this. Offers the request payload as a XOM {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* @param requestElement the contents of the SOAP message as XOM element
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement) throws Exception;
/**
* Template method. Subclasses must implement this. Offers the request payload as a XOM {@code Element}, and
* allows subclasses to return a response {@code Element}.
*
* @param requestElement the contents of the SOAP message as XOM element
* @return the response element. Can be {@code null} to specify no response.
*/
protected abstract Element invokeInternal(Element requestElement) throws Exception;
private static class XomSourceCallback implements TraxUtils.SourceCallback {
private static class XomSourceCallback implements TraxUtils.SourceCallback {
private Element element;
private Element element;
@Override
public void domSource(Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
element = DOMConverter.convert((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = DOMConverter.convert((org.w3c.dom.Document) node);
element = document.getRootElement();
}
else {
throw new IllegalArgumentException("DOMSource contains neither Document nor Element");
}
}
@Override
public void domSource(Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
element = DOMConverter.convert((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = DOMConverter.convert((org.w3c.dom.Document) node);
element = document.getRootElement();
}
else {
throw new IllegalArgumentException("DOMSource contains neither Document nor Element");
}
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws IOException, SAXException {
try {
Builder builder = new Builder(reader);
Document document;
if (inputSource.getByteStream() != null) {
document = builder.build(inputSource.getByteStream());
}
else if (inputSource.getCharacterStream() != null) {
document = builder.build(inputSource.getCharacterStream());
}
else {
throw new IllegalArgumentException(
"InputSource in SAXSource contains neither byte stream nor character stream");
}
element = document.getRootElement();
}
catch (ValidityException ex) {
throw new XomParsingException(ex);
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws IOException, SAXException {
try {
Builder builder = new Builder(reader);
Document document;
if (inputSource.getByteStream() != null) {
document = builder.build(inputSource.getByteStream());
}
else if (inputSource.getCharacterStream() != null) {
document = builder.build(inputSource.getCharacterStream());
}
else {
throw new IllegalArgumentException(
"InputSource in SAXSource contains neither byte stream nor character stream");
}
element = document.getRootElement();
}
catch (ValidityException ex) {
throw new XomParsingException(ex);
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void staxSource(XMLEventReader eventReader) throws XMLStreamException {
throw new IllegalArgumentException("XMLEventReader not supported");
}
@Override
public void staxSource(XMLEventReader eventReader) throws XMLStreamException {
throw new IllegalArgumentException("XMLEventReader not supported");
}
@Override
public void staxSource(XMLStreamReader streamReader) throws XMLStreamException {
Document document = StaxStreamConverter.convert(streamReader);
element = document.getRootElement();
}
@Override
public void staxSource(XMLStreamReader streamReader) throws XMLStreamException {
Document document = StaxStreamConverter.convert(streamReader);
element = document.getRootElement();
}
@Override
public void streamSource(InputStream inputStream) throws IOException {
try {
Builder builder = new Builder();
Document document = builder.build(inputStream);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void streamSource(InputStream inputStream) throws IOException {
try {
Builder builder = new Builder();
Document document = builder.build(inputStream);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void streamSource(Reader reader) throws IOException {
try {
Builder builder = new Builder();
Document document = builder.build(reader);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void streamSource(Reader reader) throws IOException {
try {
Builder builder = new Builder();
Document document = builder.build(reader);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
@Override
public void source(String systemId) throws Exception {
try {
Builder builder = new Builder();
Document document = builder.build(systemId);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
}
@Override
public void source(String systemId) throws Exception {
try {
Builder builder = new Builder();
Document document = builder.build(systemId);
element = document.getRootElement();
}
catch (ParsingException ex) {
throw new XomParsingException(ex);
}
}
}
@SuppressWarnings("serial")
private static class XomParsingException extends NestedRuntimeException {
private static class XomParsingException extends NestedRuntimeException {
private XomParsingException(ParsingException ex) {
super(ex.getMessage(), ex);
}
}
private XomParsingException(ParsingException ex) {
super(ex.getMessage(), ex);
}
}
private static class StaxStreamConverter {
private static class StaxStreamConverter {
private static Document convert(XMLStreamReader streamReader) throws XMLStreamException {
NodeFactory nodeFactory = new NodeFactory();
Document document = null;
Element element = null;
ParentNode parent = null;
boolean documentFinished = false;
while (streamReader.hasNext()) {
int event = streamReader.next();
switch (event) {
case XMLStreamConstants.START_DOCUMENT:
document = nodeFactory.startMakingDocument();
parent = document;
break;
case XMLStreamConstants.END_DOCUMENT:
nodeFactory.finishMakingDocument(document);
documentFinished = true;
break;
case XMLStreamConstants.START_ELEMENT:
if (document == null) {
document = nodeFactory.startMakingDocument();
parent = document;
}
String name = QNameUtils.toQualifiedName(streamReader.getName());
if (element == null) {
element = nodeFactory.makeRootElement(name, streamReader.getNamespaceURI());
document.setRootElement(element);
}
else {
element = nodeFactory.startMakingElement(name, streamReader.getNamespaceURI());
parent.appendChild(element);
}
convertNamespaces(streamReader, element);
convertAttributes(streamReader, nodeFactory);
parent = element;
break;
case XMLStreamConstants.END_ELEMENT:
nodeFactory.finishMakingElement(element);
parent = parent.getParent();
break;
case XMLStreamConstants.ATTRIBUTE:
convertAttributes(streamReader, nodeFactory);
break;
case XMLStreamConstants.CHARACTERS:
nodeFactory.makeText(streamReader.getText());
break;
case XMLStreamConstants.COMMENT:
nodeFactory.makeComment(streamReader.getText());
break;
default:
break;
}
}
if (!documentFinished) {
nodeFactory.finishMakingDocument(document);
}
return document;
}
private static Document convert(XMLStreamReader streamReader) throws XMLStreamException {
NodeFactory nodeFactory = new NodeFactory();
Document document = null;
Element element = null;
ParentNode parent = null;
boolean documentFinished = false;
while (streamReader.hasNext()) {
int event = streamReader.next();
switch (event) {
case XMLStreamConstants.START_DOCUMENT:
document = nodeFactory.startMakingDocument();
parent = document;
break;
case XMLStreamConstants.END_DOCUMENT:
nodeFactory.finishMakingDocument(document);
documentFinished = true;
break;
case XMLStreamConstants.START_ELEMENT:
if (document == null) {
document = nodeFactory.startMakingDocument();
parent = document;
}
String name = QNameUtils.toQualifiedName(streamReader.getName());
if (element == null) {
element = nodeFactory.makeRootElement(name, streamReader.getNamespaceURI());
document.setRootElement(element);
}
else {
element = nodeFactory.startMakingElement(name, streamReader.getNamespaceURI());
parent.appendChild(element);
}
convertNamespaces(streamReader, element);
convertAttributes(streamReader, nodeFactory);
parent = element;
break;
case XMLStreamConstants.END_ELEMENT:
nodeFactory.finishMakingElement(element);
parent = parent.getParent();
break;
case XMLStreamConstants.ATTRIBUTE:
convertAttributes(streamReader, nodeFactory);
break;
case XMLStreamConstants.CHARACTERS:
nodeFactory.makeText(streamReader.getText());
break;
case XMLStreamConstants.COMMENT:
nodeFactory.makeComment(streamReader.getText());
break;
default:
break;
}
}
if (!documentFinished) {
nodeFactory.finishMakingDocument(document);
}
return document;
}
private static void convertNamespaces(XMLStreamReader streamReader, Element element) {
for (int i = 0; i < streamReader.getNamespaceCount(); i++) {
String uri = streamReader.getNamespaceURI(i);
String prefix = streamReader.getNamespacePrefix(i);
private static void convertNamespaces(XMLStreamReader streamReader, Element element) {
for (int i = 0; i < streamReader.getNamespaceCount(); i++) {
String uri = streamReader.getNamespaceURI(i);
String prefix = streamReader.getNamespacePrefix(i);
element.addNamespaceDeclaration(prefix, uri);
}
element.addNamespaceDeclaration(prefix, uri);
}
}
}
private static void convertAttributes(XMLStreamReader streamReader, NodeFactory nodeFactory) {
for (int i = 0; i < streamReader.getAttributeCount(); i++) {
String name = QNameUtils.toQualifiedName(streamReader.getAttributeName(i));
String uri = streamReader.getAttributeNamespace(i);
String value = streamReader.getAttributeValue(i);
Attribute.Type type = convertAttributeType(streamReader.getAttributeType(i));
private static void convertAttributes(XMLStreamReader streamReader, NodeFactory nodeFactory) {
for (int i = 0; i < streamReader.getAttributeCount(); i++) {
String name = QNameUtils.toQualifiedName(streamReader.getAttributeName(i));
String uri = streamReader.getAttributeNamespace(i);
String value = streamReader.getAttributeValue(i);
Attribute.Type type = convertAttributeType(streamReader.getAttributeType(i));
nodeFactory.makeAttribute(name, uri, value, type);
}
}
nodeFactory.makeAttribute(name, uri, value, type);
}
}
private static Attribute.Type convertAttributeType(String type) {
type = type.toUpperCase(Locale.ENGLISH);
if ("CDATA".equals(type)) {
return Attribute.Type.CDATA;
}
else if ("ENTITIES".equals(type)) {
return Attribute.Type.ENTITIES;
}
else if ("ENTITY".equals(type)) {
return Attribute.Type.ENTITY;
}
else if ("ENUMERATION".equals(type)) {
return Attribute.Type.ENUMERATION;
}
else if ("ID".equals(type)) {
return Attribute.Type.ID;
}
else if ("IDREF".equals(type)) {
return Attribute.Type.IDREF;
}
else if ("IDREFS".equals(type)) {
return Attribute.Type.IDREFS;
}
else if ("NMTOKEN".equals(type)) {
return Attribute.Type.NMTOKEN;
}
else if ("NMTOKENS".equals(type)) {
return Attribute.Type.NMTOKENS;
}
else if ("NOTATION".equals(type)) {
return Attribute.Type.NOTATION;
}
else {
return Attribute.Type.UNDECLARED;
}
}
private static Attribute.Type convertAttributeType(String type) {
type = type.toUpperCase(Locale.ENGLISH);
if ("CDATA".equals(type)) {
return Attribute.Type.CDATA;
}
else if ("ENTITIES".equals(type)) {
return Attribute.Type.ENTITIES;
}
else if ("ENTITY".equals(type)) {
return Attribute.Type.ENTITY;
}
else if ("ENUMERATION".equals(type)) {
return Attribute.Type.ENUMERATION;
}
else if ("ID".equals(type)) {
return Attribute.Type.ID;
}
else if ("IDREF".equals(type)) {
return Attribute.Type.IDREF;
}
else if ("IDREFS".equals(type)) {
return Attribute.Type.IDREFS;
}
else if ("NMTOKEN".equals(type)) {
return Attribute.Type.NMTOKEN;
}
else if ("NMTOKENS".equals(type)) {
return Attribute.Type.NMTOKENS;
}
else if ("NOTATION".equals(type)) {
return Attribute.Type.NOTATION;
}
else {
return Attribute.Type.UNDECLARED;
}
}
}
}
}

View File

@@ -30,13 +30,13 @@ import org.springframework.ws.context.MessageContext;
*/
public interface MessageEndpoint {
/**
* Invokes an operation.
*
* <p>The given {@code messageContext} can be used to create a response.
*
* @param messageContext the message context
* @throws Exception if an exception occurs
*/
void invoke(MessageContext messageContext) throws Exception;
/**
* Invokes an operation.
*
* <p>The given {@code messageContext} can be used to create a response.
*
* @param messageContext the message context
* @throws Exception if an exception occurs
*/
void invoke(MessageContext messageContext) throws Exception;
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -34,144 +34,144 @@ import org.springframework.util.ReflectionUtils;
*/
public final class MethodEndpoint {
private final Object bean;
private final Object bean;
private final Method method;
private final Method method;
private final BeanFactory beanFactory;
private final BeanFactory beanFactory;
/**
* Constructs a new method endpoint with the given bean and method.
*
* @param bean the object bean
* @param method the method
*/
public MethodEndpoint(Object bean, Method method) {
Assert.notNull(bean, "bean must not be null");
Assert.notNull(method, "method must not be null");
this.bean = bean;
this.method = method;
this.beanFactory = null;
}
/**
* Constructs a new method endpoint with the given bean and method.
*
* @param bean the object bean
* @param method the method
*/
public MethodEndpoint(Object bean, Method method) {
Assert.notNull(bean, "bean must not be null");
Assert.notNull(method, "method must not be null");
this.bean = bean;
this.method = method;
this.beanFactory = null;
}
/**
* Constructs a new method endpoint with the given bean, method name and parameters.
*
* @param bean the object bean
* @param methodName the method name
* @param parameterTypes the method parameter types
* @throws NoSuchMethodException when the method cannot be found
*/
public MethodEndpoint(Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
Assert.notNull(bean, "bean must not be null");
Assert.notNull(methodName, "method must not be null");
this.bean = bean;
this.method = bean.getClass().getMethod(methodName, parameterTypes);
this.beanFactory = null;
}
/**
* Constructs a new method endpoint with the given bean, method name and parameters.
*
* @param bean the object bean
* @param methodName the method name
* @param parameterTypes the method parameter types
* @throws NoSuchMethodException when the method cannot be found
*/
public MethodEndpoint(Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
Assert.notNull(bean, "bean must not be null");
Assert.notNull(methodName, "method must not be null");
this.bean = bean;
this.method = bean.getClass().getMethod(methodName, parameterTypes);
this.beanFactory = null;
}
/**
* Constructs a new method endpoint with the given bean name and method. The bean name will be lazily initialized when
* {@link #invoke(Object...)} is called.
*
* @param beanName the bean name
* @param beanFactory the bean factory to use for bean initialization
* @param method the method
*/
public MethodEndpoint(String beanName, BeanFactory beanFactory, Method method) {
Assert.hasText(beanName, "'beanName' must not be null");
Assert.notNull(beanFactory, "'beanFactory' must not be null");
Assert.notNull(method, "'method' must not be null");
Assert.isTrue(beanFactory.containsBean(beanName),
"Bean factory [" + beanFactory + "] does not contain bean " + "with name [" + beanName + "]");
this.bean = beanName;
this.beanFactory = beanFactory;
this.method = method;
}
/**
* Constructs a new method endpoint with the given bean name and method. The bean name will be lazily initialized when
* {@link #invoke(Object...)} is called.
*
* @param beanName the bean name
* @param beanFactory the bean factory to use for bean initialization
* @param method the method
*/
public MethodEndpoint(String beanName, BeanFactory beanFactory, Method method) {
Assert.hasText(beanName, "'beanName' must not be null");
Assert.notNull(beanFactory, "'beanFactory' must not be null");
Assert.notNull(method, "'method' must not be null");
Assert.isTrue(beanFactory.containsBean(beanName),
"Bean factory [" + beanFactory + "] does not contain bean " + "with name [" + beanName + "]");
this.bean = beanName;
this.beanFactory = beanFactory;
this.method = method;
}
/** Returns the object bean for this method endpoint. */
public Object getBean() {
if (beanFactory != null && bean instanceof String) {
String beanName = (String) bean;
return beanFactory.getBean(beanName);
}
else {
return bean;
}
}
/** Returns the object bean for this method endpoint. */
public Object getBean() {
if (beanFactory != null && bean instanceof String) {
String beanName = (String) bean;
return beanFactory.getBean(beanName);
}
else {
return bean;
}
}
/** Returns the method for this method endpoint. */
public Method getMethod() {
return this.method;
}
/** Returns the method for this method endpoint. */
public Method getMethod() {
return this.method;
}
/** Returns the method parameters for this method endpoint. */
public MethodParameter[] getMethodParameters() {
int parameterCount = getMethod().getParameterTypes().length;
MethodParameter[] parameters = new MethodParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
parameters[i] = new MethodParameter(getMethod(), i);
}
return parameters;
}
/** Returns the method parameters for this method endpoint. */
public MethodParameter[] getMethodParameters() {
int parameterCount = getMethod().getParameterTypes().length;
MethodParameter[] parameters = new MethodParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
parameters[i] = new MethodParameter(getMethod(), i);
}
return parameters;
}
/** Returns the method return type, as {@code MethodParameter}. */
public MethodParameter getReturnType() {
return new MethodParameter(method, -1);
}
/** Returns the method return type, as {@code MethodParameter}. */
public MethodParameter getReturnType() {
return new MethodParameter(method, -1);
}
/**
* Invokes this method endpoint with the given arguments.
*
* @param args the arguments
* @return the invocation result
* @throws Exception when the method invocation results in an exception
*/
public Object invoke(Object... args) throws Exception {
Object endpoint = getBean();
ReflectionUtils.makeAccessible(method);
try {
return method.invoke(endpoint, args);
}
catch (InvocationTargetException ex) {
handleInvocationTargetException(ex);
throw new IllegalStateException(
"Unexpected exception thrown by method - " + ex.getTargetException().getClass().getName() + ": " +
ex.getTargetException().getMessage());
}
}
/**
* Invokes this method endpoint with the given arguments.
*
* @param args the arguments
* @return the invocation result
* @throws Exception when the method invocation results in an exception
*/
public Object invoke(Object... args) throws Exception {
Object endpoint = getBean();
ReflectionUtils.makeAccessible(method);
try {
return method.invoke(endpoint, args);
}
catch (InvocationTargetException ex) {
handleInvocationTargetException(ex);
throw new IllegalStateException(
"Unexpected exception thrown by method - " + ex.getTargetException().getClass().getName() + ": " +
ex.getTargetException().getMessage());
}
}
private void handleInvocationTargetException(InvocationTargetException ex) throws Exception {
Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
if (targetException instanceof Error) {
throw (Error) targetException;
}
if (targetException instanceof Exception) {
throw (Exception) targetException;
}
private void handleInvocationTargetException(InvocationTargetException ex) throws Exception {
Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
if (targetException instanceof Error) {
throw (Error) targetException;
}
if (targetException instanceof Exception) {
throw (Exception) targetException;
}
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof MethodEndpoint) {
MethodEndpoint other = (MethodEndpoint) o;
return this.bean.equals(other.bean) && this.method.equals(other.method);
}
return false;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof MethodEndpoint) {
MethodEndpoint other = (MethodEndpoint) o;
return this.bean.equals(other.bean) && this.method.equals(other.method);
}
return false;
}
public int hashCode() {
return 31 * this.bean.hashCode() + this.method.hashCode();
}
public int hashCode() {
return 31 * this.bean.hashCode() + this.method.hashCode();
}
public String toString() {
return method.toGenericString();
}
public String toString() {
return method.toGenericString();
}
}

View File

@@ -28,12 +28,12 @@ import javax.xml.transform.Source;
*/
public interface PayloadEndpoint {
/**
* Invokes the endpoint with the given request payload, and possibly returns a response.
*
* @param request the payload of the request message, may be {@code null}
* @return the payload of the response message, may be {@code null} to indicate no response
* @throws Exception if an exception occurs
*/
Source invoke(Source request) throws Exception;
/**
* Invokes the endpoint with the given request payload, and possibly returns a response.
*
* @param request the payload of the request message, may be {@code null}
* @return the payload of the response message, may be {@code null} to indicate no response
* @throws Exception if an exception occurs
*/
Source invoke(Source request) throws Exception;
}

View File

@@ -30,47 +30,47 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public abstract class AbstractMethodEndpointAdapter extends TransformerObjectSupport implements EndpointAdapter {
/**
* Delegates to {@link #supportsInternal(org.springframework.ws.server.endpoint.MethodEndpoint)}.
*
* @param endpoint endpoint object to check
* @return whether or not this adapter can adapt the given endpoint
*/
@Override
public final boolean supports(Object endpoint) {
return endpoint instanceof MethodEndpoint && supportsInternal((MethodEndpoint) endpoint);
}
/**
* Delegates to {@link #supportsInternal(org.springframework.ws.server.endpoint.MethodEndpoint)}.
*
* @param endpoint endpoint object to check
* @return whether or not this adapter can adapt the given endpoint
*/
@Override
public final boolean supports(Object endpoint) {
return endpoint instanceof MethodEndpoint && supportsInternal((MethodEndpoint) endpoint);
}
/**
* Delegates to {@link #invokeInternal(org.springframework.ws.context.MessageContext,MethodEndpoint)}.
*
* @param messageContext the current message context
* @param endpoint the endpoint to use. This object must have previously been passed to the
* {@code supportsInternal} method of this interface, which must have returned
* {@code true}
* @throws Exception in case of errors
*/
@Override
public final void invoke(MessageContext messageContext, Object endpoint) throws Exception {
invokeInternal(messageContext, (MethodEndpoint) endpoint);
}
/**
* Delegates to {@link #invokeInternal(org.springframework.ws.context.MessageContext,MethodEndpoint)}.
*
* @param messageContext the current message context
* @param endpoint the endpoint to use. This object must have previously been passed to the
* {@code supportsInternal} method of this interface, which must have returned
* {@code true}
* @throws Exception in case of errors
*/
@Override
public final void invoke(MessageContext messageContext, Object endpoint) throws Exception {
invokeInternal(messageContext, (MethodEndpoint) endpoint);
}
/**
* Given a method endpoint, return whether or not this adapter can support it.
*
* @param methodEndpoint method endpoint to check
* @return whether or not this adapter can adapt the given method
*/
protected abstract boolean supportsInternal(MethodEndpoint methodEndpoint);
/**
* Given a method endpoint, return whether or not this adapter can support it.
*
* @param methodEndpoint method endpoint to check
* @return whether or not this adapter can adapt the given method
*/
protected abstract boolean supportsInternal(MethodEndpoint methodEndpoint);
/**
* Use the given method endpoint to handle the request.
*
* @param messageContext the current message context
* @param methodEndpoint the method endpoint to use
* @throws Exception in case of errors
*/
protected abstract void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint)
throws Exception;
/**
* Use the given method endpoint to handle the request.
*
* @param messageContext the current message context
* @param methodEndpoint the method endpoint to use
* @throws Exception in case of errors
*/
protected abstract void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint)
throws Exception;
}

View File

@@ -49,47 +49,47 @@ import org.springframework.ws.server.endpoint.adapter.method.jaxb.XmlRootElement
* @since 2.0
*/
public class DefaultMethodEndpointAdapter extends AbstractMethodEndpointAdapter
implements BeanClassLoaderAware, InitializingBean {
implements BeanClassLoaderAware, InitializingBean {
private static final String DOM4J_CLASS_NAME = "org.dom4j.Element";
private static final String DOM4J_CLASS_NAME = "org.dom4j.Element";
private static final String JAXB2_CLASS_NAME = "javax.xml.bind.Binder";
private static final String JAXB2_CLASS_NAME = "javax.xml.bind.Binder";
private static final String JDOM_CLASS_NAME = "org.jdom2.Element";
private static final String JDOM_CLASS_NAME = "org.jdom2.Element";
private static final String STAX_CLASS_NAME = "javax.xml.stream.XMLInputFactory";
private static final String STAX_CLASS_NAME = "javax.xml.stream.XMLInputFactory";
private static final String XOM_CLASS_NAME = "nu.xom.Element";
private static final String XOM_CLASS_NAME = "nu.xom.Element";
private static final String SOAP_METHOD_ARGUMENT_RESOLVER_CLASS_NAME =
"org.springframework.ws.soap.server.endpoint.adapter.method.SoapMethodArgumentResolver";
private static final String SOAP_METHOD_ARGUMENT_RESOLVER_CLASS_NAME =
"org.springframework.ws.soap.server.endpoint.adapter.method.SoapMethodArgumentResolver";
private static final String SOAP_HEADER_ELEMENT_ARGUMENT_RESOLVER_CLASS_NAME =
"org.springframework.ws.soap.server.endpoint.adapter.method.SoapHeaderElementMethodArgumentResolver";
private static final String SOAP_HEADER_ELEMENT_ARGUMENT_RESOLVER_CLASS_NAME =
"org.springframework.ws.soap.server.endpoint.adapter.method.SoapHeaderElementMethodArgumentResolver";
private List<MethodArgumentResolver> methodArgumentResolvers;
private List<MethodArgumentResolver> methodArgumentResolvers;
private List<MethodArgumentResolver> customMethodArgumentResolvers;
private List<MethodReturnValueHandler> methodReturnValueHandlers;
private List<MethodReturnValueHandler> methodReturnValueHandlers;
private List<MethodReturnValueHandler> customMethodReturnValueHandlers;
private List<MethodReturnValueHandler> customMethodReturnValueHandlers;
private ClassLoader classLoader;
private ClassLoader classLoader;
/**
* Returns the list of {@code MethodArgumentResolver}s to use.
*/
public List<MethodArgumentResolver> getMethodArgumentResolvers() {
return methodArgumentResolvers;
}
return methodArgumentResolvers;
}
/**
* Sets the list of {@code MethodArgumentResolver}s to use.
*/
public void setMethodArgumentResolvers(List<MethodArgumentResolver> methodArgumentResolvers) {
this.methodArgumentResolvers = methodArgumentResolvers;
}
this.methodArgumentResolvers = methodArgumentResolvers;
}
/**
* Returns the custom argument resolvers.
@@ -112,15 +112,15 @@ public class DefaultMethodEndpointAdapter extends AbstractMethodEndpointAdapter
* Returns the list of {@code MethodReturnValueHandler}s to use.
*/
public List<MethodReturnValueHandler> getMethodReturnValueHandlers() {
return methodReturnValueHandlers;
}
return methodReturnValueHandlers;
}
/**
* Sets the list of {@code MethodReturnValueHandler}s to use.
*/
public void setMethodReturnValueHandlers(List<MethodReturnValueHandler> methodReturnValueHandlers) {
this.methodReturnValueHandlers = methodReturnValueHandlers;
}
this.methodReturnValueHandlers = methodReturnValueHandlers;
}
/**
* Returns the custom return value handlers.
@@ -140,214 +140,214 @@ public class DefaultMethodEndpointAdapter extends AbstractMethodEndpointAdapter
}
private ClassLoader getClassLoader() {
return this.classLoader != null ? this.classLoader : DefaultMethodEndpointAdapter.class.getClassLoader();
}
return this.classLoader != null ? this.classLoader : DefaultMethodEndpointAdapter.class.getClassLoader();
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void afterPropertiesSet() throws Exception {
initDefaultStrategies();
}
@Override
public void afterPropertiesSet() throws Exception {
initDefaultStrategies();
}
/** Initialize the default implementations for the adapter's strategies. */
protected void initDefaultStrategies() {
initMethodArgumentResolvers();
initMethodReturnValueHandlers();
}
/** Initialize the default implementations for the adapter's strategies. */
protected void initDefaultStrategies() {
initMethodArgumentResolvers();
initMethodReturnValueHandlers();
}
private void initMethodArgumentResolvers() {
if (CollectionUtils.isEmpty(methodArgumentResolvers)) {
List<MethodArgumentResolver> methodArgumentResolvers = new ArrayList<MethodArgumentResolver>();
methodArgumentResolvers.add(new DomPayloadMethodProcessor());
methodArgumentResolvers.add(new MessageContextMethodArgumentResolver());
methodArgumentResolvers.add(new SourcePayloadMethodProcessor());
methodArgumentResolvers.add(new XPathParamMethodArgumentResolver());
addMethodArgumentResolver(SOAP_METHOD_ARGUMENT_RESOLVER_CLASS_NAME, methodArgumentResolvers);
addMethodArgumentResolver(SOAP_HEADER_ELEMENT_ARGUMENT_RESOLVER_CLASS_NAME, methodArgumentResolvers);
if (isPresent(DOM4J_CLASS_NAME)) {
methodArgumentResolvers.add(new Dom4jPayloadMethodProcessor());
}
if (isPresent(JAXB2_CLASS_NAME)) {
methodArgumentResolvers.add(new XmlRootElementPayloadMethodProcessor());
methodArgumentResolvers.add(new JaxbElementPayloadMethodProcessor());
}
if (isPresent(JDOM_CLASS_NAME)) {
methodArgumentResolvers.add(new JDomPayloadMethodProcessor());
}
if (isPresent(STAX_CLASS_NAME)) {
methodArgumentResolvers.add(new StaxPayloadMethodArgumentResolver());
}
if (isPresent(XOM_CLASS_NAME)) {
methodArgumentResolvers.add(new XomPayloadMethodProcessor());
}
if (logger.isDebugEnabled()) {
logger.debug("No MethodArgumentResolvers set, using defaults: " + methodArgumentResolvers);
}
if (getCustomMethodArgumentResolvers() != null) {
methodArgumentResolvers.addAll(getCustomMethodArgumentResolvers());
}
setMethodArgumentResolvers(methodArgumentResolvers);
}
}
private void initMethodArgumentResolvers() {
if (CollectionUtils.isEmpty(methodArgumentResolvers)) {
List<MethodArgumentResolver> methodArgumentResolvers = new ArrayList<MethodArgumentResolver>();
methodArgumentResolvers.add(new DomPayloadMethodProcessor());
methodArgumentResolvers.add(new MessageContextMethodArgumentResolver());
methodArgumentResolvers.add(new SourcePayloadMethodProcessor());
methodArgumentResolvers.add(new XPathParamMethodArgumentResolver());
addMethodArgumentResolver(SOAP_METHOD_ARGUMENT_RESOLVER_CLASS_NAME, methodArgumentResolvers);
addMethodArgumentResolver(SOAP_HEADER_ELEMENT_ARGUMENT_RESOLVER_CLASS_NAME, methodArgumentResolvers);
if (isPresent(DOM4J_CLASS_NAME)) {
methodArgumentResolvers.add(new Dom4jPayloadMethodProcessor());
}
if (isPresent(JAXB2_CLASS_NAME)) {
methodArgumentResolvers.add(new XmlRootElementPayloadMethodProcessor());
methodArgumentResolvers.add(new JaxbElementPayloadMethodProcessor());
}
if (isPresent(JDOM_CLASS_NAME)) {
methodArgumentResolvers.add(new JDomPayloadMethodProcessor());
}
if (isPresent(STAX_CLASS_NAME)) {
methodArgumentResolvers.add(new StaxPayloadMethodArgumentResolver());
}
if (isPresent(XOM_CLASS_NAME)) {
methodArgumentResolvers.add(new XomPayloadMethodProcessor());
}
if (logger.isDebugEnabled()) {
logger.debug("No MethodArgumentResolvers set, using defaults: " + methodArgumentResolvers);
}
if (getCustomMethodArgumentResolvers() != null) {
methodArgumentResolvers.addAll(getCustomMethodArgumentResolvers());
}
setMethodArgumentResolvers(methodArgumentResolvers);
}
}
/**
* Certain (SOAP-specific) {@code MethodArgumentResolver}s have to be instantiated by class name, in order to not
* introduce a cyclic dependency.
*/
@SuppressWarnings("unchecked")
private void addMethodArgumentResolver(String className, List<MethodArgumentResolver> methodArgumentResolvers) {
try {
Class<MethodArgumentResolver> methodArgumentResolverClass =
(Class<MethodArgumentResolver>) ClassUtils.forName(className, getClassLoader());
methodArgumentResolvers.add(BeanUtils.instantiate(methodArgumentResolverClass));
}
catch (ClassNotFoundException e) {
logger.warn("Could not find \"" + className + "\" on the classpath");
}
}
/**
* Certain (SOAP-specific) {@code MethodArgumentResolver}s have to be instantiated by class name, in order to not
* introduce a cyclic dependency.
*/
@SuppressWarnings("unchecked")
private void addMethodArgumentResolver(String className, List<MethodArgumentResolver> methodArgumentResolvers) {
try {
Class<MethodArgumentResolver> methodArgumentResolverClass =
(Class<MethodArgumentResolver>) ClassUtils.forName(className, getClassLoader());
methodArgumentResolvers.add(BeanUtils.instantiate(methodArgumentResolverClass));
}
catch (ClassNotFoundException e) {
logger.warn("Could not find \"" + className + "\" on the classpath");
}
}
private void initMethodReturnValueHandlers() {
if (CollectionUtils.isEmpty(methodReturnValueHandlers)) {
List<MethodReturnValueHandler> methodReturnValueHandlers = new ArrayList<MethodReturnValueHandler>();
methodReturnValueHandlers.add(new DomPayloadMethodProcessor());
methodReturnValueHandlers.add(new SourcePayloadMethodProcessor());
if (isPresent(DOM4J_CLASS_NAME)) {
methodReturnValueHandlers.add(new Dom4jPayloadMethodProcessor());
}
if (isPresent(JAXB2_CLASS_NAME)) {
methodReturnValueHandlers.add(new XmlRootElementPayloadMethodProcessor());
methodReturnValueHandlers.add(new JaxbElementPayloadMethodProcessor());
}
if (isPresent(JDOM_CLASS_NAME)) {
methodReturnValueHandlers.add(new JDomPayloadMethodProcessor());
}
if (isPresent(XOM_CLASS_NAME)) {
methodReturnValueHandlers.add(new XomPayloadMethodProcessor());
}
if (logger.isDebugEnabled()) {
logger.debug("No MethodReturnValueHandlers set, using defaults: " + methodReturnValueHandlers);
}
if (getCustomMethodReturnValueHandlers() != null) {
methodReturnValueHandlers.addAll(getCustomMethodReturnValueHandlers());
}
setMethodReturnValueHandlers(methodReturnValueHandlers);
}
}
private void initMethodReturnValueHandlers() {
if (CollectionUtils.isEmpty(methodReturnValueHandlers)) {
List<MethodReturnValueHandler> methodReturnValueHandlers = new ArrayList<MethodReturnValueHandler>();
methodReturnValueHandlers.add(new DomPayloadMethodProcessor());
methodReturnValueHandlers.add(new SourcePayloadMethodProcessor());
if (isPresent(DOM4J_CLASS_NAME)) {
methodReturnValueHandlers.add(new Dom4jPayloadMethodProcessor());
}
if (isPresent(JAXB2_CLASS_NAME)) {
methodReturnValueHandlers.add(new XmlRootElementPayloadMethodProcessor());
methodReturnValueHandlers.add(new JaxbElementPayloadMethodProcessor());
}
if (isPresent(JDOM_CLASS_NAME)) {
methodReturnValueHandlers.add(new JDomPayloadMethodProcessor());
}
if (isPresent(XOM_CLASS_NAME)) {
methodReturnValueHandlers.add(new XomPayloadMethodProcessor());
}
if (logger.isDebugEnabled()) {
logger.debug("No MethodReturnValueHandlers set, using defaults: " + methodReturnValueHandlers);
}
if (getCustomMethodReturnValueHandlers() != null) {
methodReturnValueHandlers.addAll(getCustomMethodReturnValueHandlers());
}
setMethodReturnValueHandlers(methodReturnValueHandlers);
}
}
private boolean isPresent(String className) {
return ClassUtils.isPresent(className, getClassLoader());
}
private boolean isPresent(String className) {
return ClassUtils.isPresent(className, getClassLoader());
}
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
return supportsParameters(methodEndpoint.getMethodParameters()) &&
supportsReturnType(methodEndpoint.getReturnType());
}
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
return supportsParameters(methodEndpoint.getMethodParameters()) &&
supportsReturnType(methodEndpoint.getReturnType());
}
private boolean supportsParameters(MethodParameter[] methodParameters) {
for (MethodParameter methodParameter : methodParameters) {
boolean supported = false;
for (MethodArgumentResolver methodArgumentResolver : methodArgumentResolvers) {
if (logger.isTraceEnabled()) {
logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" +
methodParameter.getGenericParameterType() + "]");
}
if (methodArgumentResolver.supportsParameter(methodParameter)) {
supported = true;
break;
}
}
if (!supported) {
return false;
}
}
return true;
}
private boolean supportsParameters(MethodParameter[] methodParameters) {
for (MethodParameter methodParameter : methodParameters) {
boolean supported = false;
for (MethodArgumentResolver methodArgumentResolver : methodArgumentResolvers) {
if (logger.isTraceEnabled()) {
logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" +
methodParameter.getGenericParameterType() + "]");
}
if (methodArgumentResolver.supportsParameter(methodParameter)) {
supported = true;
break;
}
}
if (!supported) {
return false;
}
}
return true;
}
private boolean supportsReturnType(MethodParameter methodReturnType) {
if (Void.TYPE.equals(methodReturnType.getParameterType())) {
return true;
}
for (MethodReturnValueHandler methodReturnValueHandler : methodReturnValueHandlers) {
if (methodReturnValueHandler.supportsReturnType(methodReturnType)) {
return true;
}
}
return false;
}
private boolean supportsReturnType(MethodParameter methodReturnType) {
if (Void.TYPE.equals(methodReturnType.getParameterType())) {
return true;
}
for (MethodReturnValueHandler methodReturnValueHandler : methodReturnValueHandlers) {
if (methodReturnValueHandler.supportsReturnType(methodReturnType)) {
return true;
}
}
return false;
}
@Override
protected final void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Object[] args = getMethodArguments(messageContext, methodEndpoint);
@Override
protected final void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Object[] args = getMethodArguments(messageContext, methodEndpoint);
if (logger.isTraceEnabled()) {
logger.trace("Invoking [" + methodEndpoint + "] with arguments " + Arrays.asList(args));
}
if (logger.isTraceEnabled()) {
logger.trace("Invoking [" + methodEndpoint + "] with arguments " + Arrays.asList(args));
}
Object returnValue = methodEndpoint.invoke(args);
Object returnValue = methodEndpoint.invoke(args);
if (logger.isTraceEnabled()) {
logger.trace("Method [" + methodEndpoint + "] returned [" + returnValue + "]");
}
if (logger.isTraceEnabled()) {
logger.trace("Method [" + methodEndpoint + "] returned [" + returnValue + "]");
}
Class<?> returnType = methodEndpoint.getMethod().getReturnType();
if (!Void.TYPE.equals(returnType)) {
handleMethodReturnValue(messageContext, returnValue, methodEndpoint);
}
}
Class<?> returnType = methodEndpoint.getMethod().getReturnType();
if (!Void.TYPE.equals(returnType)) {
handleMethodReturnValue(messageContext, returnValue, methodEndpoint);
}
}
/**
* Returns the argument array for the given method endpoint.
*
* <p>This implementation iterates over the set {@linkplain #setMethodArgumentResolvers(List) argument resolvers} to
* resolve each argument.
*
* @param messageContext the current message context
* @param methodEndpoint the method endpoint to get arguments for
* @return the arguments
* @throws Exception in case of errors
*/
protected Object[] getMethodArguments(MessageContext messageContext, MethodEndpoint methodEndpoint)
throws Exception {
MethodParameter[] parameters = methodEndpoint.getMethodParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
for (MethodArgumentResolver methodArgumentResolver : methodArgumentResolvers) {
if (methodArgumentResolver.supportsParameter(parameters[i])) {
args[i] = methodArgumentResolver.resolveArgument(messageContext, parameters[i]);
break;
}
}
}
return args;
}
/**
* Returns the argument array for the given method endpoint.
*
* <p>This implementation iterates over the set {@linkplain #setMethodArgumentResolvers(List) argument resolvers} to
* resolve each argument.
*
* @param messageContext the current message context
* @param methodEndpoint the method endpoint to get arguments for
* @return the arguments
* @throws Exception in case of errors
*/
protected Object[] getMethodArguments(MessageContext messageContext, MethodEndpoint methodEndpoint)
throws Exception {
MethodParameter[] parameters = methodEndpoint.getMethodParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
for (MethodArgumentResolver methodArgumentResolver : methodArgumentResolvers) {
if (methodArgumentResolver.supportsParameter(parameters[i])) {
args[i] = methodArgumentResolver.resolveArgument(messageContext, parameters[i]);
break;
}
}
}
return args;
}
/**
* Handle the return value for the given method endpoint.
*
* <p>This implementation iterates over the set {@linkplain #setMethodReturnValueHandlers(java.util.List)} return value
* handlers} to resolve the return value.
*
* @param messageContext the current message context
* @param returnValue the return value
* @param methodEndpoint the method endpoint to get arguments for
* @throws Exception in case of errors
*/
protected void handleMethodReturnValue(MessageContext messageContext,
Object returnValue,
MethodEndpoint methodEndpoint) throws Exception {
MethodParameter returnType = methodEndpoint.getReturnType();
for (MethodReturnValueHandler methodReturnValueHandler : methodReturnValueHandlers) {
if (methodReturnValueHandler.supportsReturnType(returnType)) {
methodReturnValueHandler.handleReturnValue(messageContext, returnType, returnValue);
return;
}
}
throw new IllegalStateException(
"Return value [" + returnValue + "] not resolved by any MethodReturnValueHandler");
}
/**
* Handle the return value for the given method endpoint.
*
* <p>This implementation iterates over the set {@linkplain #setMethodReturnValueHandlers(java.util.List)} return value
* handlers} to resolve the return value.
*
* @param messageContext the current message context
* @param returnValue the return value
* @param methodEndpoint the method endpoint to get arguments for
* @throws Exception in case of errors
*/
protected void handleMethodReturnValue(MessageContext messageContext,
Object returnValue,
MethodEndpoint methodEndpoint) throws Exception {
MethodParameter returnType = methodEndpoint.getReturnType();
for (MethodReturnValueHandler methodReturnValueHandler : methodReturnValueHandlers) {
if (methodReturnValueHandler.supportsReturnType(returnType)) {
methodReturnValueHandler.handleReturnValue(messageContext, returnType, returnValue);
return;
}
}
throw new IllegalStateException(
"Return value [" + returnValue + "] not resolved by any MethodReturnValueHandler");
}
}

View File

@@ -36,78 +36,78 @@ import org.springframework.ws.server.endpoint.MethodEndpoint;
* @author Arjen Poutsma
* @since 1.0.2
* @deprecated as of Spring Web Services 2.0, in favor of {@link DefaultMethodEndpointAdapter} and {@link
* org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor
* MarshallingPayloadMethodProcessor}.
* org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor
* MarshallingPayloadMethodProcessor}.
*/
@Deprecated
public class GenericMarshallingMethodEndpointAdapter extends MarshallingMethodEndpointAdapter {
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter}. The {@link Marshaller} and {@link
* Unmarshaller} must be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
public GenericMarshallingMethodEndpointAdapter() {
}
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter}. The {@link Marshaller} and {@link
* Unmarshaller} must be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
public GenericMarshallingMethodEndpointAdapter() {
}
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter} with the given marshaller. 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} does not implement the {@link Unmarshaller}
* interface
*/
public GenericMarshallingMethodEndpointAdapter(Marshaller marshaller) {
super(marshaller);
}
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter} with the given marshaller. 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} does not implement the {@link Unmarshaller}
* interface
*/
public GenericMarshallingMethodEndpointAdapter(Marshaller marshaller) {
super(marshaller);
}
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public GenericMarshallingMethodEndpointAdapter(Marshaller marshaller, Unmarshaller unmarshaller) {
super(marshaller, unmarshaller);
}
/**
* Creates a new {@code GenericMarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public GenericMarshallingMethodEndpointAdapter(Marshaller marshaller, Unmarshaller unmarshaller) {
super(marshaller, unmarshaller);
}
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return supportsReturnType(method) && supportsParameters(method);
}
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return supportsReturnType(method) && supportsParameters(method);
}
private boolean supportsReturnType(Method method) {
if (Void.TYPE.equals(method.getReturnType())) {
return true;
}
else {
if (getMarshaller() instanceof GenericMarshaller) {
return ((GenericMarshaller) getMarshaller()).supports(method.getGenericReturnType());
}
else {
return getMarshaller().supports(method.getReturnType());
}
}
}
private boolean supportsReturnType(Method method) {
if (Void.TYPE.equals(method.getReturnType())) {
return true;
}
else {
if (getMarshaller() instanceof GenericMarshaller) {
return ((GenericMarshaller) getMarshaller()).supports(method.getGenericReturnType());
}
else {
return getMarshaller().supports(method.getReturnType());
}
}
}
private boolean supportsParameters(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
else if (getUnmarshaller() instanceof GenericUnmarshaller) {
GenericUnmarshaller genericUnmarshaller = (GenericUnmarshaller) getUnmarshaller();
return genericUnmarshaller.supports(method.getGenericParameterTypes()[0]);
}
else {
return getUnmarshaller().supports(method.getParameterTypes()[0]);
}
}
private boolean supportsParameters(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
else if (getUnmarshaller() instanceof GenericUnmarshaller) {
GenericUnmarshaller genericUnmarshaller = (GenericUnmarshaller) getUnmarshaller();
return genericUnmarshaller.supports(method.getGenericParameterTypes()[0]);
}
else {
return getUnmarshaller().supports(method.getParameterTypes()[0]);
}
}
}

View File

@@ -50,139 +50,139 @@ import org.springframework.ws.support.MarshallingUtils;
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
* @since 1.0.0
* @deprecated as of Spring Web Services 2.0, in favor of {@link DefaultMethodEndpointAdapter} and {@link
* org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor
* MarshallingPayloadMethodProcessor}.
* org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor
* MarshallingPayloadMethodProcessor}.
*/
@Deprecated
public class MarshallingMethodEndpointAdapter extends AbstractMethodEndpointAdapter implements InitializingBean {
private Marshaller marshaller;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private Unmarshaller unmarshaller;
/**
* Creates a new {@code MarshallingMethodEndpointAdapter}. The {@link Marshaller} and {@link Unmarshaller} must
* be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
public MarshallingMethodEndpointAdapter() {
}
/**
* Creates a new {@code MarshallingMethodEndpointAdapter}. The {@link Marshaller} and {@link Unmarshaller} must
* be injected using properties.
*
* @see #setMarshaller(org.springframework.oxm.Marshaller)
* @see #setUnmarshaller(org.springframework.oxm.Unmarshaller)
*/
public MarshallingMethodEndpointAdapter() {
}
/**
* Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller. 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 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} does not implement the {@link Unmarshaller}
* interface
*/
public MarshallingMethodEndpointAdapter(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 explicitly by using the " +
"MarshallingMethodEndpointAdapter(Marshaller, Unmarshaller) constructor.");
}
else {
this.setMarshaller(marshaller);
this.setUnmarshaller((Unmarshaller) marshaller);
}
}
/**
* Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller. 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 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} does not implement the {@link Unmarshaller}
* interface
*/
public MarshallingMethodEndpointAdapter(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 explicitly by using the " +
"MarshallingMethodEndpointAdapter(Marshaller, Unmarshaller) constructor.");
}
else {
this.setMarshaller(marshaller);
this.setUnmarshaller((Unmarshaller) marshaller);
}
}
/**
* Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingMethodEndpointAdapter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
this.setMarshaller(marshaller);
this.setUnmarshaller(unmarshaller);
}
/**
* Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingMethodEndpointAdapter(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
this.setMarshaller(marshaller);
this.setUnmarshaller(unmarshaller);
}
/** Returns the marshaller used for transforming objects into XML. */
public Marshaller getMarshaller() {
return marshaller;
}
/** Returns the marshaller used for transforming objects into XML. */
public Marshaller getMarshaller() {
return marshaller;
}
/** Sets the marshaller used for transforming objects into XML. */
public final void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Sets the marshaller used for transforming objects into XML. */
public final void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/** Returns the unmarshaller used for transforming XML into objects. */
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/** Returns the unmarshaller used for transforming XML into objects. */
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/** Sets the unmarshaller used for transforming XML into objects. */
public final void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
/** Sets the unmarshaller used for transforming XML into objects. */
public final void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(getMarshaller(), "marshaller is required");
Assert.notNull(getUnmarshaller(), "unmarshaller is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(getMarshaller(), "marshaller is required");
Assert.notNull(getUnmarshaller(), "unmarshaller is required");
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
WebServiceMessage request = messageContext.getRequest();
Object requestObject = unmarshalRequest(request);
Object responseObject = methodEndpoint.invoke(new Object[]{requestObject});
if (responseObject != null) {
WebServiceMessage response = messageContext.getResponse();
marshalResponse(responseObject, response);
}
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
WebServiceMessage request = messageContext.getRequest();
Object requestObject = unmarshalRequest(request);
Object responseObject = methodEndpoint.invoke(new Object[]{requestObject});
if (responseObject != null) {
WebServiceMessage response = messageContext.getResponse();
marshalResponse(responseObject, response);
}
}
private Object unmarshalRequest(WebServiceMessage request) throws IOException {
Object requestObject = MarshallingUtils.unmarshal(getUnmarshaller(), request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + requestObject + "]");
}
return requestObject;
}
private Object unmarshalRequest(WebServiceMessage request) throws IOException {
Object requestObject = MarshallingUtils.unmarshal(getUnmarshaller(), request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + requestObject + "]");
}
return requestObject;
}
private void marshalResponse(Object responseObject, WebServiceMessage response) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + responseObject + "] to response payload");
}
MarshallingUtils.marshal(getMarshaller(), responseObject, response);
}
private void marshalResponse(Object responseObject, WebServiceMessage response) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + responseObject + "] to response payload");
}
MarshallingUtils.marshal(getMarshaller(), responseObject, response);
}
/**
* Supports a method with a single, unmarshallable parameter, and that return {@code void} or a marshallable
* type.
*
* @see Marshaller#supports(Class)
* @see Unmarshaller#supports(Class)
*/
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return supportsReturnType(method) && supportsParameters(method);
}
/**
* Supports a method with a single, unmarshallable parameter, and that return {@code void} or a marshallable
* type.
*
* @see Marshaller#supports(Class)
* @see Unmarshaller#supports(Class)
*/
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return supportsReturnType(method) && supportsParameters(method);
}
private boolean supportsReturnType(Method method) {
return (Void.TYPE.equals(method.getReturnType()) || getMarshaller().supports(method.getReturnType()));
}
private boolean supportsReturnType(Method method) {
return (Void.TYPE.equals(method.getReturnType()) || getMarshaller().supports(method.getReturnType()));
}
private boolean supportsParameters(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
else {
return getUnmarshaller().supports(method.getParameterTypes()[0]);
}
}
private boolean supportsParameters(Method method) {
if (method.getParameterTypes().length != 1) {
return false;
}
else {
return getUnmarshaller().supports(method.getParameterTypes()[0]);
}
}
}

View File

@@ -33,13 +33,13 @@ import org.springframework.ws.soap.server.SoapMessageDispatcher;
*/
public class MessageEndpointAdapter implements EndpointAdapter {
@Override
public boolean supports(Object endpoint) {
return endpoint instanceof MessageEndpoint;
}
@Override
public boolean supports(Object endpoint) {
return endpoint instanceof MessageEndpoint;
}
@Override
public void invoke(MessageContext messageContext, Object endpoint) throws Exception {
((MessageEndpoint) endpoint).invoke(messageContext);
}
@Override
public void invoke(MessageContext messageContext, Object endpoint) throws Exception {
((MessageEndpoint) endpoint).invoke(messageContext);
}
}

View File

@@ -36,22 +36,22 @@ import org.springframework.ws.soap.server.SoapMessageDispatcher;
* @author Arjen Poutsma
* @since 1.0.0
* @deprecated as of Spring Web Services 2.0, in favor of {@link DefaultMethodEndpointAdapter} and {@link
* org.springframework.ws.server.endpoint.adapter.method.MessageContextMethodArgumentResolver
* MessageContextMethodArgumentResolver}.
* org.springframework.ws.server.endpoint.adapter.method.MessageContextMethodArgumentResolver
* MessageContextMethodArgumentResolver}.
*/
@Deprecated
public class MessageMethodEndpointAdapter extends AbstractMethodEndpointAdapter {
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return Void.TYPE.isAssignableFrom(method.getReturnType()) && method.getParameterTypes().length == 1 &&
MessageContext.class.isAssignableFrom(method.getParameterTypes()[0]);
}
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return Void.TYPE.isAssignableFrom(method.getReturnType()) && method.getParameterTypes().length == 1 &&
MessageContext.class.isAssignableFrom(method.getParameterTypes()[0]);
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
methodEndpoint.invoke(messageContext);
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
methodEndpoint.invoke(messageContext);
}
}

View File

@@ -38,19 +38,19 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public class PayloadEndpointAdapter extends TransformerObjectSupport implements EndpointAdapter {
@Override
public boolean supports(Object endpoint) {
return endpoint instanceof PayloadEndpoint;
}
@Override
public boolean supports(Object endpoint) {
return endpoint instanceof PayloadEndpoint;
}
@Override
public void invoke(MessageContext messageContext, Object endpoint) throws Exception {
PayloadEndpoint payloadEndpoint = (PayloadEndpoint) endpoint;
Source requestSource = messageContext.getRequest().getPayloadSource();
Source responseSource = payloadEndpoint.invoke(requestSource);
if (responseSource != null) {
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
@Override
public void invoke(MessageContext messageContext, Object endpoint) throws Exception {
PayloadEndpoint payloadEndpoint = (PayloadEndpoint) endpoint;
Source requestSource = messageContext.getRequest().getPayloadSource();
Source responseSource = payloadEndpoint.invoke(requestSource);
if (responseSource != null) {
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
}

View File

@@ -42,29 +42,29 @@ import org.springframework.ws.soap.server.SoapMessageDispatcher;
* @author Arjen Poutsma
* @since 1.0.0
* @deprecated as of Spring Web Services 2.0, in favor of {@link DefaultMethodEndpointAdapter} and {@link
* org.springframework.ws.server.endpoint.adapter.method.SourcePayloadMethodProcessor
* SourcePayloadMethodProcessor}.
* org.springframework.ws.server.endpoint.adapter.method.SourcePayloadMethodProcessor
* SourcePayloadMethodProcessor}.
*/
@Deprecated
public class PayloadMethodEndpointAdapter extends AbstractMethodEndpointAdapter {
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return (Void.TYPE.isAssignableFrom(method.getReturnType()) ||
Source.class.isAssignableFrom(method.getReturnType())) && method.getParameterTypes().length == 1 &&
Source.class.isAssignableFrom(method.getParameterTypes()[0]);
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
return (Void.TYPE.isAssignableFrom(method.getReturnType()) ||
Source.class.isAssignableFrom(method.getReturnType())) && method.getParameterTypes().length == 1 &&
Source.class.isAssignableFrom(method.getParameterTypes()[0]);
}
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Source requestSource = messageContext.getRequest().getPayloadSource();
Object result = methodEndpoint.invoke(requestSource);
if (result != null) {
Source responseSource = (Source) result;
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Source requestSource = messageContext.getRequest().getPayloadSource();
Object result = methodEndpoint.invoke(requestSource);
if (result != null) {
Source responseSource = (Source) result;
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
}

View File

@@ -58,126 +58,126 @@ import org.springframework.xml.namespace.SimpleNamespaceContext;
* @author Arjen Poutsma
* @since 1.0.0
* @deprecated as of Spring Web Services 2.0, in favor of {@link DefaultMethodEndpointAdapter} and {@link
* org.springframework.ws.server.endpoint.adapter.method.XPathParamMethodArgumentResolver
* XPathParamMethodArgumentResolver}.
* org.springframework.ws.server.endpoint.adapter.method.XPathParamMethodArgumentResolver
* XPathParamMethodArgumentResolver}.
*/
@Deprecated
public class XPathParamAnnotationMethodEndpointAdapter extends AbstractMethodEndpointAdapter
implements InitializingBean {
implements InitializingBean {
private XPathFactory xpathFactory;
private XPathFactory xpathFactory;
private Map<String, String> namespaces;
private Map<String, String> namespaces;
/** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
/** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
@Override
public void afterPropertiesSet() throws Exception {
xpathFactory = XPathFactory.newInstance();
}
@Override
public void afterPropertiesSet() throws Exception {
xpathFactory = XPathFactory.newInstance();
}
/** Supports methods with @XPathParam parameters, and return either {@code Source} or nothing. */
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
if (!(Source.class.isAssignableFrom(method.getReturnType()) || Void.TYPE.equals(method.getReturnType()))) {
return false;
}
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (getXPathParamAnnotation(method, i) == null || !isSupportedType(parameterTypes[i])) {
return false;
}
}
return true;
}
/** Supports methods with @XPathParam parameters, and return either {@code Source} or nothing. */
@Override
protected boolean supportsInternal(MethodEndpoint methodEndpoint) {
Method method = methodEndpoint.getMethod();
if (!(Source.class.isAssignableFrom(method.getReturnType()) || Void.TYPE.equals(method.getReturnType()))) {
return false;
}
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (getXPathParamAnnotation(method, i) == null || !isSupportedType(parameterTypes[i])) {
return false;
}
}
return true;
}
private XPathParam getXPathParamAnnotation(Method method, int paramIdx) {
Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (int annIdx = 0; annIdx < paramAnnotations[paramIdx].length; annIdx++) {
if (paramAnnotations[paramIdx][annIdx].annotationType().equals(XPathParam.class)) {
return (XPathParam) paramAnnotations[paramIdx][annIdx];
}
}
return null;
}
private XPathParam getXPathParamAnnotation(Method method, int paramIdx) {
Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (int annIdx = 0; annIdx < paramAnnotations[paramIdx].length; annIdx++) {
if (paramAnnotations[paramIdx][annIdx].annotationType().equals(XPathParam.class)) {
return (XPathParam) paramAnnotations[paramIdx][annIdx];
}
}
return null;
}
private boolean isSupportedType(Class<?> clazz) {
return Boolean.class.isAssignableFrom(clazz) || Boolean.TYPE.isAssignableFrom(clazz) ||
Double.class.isAssignableFrom(clazz) || Double.TYPE.isAssignableFrom(clazz) ||
Node.class.isAssignableFrom(clazz) || NodeList.class.isAssignableFrom(clazz) ||
String.class.isAssignableFrom(clazz);
}
private boolean isSupportedType(Class<?> clazz) {
return Boolean.class.isAssignableFrom(clazz) || Boolean.TYPE.isAssignableFrom(clazz) ||
Double.class.isAssignableFrom(clazz) || Double.TYPE.isAssignableFrom(clazz) ||
Node.class.isAssignableFrom(clazz) || NodeList.class.isAssignableFrom(clazz) ||
String.class.isAssignableFrom(clazz);
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Element payloadElement = getRootElement(messageContext.getRequest().getPayloadSource());
Object[] args = getMethodArguments(payloadElement, methodEndpoint.getMethod());
Object result = methodEndpoint.invoke(args);
if (result != null && result instanceof Source) {
Source responseSource = (Source) result;
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
@Override
protected void invokeInternal(MessageContext messageContext, MethodEndpoint methodEndpoint) throws Exception {
Element payloadElement = getRootElement(messageContext.getRequest().getPayloadSource());
Object[] args = getMethodArguments(payloadElement, methodEndpoint.getMethod());
Object result = methodEndpoint.invoke(args);
if (result != null && result instanceof Source) {
Source responseSource = (Source) result;
WebServiceMessage response = messageContext.getResponse();
transform(responseSource, response.getPayloadResult());
}
}
private Object[] getMethodArguments(Element payloadElement, Method method) throws XPathExpressionException {
Class<?>[] parameterTypes = method.getParameterTypes();
XPath xpath = createXPath();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
String expression = getXPathParamAnnotation(method, i).value();
QName conversionType;
if (Boolean.class.isAssignableFrom(parameterTypes[i]) || Boolean.TYPE.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.BOOLEAN;
}
else
if (Double.class.isAssignableFrom(parameterTypes[i]) || Double.TYPE.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NUMBER;
}
else if (Node.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NODE;
}
else if (NodeList.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NODESET;
}
else if (String.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.STRING;
}
else {
throw new IllegalArgumentException("Invalid parameter type [" + parameterTypes[i] + "]. " +
"Supported are: Boolean, Double, Node, NodeList, and String.");
}
args[i] = xpath.evaluate(expression, payloadElement, conversionType);
}
return args;
}
private Object[] getMethodArguments(Element payloadElement, Method method) throws XPathExpressionException {
Class<?>[] parameterTypes = method.getParameterTypes();
XPath xpath = createXPath();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
String expression = getXPathParamAnnotation(method, i).value();
QName conversionType;
if (Boolean.class.isAssignableFrom(parameterTypes[i]) || Boolean.TYPE.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.BOOLEAN;
}
else
if (Double.class.isAssignableFrom(parameterTypes[i]) || Double.TYPE.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NUMBER;
}
else if (Node.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NODE;
}
else if (NodeList.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.NODESET;
}
else if (String.class.isAssignableFrom(parameterTypes[i])) {
conversionType = XPathConstants.STRING;
}
else {
throw new IllegalArgumentException("Invalid parameter type [" + parameterTypes[i] + "]. " +
"Supported are: Boolean, Double, Node, NodeList, and String.");
}
args[i] = xpath.evaluate(expression, payloadElement, conversionType);
}
return args;
}
private synchronized XPath createXPath() {
XPath xpath = xpathFactory.newXPath();
if (namespaces != null) {
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(namespaces);
xpath.setNamespaceContext(namespaceContext);
}
return xpath;
}
private synchronized XPath createXPath() {
XPath xpath = xpathFactory.newXPath();
if (namespaces != null) {
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.setBindings(namespaces);
xpath.setNamespaceContext(namespaceContext);
}
return xpath;
}
/**
* Returns the root element of the given source.
*
* @param source the source to get the root element from
* @return the root element
*/
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
/**
* Returns the root element of the given source.
*
* @param source the source to get the root element from
* @return the root element
*/
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
}

View File

@@ -36,74 +36,74 @@ import org.springframework.xml.transform.TransformerObjectSupport;
* @since 2.0
*/
public abstract class AbstractPayloadMethodProcessor extends TransformerObjectSupport
implements MethodArgumentResolver, MethodReturnValueHandler {
implements MethodArgumentResolver, MethodReturnValueHandler {
// MethodArgumentResolver
// MethodArgumentResolver
/**
* {@inheritDoc}
*
* <p>This implementation gets checks if the given parameter is annotated with {@link RequestPayload}, and invokes
* {@link #supportsRequestPayloadParameter(org.springframework.core.MethodParameter)} afterwards.
*/
@Override
public final boolean supportsParameter(MethodParameter parameter) {
Assert.isTrue(parameter.getParameterIndex() >= 0, "Parameter index larger smaller than 0");
if (parameter.getParameterAnnotation(RequestPayload.class) == null) {
return false;
}
else {
return supportsRequestPayloadParameter(parameter);
}
}
/**
* {@inheritDoc}
*
* <p>This implementation gets checks if the given parameter is annotated with {@link RequestPayload}, and invokes
* {@link #supportsRequestPayloadParameter(org.springframework.core.MethodParameter)} afterwards.
*/
@Override
public final boolean supportsParameter(MethodParameter parameter) {
Assert.isTrue(parameter.getParameterIndex() >= 0, "Parameter index larger smaller than 0");
if (parameter.getParameterAnnotation(RequestPayload.class) == null) {
return false;
}
else {
return supportsRequestPayloadParameter(parameter);
}
}
/**
* Indicates whether the given {@linkplain MethodParameter method parameter}, annotated with {@link RequestPayload},
* is supported by this resolver.
*
* @param parameter the method parameter to check
* @return {@code true} if this resolver supports the supplied parameter; {@code false} otherwise
*/
protected abstract boolean supportsRequestPayloadParameter(MethodParameter parameter);
/**
* Indicates whether the given {@linkplain MethodParameter method parameter}, annotated with {@link RequestPayload},
* is supported by this resolver.
*
* @param parameter the method parameter to check
* @return {@code true} if this resolver supports the supplied parameter; {@code false} otherwise
*/
protected abstract boolean supportsRequestPayloadParameter(MethodParameter parameter);
// MethodReturnValueHandler
/**
* {@inheritDoc}
*
* <p>This implementation gets checks if the method of the given return type is annotated with {@link ResponsePayload},
* and invokes {@link #supportsResponsePayloadReturnType(org.springframework.core.MethodParameter)} afterwards.
*/
@Override
public final boolean supportsReturnType(MethodParameter returnType) {
Assert.isTrue(returnType.getParameterIndex() == -1, "Parameter index is not -1");
if (returnType.getMethodAnnotation(ResponsePayload.class) == null) {
return false;
}
else {
return supportsResponsePayloadReturnType(returnType);
}
}
// MethodReturnValueHandler
/**
* {@inheritDoc}
*
* <p>This implementation gets checks if the method of the given return type is annotated with {@link ResponsePayload},
* and invokes {@link #supportsResponsePayloadReturnType(org.springframework.core.MethodParameter)} afterwards.
*/
@Override
public final boolean supportsReturnType(MethodParameter returnType) {
Assert.isTrue(returnType.getParameterIndex() == -1, "Parameter index is not -1");
if (returnType.getMethodAnnotation(ResponsePayload.class) == null) {
return false;
}
else {
return supportsResponsePayloadReturnType(returnType);
}
}
/**
* Indicates whether the given {@linkplain MethodParameter method return type}, annotated with {@link
* ResponsePayload}, is supported.
*
* @param returnType the method parameter to check
* @return {@code true} if this resolver supports the supplied return type; {@code false} otherwise
*/
protected abstract boolean supportsResponsePayloadReturnType(MethodParameter returnType);
/**
* Indicates whether the given {@linkplain MethodParameter method return type}, annotated with {@link
* ResponsePayload}, is supported.
*
* @param returnType the method parameter to check
* @return {@code true} if this resolver supports the supplied return type; {@code false} otherwise
*/
protected abstract boolean supportsResponsePayloadReturnType(MethodParameter returnType);
/**
* Converts the given source to a byte array input stream.
*
* @param source the source to convert
* @return the input stream
* @throws javax.xml.transform.TransformerException in case of transformation errors
*/
protected ByteArrayInputStream convertToByteArrayInputStream(Source source) throws TransformerException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transform(source, new StreamResult(bos));
return new ByteArrayInputStream(bos.toByteArray());
}
/**
* Converts the given source to a byte array input stream.
*
* @param source the source to convert
* @return the input stream
* @throws javax.xml.transform.TransformerException in case of transformation errors
*/
protected ByteArrayInputStream convertToByteArrayInputStream(Source source) throws TransformerException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transform(source, new StreamResult(bos));
return new ByteArrayInputStream(bos.toByteArray());
}
}

View File

@@ -32,53 +32,53 @@ import org.springframework.ws.server.endpoint.annotation.RequestPayload;
*/
public abstract class AbstractPayloadSourceMethodProcessor extends AbstractPayloadMethodProcessor {
// MethodArgumentResolver
// MethodArgumentResolver
@Override
public final Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
Source requestPayload = getRequestPayload(messageContext);
return requestPayload != null ? resolveRequestPayloadArgument(parameter, requestPayload) : null;
}
@Override
public final Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
Source requestPayload = getRequestPayload(messageContext);
return requestPayload != null ? resolveRequestPayloadArgument(parameter, requestPayload) : null;
}
/** Returns the request payload as {@code Source}. */
private Source getRequestPayload(MessageContext messageContext) {
WebServiceMessage request = messageContext.getRequest();
return request != null ? request.getPayloadSource() : null;
}
/** Returns the request payload as {@code Source}. */
private Source getRequestPayload(MessageContext messageContext) {
WebServiceMessage request = messageContext.getRequest();
return request != null ? request.getPayloadSource() : null;
}
/**
* Resolves the given parameter, annotated with {@link RequestPayload}, into a method argument.
*
* @param parameter the parameter to resolve to an argument
* @param requestPayload the request payload
* @return the resolved argument. May be {@code null}.
* @throws Exception in case of errors
*/
protected abstract Object resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws Exception;
/**
* Resolves the given parameter, annotated with {@link RequestPayload}, into a method argument.
*
* @param parameter the parameter to resolve to an argument
* @param requestPayload the request payload
* @return the resolved argument. May be {@code null}.
* @throws Exception in case of errors
*/
protected abstract Object resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws Exception;
// MethodReturnValueHandler
// MethodReturnValueHandler
@Override
public final void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception {
if (returnValue != null) {
Source responsePayload = createResponsePayload(returnType, returnValue);
if (responsePayload != null) {
WebServiceMessage response = messageContext.getResponse();
transform(responsePayload, response.getPayloadResult());
}
}
}
@Override
public final void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception {
if (returnValue != null) {
Source responsePayload = createResponsePayload(returnType, returnValue);
if (responsePayload != null) {
WebServiceMessage response = messageContext.getResponse();
transform(responsePayload, response.getPayloadResult());
}
}
}
/**
* Creates a response payload for the given return value.
*
* @param returnType the return type to handle
* @param returnValue the return value to handle
* @return the response payload
* @throws Exception in case of errors
*/
protected abstract Source createResponsePayload(MethodParameter returnType, Object returnValue) throws Exception;
/**
* Creates a response payload for the given return value.
*
* @param returnType the return type to handle
* @param returnValue the return value to handle
* @return the response payload
* @throws Exception in case of errors
*/
protected abstract Source createResponsePayload(MethodParameter returnType, Object returnValue) throws Exception;
}

View File

@@ -35,135 +35,135 @@ import org.springframework.ws.support.MarshallingUtils;
*/
public class MarshallingPayloadMethodProcessor extends AbstractPayloadMethodProcessor {
private Marshaller marshaller;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private Unmarshaller unmarshaller;
/**
* Creates a new {@code MarshallingPayloadMethodProcessor}. The {@link Marshaller} and {@link Unmarshaller} must be
* injected using properties.
*
* @see #setMarshaller(Marshaller)
* @see #setUnmarshaller(Unmarshaller)
*/
public MarshallingPayloadMethodProcessor() {
}
/**
* Creates a new {@code MarshallingPayloadMethodProcessor}. The {@link Marshaller} and {@link Unmarshaller} must be
* injected using properties.
*
* @see #setMarshaller(Marshaller)
* @see #setUnmarshaller(Unmarshaller)
*/
public MarshallingPayloadMethodProcessor() {
}
/**
* Creates a new {@code MarshallingPayloadMethodProcessor} with the given marshaller. 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 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} does not implement the {@link Unmarshaller} interface
*/
public MarshallingPayloadMethodProcessor(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.isInstanceOf(Unmarshaller.class, marshaller);
setMarshaller(marshaller);
setUnmarshaller((Unmarshaller) marshaller);
}
/**
* Creates a new {@code MarshallingPayloadMethodProcessor} with the given marshaller. 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 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} does not implement the {@link Unmarshaller} interface
*/
public MarshallingPayloadMethodProcessor(Marshaller marshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.isInstanceOf(Unmarshaller.class, marshaller);
setMarshaller(marshaller);
setUnmarshaller((Unmarshaller) marshaller);
}
/**
* Creates a new {@code MarshallingPayloadMethodProcessor} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingPayloadMethodProcessor(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
setMarshaller(marshaller);
setUnmarshaller(unmarshaller);
}
/**
* Creates a new {@code MarshallingPayloadMethodProcessor} with the given marshaller and unmarshaller.
*
* @param marshaller the marshaller to use
* @param unmarshaller the unmarshaller to use
*/
public MarshallingPayloadMethodProcessor(Marshaller marshaller, Unmarshaller unmarshaller) {
Assert.notNull(marshaller, "marshaller must not be null");
Assert.notNull(unmarshaller, "unmarshaller must not be null");
setMarshaller(marshaller);
setUnmarshaller(unmarshaller);
}
/**
* Returns the marshaller used for transforming objects into XML.
*/
public Marshaller getMarshaller() {
return marshaller;
}
/**
* Returns the marshaller used for transforming objects into XML.
*/
public Marshaller getMarshaller() {
return marshaller;
}
/**
* Sets the marshaller used for transforming objects into XML.
*/
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/**
* Sets the marshaller used for transforming objects into XML.
*/
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
/**
* Returns the unmarshaller used for transforming XML into objects.
*/
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/**
* Returns the unmarshaller used for transforming XML into objects.
*/
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
/**
* Sets the unmarshaller used for transforming XML into objects.
*/
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
/**
* Sets the unmarshaller used for transforming XML into objects.
*/
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Unmarshaller unmarshaller = getUnmarshaller();
if (unmarshaller == null) {
return false;
}
else if (unmarshaller instanceof GenericUnmarshaller) {
return ((GenericUnmarshaller) unmarshaller).supports(parameter.getGenericParameterType());
}
else {
return unmarshaller.supports(parameter.getParameterType());
}
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Unmarshaller unmarshaller = getUnmarshaller();
if (unmarshaller == null) {
return false;
}
else if (unmarshaller instanceof GenericUnmarshaller) {
return ((GenericUnmarshaller) unmarshaller).supports(parameter.getGenericParameterType());
}
else {
return unmarshaller.supports(parameter.getParameterType());
}
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
Unmarshaller unmarshaller = getUnmarshaller();
Assert.state(unmarshaller != null, "unmarshaller must not be null");
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
Unmarshaller unmarshaller = getUnmarshaller();
Assert.state(unmarshaller != null, "unmarshaller must not be null");
WebServiceMessage request = messageContext.getRequest();
Object argument = MarshallingUtils.unmarshal(unmarshaller, request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + argument + "]");
}
return argument;
}
WebServiceMessage request = messageContext.getRequest();
Object argument = MarshallingUtils.unmarshal(unmarshaller, request);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + argument + "]");
}
return argument;
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Marshaller marshaller = getMarshaller();
if (marshaller == null) {
return false;
}
else if (marshaller instanceof GenericMarshaller) {
GenericMarshaller genericMarshaller = (GenericMarshaller) marshaller;
return genericMarshaller.supports(returnType.getGenericParameterType());
}
else {
return marshaller.supports(returnType.getParameterType());
}
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Marshaller marshaller = getMarshaller();
if (marshaller == null) {
return false;
}
else if (marshaller instanceof GenericMarshaller) {
GenericMarshaller genericMarshaller = (GenericMarshaller) marshaller;
return genericMarshaller.supports(returnType.getGenericParameterType());
}
else {
return marshaller.supports(returnType.getParameterType());
}
}
@Override
public void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception {
if (returnValue == null) {
return;
}
Marshaller marshaller = getMarshaller();
Assert.state(marshaller != null, "marshaller must not be null");
@Override
public void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception {
if (returnValue == null) {
return;
}
Marshaller marshaller = getMarshaller();
Assert.state(marshaller != null, "marshaller must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + returnValue + "] to response payload");
}
WebServiceMessage response = messageContext.getResponse();
MarshallingUtils.marshal(marshaller, returnValue, response);
}
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + returnValue + "] to response payload");
}
WebServiceMessage response = messageContext.getResponse();
MarshallingUtils.marshal(marshaller, returnValue, response);
}
}

View File

@@ -27,13 +27,13 @@ import org.springframework.ws.context.MessageContext;
*/
public class MessageContextMethodArgumentResolver implements MethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return MessageContext.class.equals(parameter.getParameterType());
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return MessageContext.class.equals(parameter.getParameterType());
}
@Override
public MessageContext resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
return messageContext;
}
@Override
public MessageContext resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception {
return messageContext;
}
}

View File

@@ -29,24 +29,24 @@ import org.springframework.ws.context.MessageContext;
*/
public interface MethodArgumentResolver {
/**
* Indicates whether the given {@linkplain MethodParameter method parameter} is supported by this resolver.
*
* @param parameter the method parameter to check
* @return {@code true} if this resolver supports the supplied parameter; {@code false} otherwise
*/
boolean supportsParameter(MethodParameter parameter);
/**
* Indicates whether the given {@linkplain MethodParameter method parameter} is supported by this resolver.
*
* @param parameter the method parameter to check
* @return {@code true} if this resolver supports the supplied parameter; {@code false} otherwise
*/
boolean supportsParameter(MethodParameter parameter);
/**
* Resolves the given parameter into a method argument.
*
* @param messageContext the current message context
* @param parameter the parameter to resolve to an argument. This parameter must have previously been passed to
* the {@link #supportsParameter(MethodParameter)} method of this interface, which must
* have returned {@code true}.
* @return the resolved argument. May be {@code null}.
* @throws Exception in case of errors
*/
Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception;
/**
* Resolves the given parameter into a method argument.
*
* @param messageContext the current message context
* @param parameter the parameter to resolve to an argument. This parameter must have previously been passed to
* the {@link #supportsParameter(MethodParameter)} method of this interface, which must
* have returned {@code true}.
* @return the resolved argument. May be {@code null}.
* @throws Exception in case of errors
*/
Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception;
}

View File

@@ -29,26 +29,26 @@ import org.springframework.ws.context.MessageContext;
*/
public interface MethodReturnValueHandler {
/**
* Indicates whether the given {@linkplain MethodParameter method return type} is supported by this handler.
*
* @param returnType the method return type to check
* @return {@code true} if this handler supports the supplied return type; {@code false} otherwise
*/
boolean supportsReturnType(MethodParameter returnType);
/**
* Indicates whether the given {@linkplain MethodParameter method return type} is supported by this handler.
*
* @param returnType the method return type to check
* @return {@code true} if this handler supports the supplied return type; {@code false} otherwise
*/
boolean supportsReturnType(MethodParameter returnType);
/**
* Handles the given return value.
*
* @param messageContext the current message context
* @param returnType the return type to handle. This type must have previously been passed to the {@link
* #supportsReturnType(MethodParameter)} method of this interface, which must have returned
* {@code true}.
* @param returnValue the return value to handle
* @throws Exception in case of errors
*/
void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception;
/**
* Handles the given return value.
*
* @param messageContext the current message context
* @param returnType the return type to handle. This type must have previously been passed to the {@link
* #supportsReturnType(MethodParameter)} method of this interface, which must have returned
* {@code true}.
* @param returnValue the return value to handle
* @throws Exception in case of errors
*/
void handleReturnValue(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws Exception;
}

View File

@@ -45,136 +45,136 @@ import org.xml.sax.InputSource;
*/
public class SourcePayloadMethodProcessor extends AbstractPayloadSourceMethodProcessor {
private XMLInputFactory inputFactory = createXmlInputFactory();
private XMLInputFactory inputFactory = createXmlInputFactory();
// MethodArgumentResolver
// MethodArgumentResolver
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected Source resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isAssignableFrom(requestPayload.getClass())) {
return requestPayload;
}
if (DOMSource.class.isAssignableFrom(parameterType)) {
DOMResult domResult = new DOMResult();
transform(requestPayload, domResult);
Node node = domResult.getNode();
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return new DOMSource(((Document) node).getDocumentElement());
}
else {
return new DOMSource(domResult.getNode());
}
}
else if (SAXSource.class.isAssignableFrom(parameterType)) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
InputSource inputSource = new InputSource(bis);
return new SAXSource(inputSource);
}
else if (StreamSource.class.isAssignableFrom(parameterType)) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
return new StreamSource(bis);
}
else if (JaxpVersion.isAtLeastJaxp14() && Jaxp14StaxHandler.isStaxSource(parameterType)) {
XMLStreamReader streamReader;
try {
streamReader = inputFactory.createXMLStreamReader(requestPayload);
} catch (UnsupportedOperationException ignored) {
streamReader = null;
}
catch (XMLStreamException ignored) {
streamReader = null;
}
if (streamReader == null) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
streamReader = inputFactory.createXMLStreamReader(bis);
}
return Jaxp14StaxHandler.createStaxSource(streamReader, requestPayload.getSystemId());
}
throw new IllegalArgumentException("Unknown Source type: " + parameterType);
}
@Override
protected Source resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isAssignableFrom(requestPayload.getClass())) {
return requestPayload;
}
if (DOMSource.class.isAssignableFrom(parameterType)) {
DOMResult domResult = new DOMResult();
transform(requestPayload, domResult);
Node node = domResult.getNode();
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return new DOMSource(((Document) node).getDocumentElement());
}
else {
return new DOMSource(domResult.getNode());
}
}
else if (SAXSource.class.isAssignableFrom(parameterType)) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
InputSource inputSource = new InputSource(bis);
return new SAXSource(inputSource);
}
else if (StreamSource.class.isAssignableFrom(parameterType)) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
return new StreamSource(bis);
}
else if (JaxpVersion.isAtLeastJaxp14() && Jaxp14StaxHandler.isStaxSource(parameterType)) {
XMLStreamReader streamReader;
try {
streamReader = inputFactory.createXMLStreamReader(requestPayload);
} catch (UnsupportedOperationException ignored) {
streamReader = null;
}
catch (XMLStreamException ignored) {
streamReader = null;
}
if (streamReader == null) {
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
streamReader = inputFactory.createXMLStreamReader(bis);
}
return Jaxp14StaxHandler.createStaxSource(streamReader, requestPayload.getSystemId());
}
throw new IllegalArgumentException("Unknown Source type: " + parameterType);
}
// MethodReturnValueHandler
// MethodReturnValueHandler
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
return (Source) returnValue;
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
return (Source) returnValue;
}
private boolean supports(MethodParameter parameter) {
return Source.class.isAssignableFrom(parameter.getParameterType());
}
private boolean supports(MethodParameter parameter) {
return Source.class.isAssignableFrom(parameter.getParameterType());
}
/**
* Create a {@code XMLInputFactory} that this resolver will use to create {@link javax.xml.stream.XMLStreamReader}
* and {@link javax.xml.stream.XMLEventReader} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
/**
* Create a {@code XMLInputFactory} that this resolver will use to create {@link javax.xml.stream.XMLStreamReader}
* and {@link javax.xml.stream.XMLEventReader} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
/** Inner class to avoid a static JAXP 1.4 dependency. */
private static class Jaxp14StaxHandler {
/** Inner class to avoid a static JAXP 1.4 dependency. */
private static class Jaxp14StaxHandler {
private static boolean isStaxSource(Class<?> clazz) {
return StAXSource.class.isAssignableFrom(clazz);
}
private static boolean isStaxSource(Class<?> clazz) {
return StAXSource.class.isAssignableFrom(clazz);
}
private static Source createStaxSource(XMLStreamReader streamReader, String systemId) {
return new StAXSource(new SystemIdStreamReaderDelegate(streamReader, systemId));
}
private static Source createStaxSource(XMLStreamReader streamReader, String systemId) {
return new StAXSource(new SystemIdStreamReaderDelegate(streamReader, systemId));
}
}
}
private static class SystemIdStreamReaderDelegate extends StreamReaderDelegate {
private static class SystemIdStreamReaderDelegate extends StreamReaderDelegate {
private final String systemId;
private final String systemId;
private SystemIdStreamReaderDelegate(XMLStreamReader reader, String systemId) {
super(reader);
this.systemId = systemId;
}
private SystemIdStreamReaderDelegate(XMLStreamReader reader, String systemId) {
super(reader);
this.systemId = systemId;
}
@Override
public Location getLocation() {
final Location parentLocation = getParent().getLocation();
return new Location() {
public int getLineNumber() {
return parentLocation != null ? parentLocation.getLineNumber() : -1;
}
@Override
public Location getLocation() {
final Location parentLocation = getParent().getLocation();
return new Location() {
public int getLineNumber() {
return parentLocation != null ? parentLocation.getLineNumber() : -1;
}
public int getColumnNumber() {
return parentLocation != null ? parentLocation.getColumnNumber() : -1;
}
public int getColumnNumber() {
return parentLocation != null ? parentLocation.getColumnNumber() : -1;
}
public int getCharacterOffset() {
return parentLocation != null ? parentLocation.getLineNumber() : -1;
}
public int getCharacterOffset() {
return parentLocation != null ? parentLocation.getLineNumber() : -1;
}
public String getPublicId() {
return parentLocation != null ? parentLocation.getPublicId() : null;
}
public String getPublicId() {
return parentLocation != null ? parentLocation.getPublicId() : null;
}
public String getSystemId() {
return systemId;
}
};
}
}
public String getSystemId() {
return systemId;
}
};
}
}
}

View File

@@ -41,125 +41,125 @@ import org.springframework.xml.transform.TransformerObjectSupport;
*/
public class StaxPayloadMethodArgumentResolver extends TransformerObjectSupport implements MethodArgumentResolver {
private final XMLInputFactory inputFactory = createXmlInputFactory();
private final XMLInputFactory inputFactory = createXmlInputFactory();
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getParameterAnnotation(RequestPayload.class) == null) {
return false;
}
else {
Class<?> parameterType = parameter.getParameterType();
return XMLStreamReader.class.equals(parameterType) || XMLEventReader.class.equals(parameterType);
}
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getParameterAnnotation(RequestPayload.class) == null) {
return false;
}
else {
Class<?> parameterType = parameter.getParameterType();
return XMLStreamReader.class.equals(parameterType) || XMLEventReader.class.equals(parameterType);
}
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws TransformerException, XMLStreamException {
Source source = messageContext.getRequest().getPayloadSource();
if (source == null) {
return null;
}
Class<?> parameterType = parameter.getParameterType();
if (XMLStreamReader.class.equals(parameterType)) {
return resolveStreamReader(source);
}
else if (XMLEventReader.class.equals(parameterType)) {
return resolveEventReader(source);
}
throw new UnsupportedOperationException();
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws TransformerException, XMLStreamException {
Source source = messageContext.getRequest().getPayloadSource();
if (source == null) {
return null;
}
Class<?> parameterType = parameter.getParameterType();
if (XMLStreamReader.class.equals(parameterType)) {
return resolveStreamReader(source);
}
else if (XMLEventReader.class.equals(parameterType)) {
return resolveEventReader(source);
}
throw new UnsupportedOperationException();
}
private XMLStreamReader resolveStreamReader(Source requestSource) throws TransformerException, XMLStreamException {
XMLStreamReader streamReader = null;
if (StaxUtils.isStaxSource(requestSource)) {
streamReader = StaxUtils.getXMLStreamReader(requestSource);
if (streamReader == null) {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(requestSource);
if (eventReader != null) {
try {
streamReader = StaxUtils.createEventStreamReader(eventReader);
}
catch (XMLStreamException ex) {
streamReader = null;
}
}
}
}
if (streamReader == null) {
try {
streamReader = inputFactory.createXMLStreamReader(requestSource);
}
catch (XMLStreamException ex) {
streamReader = null;
}
catch (UnsupportedOperationException ex) {
streamReader = null;
}
}
if (streamReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayInputStream bis = convertToByteArrayInputStream(requestSource);
streamReader = inputFactory.createXMLStreamReader(bis);
}
return streamReader;
}
private XMLStreamReader resolveStreamReader(Source requestSource) throws TransformerException, XMLStreamException {
XMLStreamReader streamReader = null;
if (StaxUtils.isStaxSource(requestSource)) {
streamReader = StaxUtils.getXMLStreamReader(requestSource);
if (streamReader == null) {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(requestSource);
if (eventReader != null) {
try {
streamReader = StaxUtils.createEventStreamReader(eventReader);
}
catch (XMLStreamException ex) {
streamReader = null;
}
}
}
}
if (streamReader == null) {
try {
streamReader = inputFactory.createXMLStreamReader(requestSource);
}
catch (XMLStreamException ex) {
streamReader = null;
}
catch (UnsupportedOperationException ex) {
streamReader = null;
}
}
if (streamReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayInputStream bis = convertToByteArrayInputStream(requestSource);
streamReader = inputFactory.createXMLStreamReader(bis);
}
return streamReader;
}
private XMLEventReader resolveEventReader(Source requestSource) throws TransformerException, XMLStreamException {
XMLEventReader eventReader = null;
if (StaxUtils.isStaxSource(requestSource)) {
eventReader = StaxUtils.getXMLEventReader(requestSource);
if (eventReader == null) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(requestSource);
if (streamReader != null) {
try {
eventReader = inputFactory.createXMLEventReader(streamReader);
}
catch (XMLStreamException ex) {
eventReader = null;
}
}
private XMLEventReader resolveEventReader(Source requestSource) throws TransformerException, XMLStreamException {
XMLEventReader eventReader = null;
if (StaxUtils.isStaxSource(requestSource)) {
eventReader = StaxUtils.getXMLEventReader(requestSource);
if (eventReader == null) {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(requestSource);
if (streamReader != null) {
try {
eventReader = inputFactory.createXMLEventReader(streamReader);
}
catch (XMLStreamException ex) {
eventReader = null;
}
}
}
}
if (eventReader == null) {
try {
eventReader = inputFactory.createXMLEventReader(requestSource);
}
catch (XMLStreamException ex) {
eventReader = null;
}
catch (UnsupportedOperationException ex) {
eventReader = null;
}
}
if (eventReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayInputStream bis = convertToByteArrayInputStream(requestSource);
eventReader = inputFactory.createXMLEventReader(bis);
}
return eventReader;
}
}
}
if (eventReader == null) {
try {
eventReader = inputFactory.createXMLEventReader(requestSource);
}
catch (XMLStreamException ex) {
eventReader = null;
}
catch (UnsupportedOperationException ex) {
eventReader = null;
}
}
if (eventReader == null) {
// as a final resort, transform the source to a stream, and read from that
ByteArrayInputStream bis = convertToByteArrayInputStream(requestSource);
eventReader = inputFactory.createXMLEventReader(bis);
}
return eventReader;
}
/**
* Create a {@code XMLInputFactory} that this resolver will use to create {@link XMLStreamReader} and {@link
* XMLEventReader} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
/**
* Create a {@code XMLInputFactory} that this resolver will use to create {@link XMLStreamReader} and {@link
* XMLEventReader} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XMLInputFactory createXmlInputFactory() {
return XMLInputFactory.newInstance();
}
private ByteArrayInputStream convertToByteArrayInputStream(Source source) throws TransformerException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transform(source, new StreamResult(bos));
return new ByteArrayInputStream(bos.toByteArray());
}
private ByteArrayInputStream convertToByteArrayInputStream(Source source) throws TransformerException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transform(source, new StreamResult(bos));
return new ByteArrayInputStream(bos.toByteArray());
}

View File

@@ -52,108 +52,108 @@ import org.springframework.xml.transform.TransformerHelper;
*/
public class XPathParamMethodArgumentResolver implements MethodArgumentResolver {
private final XPathFactory xpathFactory = createXPathFactory();
private final XPathFactory xpathFactory = createXPathFactory();
private TransformerHelper transformerHelper = new TransformerHelper();
private TransformerHelper transformerHelper = new TransformerHelper();
private ConversionService conversionService = new DefaultConversionService();
private ConversionService conversionService = new DefaultConversionService();
/**
* Sets the conversion service to use.
*
* <p>Defaults to the {@linkplain ConversionServiceFactory#createDefaultConversionService() default conversion
* service}.
*/
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
/**
* Sets the conversion service to use.
*
* <p>Defaults to the {@linkplain ConversionServiceFactory#createDefaultConversionService() default conversion
* service}.
*/
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
public void setTransformerHelper(TransformerHelper transformerHelper) {
this.transformerHelper = transformerHelper;
}
public void setTransformerHelper(TransformerHelper transformerHelper) {
this.transformerHelper = transformerHelper;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getParameterAnnotation(XPathParam.class) == null) {
return false;
}
Class<?> parameterType = parameter.getParameterType();
if (Boolean.class.equals(parameterType) || Boolean.TYPE.equals(parameterType) ||
Double.class.equals(parameterType) || Double.TYPE.equals(parameterType) ||
Node.class.isAssignableFrom(parameterType) || NodeList.class.isAssignableFrom(parameterType) ||
String.class.isAssignableFrom(parameterType)) {
return true;
}
else {
return conversionService.canConvert(String.class, parameterType);
}
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getParameterAnnotation(XPathParam.class) == null) {
return false;
}
Class<?> parameterType = parameter.getParameterType();
if (Boolean.class.equals(parameterType) || Boolean.TYPE.equals(parameterType) ||
Double.class.equals(parameterType) || Double.TYPE.equals(parameterType) ||
Node.class.isAssignableFrom(parameterType) || NodeList.class.isAssignableFrom(parameterType) ||
String.class.isAssignableFrom(parameterType)) {
return true;
}
else {
return conversionService.canConvert(String.class, parameterType);
}
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws TransformerException, XPathExpressionException {
Class<?> parameterType = parameter.getParameterType();
QName evaluationReturnType = getReturnType(parameterType);
boolean useConversionService = false;
if (evaluationReturnType == null) {
evaluationReturnType = XPathConstants.STRING;
useConversionService = true;
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws TransformerException, XPathExpressionException {
Class<?> parameterType = parameter.getParameterType();
QName evaluationReturnType = getReturnType(parameterType);
boolean useConversionService = false;
if (evaluationReturnType == null) {
evaluationReturnType = XPathConstants.STRING;
useConversionService = true;
}
XPath xpath = createXPath();
xpath.setNamespaceContext(NamespaceUtils.getNamespaceContext(parameter.getMethod()));
XPath xpath = createXPath();
xpath.setNamespaceContext(NamespaceUtils.getNamespaceContext(parameter.getMethod()));
Element rootElement = getRootElement(messageContext.getRequest().getPayloadSource());
String expression = parameter.getParameterAnnotation(XPathParam.class).value();
Object result = xpath.evaluate(expression, rootElement, evaluationReturnType);
return useConversionService ? conversionService.convert(result, parameterType) : result;
}
Element rootElement = getRootElement(messageContext.getRequest().getPayloadSource());
String expression = parameter.getParameterAnnotation(XPathParam.class).value();
Object result = xpath.evaluate(expression, rootElement, evaluationReturnType);
return useConversionService ? conversionService.convert(result, parameterType) : result;
}
private QName getReturnType(Class<?> parameterType) {
if (Boolean.class.equals(parameterType) || Boolean.TYPE.equals(parameterType)) {
return XPathConstants.BOOLEAN;
}
else if (Double.class.equals(parameterType) || Double.TYPE.equals(parameterType)) {
return XPathConstants.NUMBER;
}
else if (Node.class.equals(parameterType)) {
return XPathConstants.NODE;
}
else if (NodeList.class.equals(parameterType)) {
return XPathConstants.NODESET;
}
else if (String.class.equals(parameterType)) {
return XPathConstants.STRING;
}
else {
return null;
}
}
private QName getReturnType(Class<?> parameterType) {
if (Boolean.class.equals(parameterType) || Boolean.TYPE.equals(parameterType)) {
return XPathConstants.BOOLEAN;
}
else if (Double.class.equals(parameterType) || Double.TYPE.equals(parameterType)) {
return XPathConstants.NUMBER;
}
else if (Node.class.equals(parameterType)) {
return XPathConstants.NODE;
}
else if (NodeList.class.equals(parameterType)) {
return XPathConstants.NODESET;
}
else if (String.class.equals(parameterType)) {
return XPathConstants.STRING;
}
else {
return null;
}
}
private XPath createXPath() {
synchronized (xpathFactory) {
return xpathFactory.newXPath();
}
}
private XPath createXPath() {
synchronized (xpathFactory) {
return xpathFactory.newXPath();
}
}
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transformerHelper.transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
private Element getRootElement(Source source) throws TransformerException {
DOMResult domResult = new DOMResult();
transformerHelper.transform(source, domResult);
Document document = (Document) domResult.getNode();
return document.getDocumentElement();
}
/**
* Create a {@code XPathFactory} that this resolver will use to create {@link XPath} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XPathFactory createXPathFactory() {
return XPathFactory.newInstance();
}
/**
* Create a {@code XPathFactory} that this resolver will use to create {@link XPath} objects.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected XPathFactory createXPathFactory() {
return XPathFactory.newInstance();
}
}

View File

@@ -39,41 +39,41 @@ import org.dom4j.io.DocumentSource;
*/
public class Dom4jPayloadMethodProcessor extends AbstractPayloadSourceMethodProcessor {
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws TransformerException {
if (requestPayload instanceof DOMSource) {
org.w3c.dom.Node node = ((DOMSource) requestPayload).getNode();
if (node.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE) {
DOMReader domReader = new DOMReader();
Document document = domReader.read((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
DocumentResult dom4jResult = new DocumentResult();
transform(requestPayload, dom4jResult);
return dom4jResult.getDocument().getRootElement();
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws TransformerException {
if (requestPayload instanceof DOMSource) {
org.w3c.dom.Node node = ((DOMSource) requestPayload).getNode();
if (node.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE) {
DOMReader domReader = new DOMReader();
Document document = domReader.read((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
DocumentResult dom4jResult = new DocumentResult();
transform(requestPayload, dom4jResult);
return dom4jResult.getDocument().getRootElement();
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new DocumentSource(returnedElement);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new DocumentSource(returnedElement);
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
}

View File

@@ -37,55 +37,55 @@ import org.w3c.dom.Node;
*/
public class DomPayloadMethodProcessor extends AbstractPayloadSourceMethodProcessor {
// MethodArgumentResolver
// MethodArgumentResolver
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected Node resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
if (requestPayload instanceof DOMSource) {
return resolveArgumentDomSource(parameter, (DOMSource) requestPayload);
}
else {
DOMResult domResult = new DOMResult();
transform(requestPayload, domResult);
DOMSource domSource = new DOMSource(domResult.getNode());
return resolveArgumentDomSource(parameter, domSource);
}
}
@Override
protected Node resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
if (requestPayload instanceof DOMSource) {
return resolveArgumentDomSource(parameter, (DOMSource) requestPayload);
}
else {
DOMResult domResult = new DOMResult();
transform(requestPayload, domResult);
DOMSource domSource = new DOMSource(domResult.getNode());
return resolveArgumentDomSource(parameter, domSource);
}
}
private Node resolveArgumentDomSource(MethodParameter parameter, DOMSource requestSource) {
Class<?> parameterType = parameter.getParameterType();
Node requestNode = requestSource.getNode();
if (parameterType.isAssignableFrom(requestNode.getClass())) {
return requestNode;
}
else if (Element.class.equals(parameterType) && requestNode instanceof Document) {
Document document = (Document) requestNode;
return document.getDocumentElement();
}
// should not happen
throw new UnsupportedOperationException();
}
private Node resolveArgumentDomSource(MethodParameter parameter, DOMSource requestSource) {
Class<?> parameterType = parameter.getParameterType();
Node requestNode = requestSource.getNode();
if (parameterType.isAssignableFrom(requestNode.getClass())) {
return requestNode;
}
else if (Element.class.equals(parameterType) && requestNode instanceof Document) {
Document document = (Document) requestNode;
return document.getDocumentElement();
}
// should not happen
throw new UnsupportedOperationException();
}
// MethodReturnValueHandler
// MethodReturnValueHandler
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected DOMSource createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new DOMSource(returnedElement);
}
@Override
protected DOMSource createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new DOMSource(returnedElement);
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
}

View File

@@ -5,7 +5,7 @@
* 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
* 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,
@@ -39,43 +39,43 @@ import org.w3c.dom.Node;
*/
public class JDomPayloadMethodProcessor extends AbstractPayloadSourceMethodProcessor {
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
if (requestPayload instanceof DOMSource) {
Node node = ((DOMSource) requestPayload).getNode();
DOMBuilder domBuilder = new DOMBuilder();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return domBuilder.build((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = domBuilder.build((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
JDOMResult jdomResult = new JDOMResult();
transform(requestPayload, jdomResult);
return jdomResult.getDocument().getRootElement();
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload) throws Exception {
if (requestPayload instanceof DOMSource) {
Node node = ((DOMSource) requestPayload).getNode();
DOMBuilder domBuilder = new DOMBuilder();
if (node.getNodeType() == Node.ELEMENT_NODE) {
return domBuilder.build((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == Node.DOCUMENT_NODE) {
Document document = domBuilder.build((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
JDOMResult jdomResult = new JDOMResult();
transform(requestPayload, jdomResult);
return jdomResult.getDocument().getRootElement();
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new JDOMSource(returnedElement);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue) {
Element returnedElement = (Element) returnValue;
return new JDOMSource(returnedElement);
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
}

View File

@@ -45,66 +45,66 @@ import org.w3c.dom.DOMImplementation;
*/
public class XomPayloadMethodProcessor extends AbstractPayloadSourceMethodProcessor {
private DocumentBuilderFactory documentBuilderFactory = createDocumentBuilderFactory();
private DocumentBuilderFactory documentBuilderFactory = createDocumentBuilderFactory();
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
return supports(parameter);
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws TransformerException, IOException, ParsingException {
if (requestPayload instanceof DOMSource) {
org.w3c.dom.Node node = ((DOMSource) requestPayload).getNode();
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
return DOMConverter.convert((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE) {
Document document = DOMConverter.convert((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
Builder builder = new Builder();
Document document = builder.build(bis);
return document.getRootElement();
}
@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
throws TransformerException, IOException, ParsingException {
if (requestPayload instanceof DOMSource) {
org.w3c.dom.Node node = ((DOMSource) requestPayload).getNode();
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
return DOMConverter.convert((org.w3c.dom.Element) node);
}
else if (node.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE) {
Document document = DOMConverter.convert((org.w3c.dom.Document) node);
return document.getRootElement();
}
}
// we have no other option than to transform
ByteArrayInputStream bis = convertToByteArrayInputStream(requestPayload);
Builder builder = new Builder();
Document document = builder.build(bis);
return document.getRootElement();
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
return supports(returnType);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue)
throws ParserConfigurationException {
Element returnedElement = (Element) returnValue;
Document document = returnedElement.getDocument();
if (document == null) {
document = new Document(returnedElement);
}
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
org.w3c.dom.Document w3cDocument = DOMConverter.convert(document, domImplementation);
return new DOMSource(w3cDocument);
}
@Override
protected Source createResponsePayload(MethodParameter returnType, Object returnValue)
throws ParserConfigurationException {
Element returnedElement = (Element) returnValue;
Document document = returnedElement.getDocument();
if (document == null) {
document = new Document(returnedElement);
}
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
org.w3c.dom.Document w3cDocument = DOMConverter.convert(document, domImplementation);
return new DOMSource(w3cDocument);
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
private boolean supports(MethodParameter parameter) {
return Element.class.equals(parameter.getParameterType());
}
/**
* Create a {@code DocumentBuilderFactory} that this resolver will use to create response payloads.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected DocumentBuilderFactory createDocumentBuilderFactory() {
return DocumentBuilderFactory.newInstance();
}
/**
* Create a {@code DocumentBuilderFactory} that this resolver will use to create response payloads.
*
* <p>Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached,
* so this method will only be called once.
*
* @return the created factory
*/
protected DocumentBuilderFactory createDocumentBuilderFactory() {
return DocumentBuilderFactory.newInstance();
}
}

View File

@@ -71,7 +71,7 @@ import org.springframework.xml.transform.TraxUtils;
*/
public abstract class AbstractJaxb2PayloadMethodProcessor extends AbstractPayloadMethodProcessor {
private final ConcurrentMap<Class<?>, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class<?>, JAXBContext>();
private final ConcurrentMap<Class<?>, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class<?>, JAXBContext>();
@Override
public final void handleReturnValue(MessageContext messageContext,
@@ -85,346 +85,346 @@ public abstract class AbstractJaxb2PayloadMethodProcessor extends AbstractPayloa
MethodParameter returnType, Object returnValue) throws Exception;
/**
* Marshals the given {@code jaxbElement} to the response payload of the given message context.
*
* @param messageContext the message context to marshal to
* @param clazz the clazz to create a marshaller for
* @param jaxbElement the object to be marshalled
* @throws JAXBException in case of JAXB2 errors
*/
protected final void marshalToResponsePayload(MessageContext messageContext, Class<?> clazz, Object jaxbElement)
throws JAXBException {
Assert.notNull(messageContext, "'messageContext' must not be null");
Assert.notNull(clazz, "'clazz' must not be null");
Assert.notNull(jaxbElement, "'jaxbElement' must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + jaxbElement + "] to response payload");
}
WebServiceMessage response = messageContext.getResponse();
if (response instanceof StreamingWebServiceMessage) {
StreamingWebServiceMessage streamingResponse = (StreamingWebServiceMessage) response;
* Marshals the given {@code jaxbElement} to the response payload of the given message context.
*
* @param messageContext the message context to marshal to
* @param clazz the clazz to create a marshaller for
* @param jaxbElement the object to be marshalled
* @throws JAXBException in case of JAXB2 errors
*/
protected final void marshalToResponsePayload(MessageContext messageContext, Class<?> clazz, Object jaxbElement)
throws JAXBException {
Assert.notNull(messageContext, "'messageContext' must not be null");
Assert.notNull(clazz, "'clazz' must not be null");
Assert.notNull(jaxbElement, "'jaxbElement' must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Marshalling [" + jaxbElement + "] to response payload");
}
WebServiceMessage response = messageContext.getResponse();
if (response instanceof StreamingWebServiceMessage) {
StreamingWebServiceMessage streamingResponse = (StreamingWebServiceMessage) response;
StreamingPayload payload = new JaxbStreamingPayload(clazz, jaxbElement);
streamingResponse.setStreamingPayload(payload);
}
else {
Result responsePayload = response.getPayloadResult();
try {
Jaxb2ResultCallback callback = new Jaxb2ResultCallback(clazz, jaxbElement);
TraxUtils.doWithResult(responsePayload, callback);
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
}
StreamingPayload payload = new JaxbStreamingPayload(clazz, jaxbElement);
streamingResponse.setStreamingPayload(payload);
}
else {
Result responsePayload = response.getPayloadResult();
try {
Jaxb2ResultCallback callback = new Jaxb2ResultCallback(clazz, jaxbElement);
TraxUtils.doWithResult(responsePayload, callback);
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
}
/**
* Unmarshals the request payload of the given message context.
*
* @param messageContext the message context to unmarshal from
* @param clazz the class to unmarshal
* @return the unmarshalled object, or {@code null} if the request has no payload
* @throws JAXBException in case of JAXB2 errors
*/
protected final Object unmarshalFromRequestPayload(MessageContext messageContext, Class<?> clazz)
throws JAXBException {
Source requestPayload = getRequestPayload(messageContext);
if (requestPayload == null) {
return null;
}
try {
Jaxb2SourceCallback callback = new Jaxb2SourceCallback(clazz);
TraxUtils.doWithSource(requestPayload, callback);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + callback.result + "]");
}
return callback.result;
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
/**
* Unmarshals the request payload of the given message context.
*
* @param messageContext the message context to unmarshal from
* @param clazz the class to unmarshal
* @return the unmarshalled object, or {@code null} if the request has no payload
* @throws JAXBException in case of JAXB2 errors
*/
protected final Object unmarshalFromRequestPayload(MessageContext messageContext, Class<?> clazz)
throws JAXBException {
Source requestPayload = getRequestPayload(messageContext);
if (requestPayload == null) {
return null;
}
try {
Jaxb2SourceCallback callback = new Jaxb2SourceCallback(clazz);
TraxUtils.doWithSource(requestPayload, callback);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + callback.result + "]");
}
return callback.result;
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
/**
* Unmarshals the request payload of the given message context as {@link JAXBElement}.
*
* @param messageContext the message context to unmarshal from
* @param clazz the class to unmarshal
* @return the unmarshalled element, or {@code null} if the request has no payload
* @throws JAXBException in case of JAXB2 errors
*/
protected final <T> JAXBElement<T> unmarshalElementFromRequestPayload(MessageContext messageContext, Class<T> clazz)
throws JAXBException {
Source requestPayload = getRequestPayload(messageContext);
if (requestPayload == null) {
return null;
}
try {
JaxbElementSourceCallback<T> callback = new JaxbElementSourceCallback<T>(clazz);
TraxUtils.doWithSource(requestPayload, callback);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + callback.result + "]");
}
return callback.result;
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
/**
* Unmarshals the request payload of the given message context as {@link JAXBElement}.
*
* @param messageContext the message context to unmarshal from
* @param clazz the class to unmarshal
* @return the unmarshalled element, or {@code null} if the request has no payload
* @throws JAXBException in case of JAXB2 errors
*/
protected final <T> JAXBElement<T> unmarshalElementFromRequestPayload(MessageContext messageContext, Class<T> clazz)
throws JAXBException {
Source requestPayload = getRequestPayload(messageContext);
if (requestPayload == null) {
return null;
}
try {
JaxbElementSourceCallback<T> callback = new JaxbElementSourceCallback<T>(clazz);
TraxUtils.doWithSource(requestPayload, callback);
if (logger.isDebugEnabled()) {
logger.debug("Unmarshalled payload request to [" + callback.result + "]");
}
return callback.result;
}
catch (Exception ex) {
throw convertToJaxbException(ex);
}
}
private Source getRequestPayload(MessageContext messageContext) {
WebServiceMessage request = messageContext.getRequest();
return request != null ? request.getPayloadSource() : null;
}
private Source getRequestPayload(MessageContext messageContext) {
WebServiceMessage request = messageContext.getRequest();
return request != null ? request.getPayloadSource() : null;
}
private JAXBException convertToJaxbException(Exception ex) {
if (ex instanceof JAXBException) {
return (JAXBException) ex;
}
else {
return new JAXBException(ex);
}
}
private JAXBException convertToJaxbException(Exception ex) {
if (ex instanceof JAXBException) {
return (JAXBException) ex;
}
else {
return new JAXBException(ex);
}
}
/**
* Creates a new {@link Marshaller} to be used for marshalling objects to XML. Defaults to
* {@link javax.xml.bind.JAXBContext#createMarshaller()}, but can be overridden in subclasses for further
* customization.
*
* @param jaxbContext the JAXB context to create a marshaller for
* @return the marshaller
* @throws JAXBException in case of JAXB errors
*/
protected Marshaller createMarshaller(JAXBContext jaxbContext) throws JAXBException {
return jaxbContext.createMarshaller();
}
/**
* Creates a new {@link Marshaller} to be used for marshalling objects to XML. Defaults to
* {@link javax.xml.bind.JAXBContext#createMarshaller()}, but can be overridden in subclasses for further
* customization.
*
* @param jaxbContext the JAXB context to create a marshaller for
* @return the marshaller
* @throws JAXBException in case of JAXB errors
*/
protected Marshaller createMarshaller(JAXBContext jaxbContext) throws JAXBException {
return jaxbContext.createMarshaller();
}
private Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
return createMarshaller(getJaxbContext(clazz));
}
private Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
return createMarshaller(getJaxbContext(clazz));
}
/**
* Creates a new {@link Unmarshaller} to be used for unmarshalling XML to objects. Defaults to
* {@link javax.xml.bind.JAXBContext#createUnmarshaller()}, but can be overridden in subclasses for further
* customization.
*
* @param jaxbContext the JAXB context to create a unmarshaller for
* @return the unmarshaller
* @throws JAXBException in case of JAXB errors
*/
protected Unmarshaller createUnmarshaller(JAXBContext jaxbContext) throws JAXBException {
return jaxbContext.createUnmarshaller();
}
/**
* Creates a new {@link Unmarshaller} to be used for unmarshalling XML to objects. Defaults to
* {@link javax.xml.bind.JAXBContext#createUnmarshaller()}, but can be overridden in subclasses for further
* customization.
*
* @param jaxbContext the JAXB context to create a unmarshaller for
* @return the unmarshaller
* @throws JAXBException in case of JAXB errors
*/
protected Unmarshaller createUnmarshaller(JAXBContext jaxbContext) throws JAXBException {
return jaxbContext.createUnmarshaller();
}
private Unmarshaller createUnmarshaller(Class<?> clazz) throws JAXBException {
return createUnmarshaller(getJaxbContext(clazz));
}
private Unmarshaller createUnmarshaller(Class<?> clazz) throws JAXBException {
return createUnmarshaller(getJaxbContext(clazz));
}
private JAXBContext getJaxbContext(Class<?> clazz) throws JAXBException {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
jaxbContext = JAXBContext.newInstance(clazz);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
return jaxbContext;
}
private JAXBContext getJaxbContext(Class<?> clazz) throws JAXBException {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
jaxbContext = JAXBContext.newInstance(clazz);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
return jaxbContext;
}
// Callbacks
// Callbacks
private class Jaxb2SourceCallback implements TraxUtils.SourceCallback {
private class Jaxb2SourceCallback implements TraxUtils.SourceCallback {
private final Unmarshaller unmarshaller;
private final Unmarshaller unmarshaller;
private Object result;
private Object result;
public Jaxb2SourceCallback(Class<?> clazz) throws JAXBException {
this.unmarshaller = createUnmarshaller(clazz);
}
public Jaxb2SourceCallback(Class<?> clazz) throws JAXBException {
this.unmarshaller = createUnmarshaller(clazz);
}
@Override
public void domSource(Node node) throws JAXBException {
result = unmarshaller.unmarshal(node);
}
@Override
public void domSource(Node node) throws JAXBException {
result = unmarshaller.unmarshal(node);
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws Exception {
if (inputSource.getByteStream() == null && inputSource.getCharacterStream() == null
&& inputSource.getSystemId() == null) {
// The InputSource neither has a stream nor a system ID set; this means that
// we are dealing with a custom SAXSource that is not backed by a SAX parser
// but that generates a sequence of SAX events in some other way.
// In this case, we need to use a ContentHandler to feed the SAX events into
// the unmarshaller.
UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();
reader.setContentHandler(handler);
reader.parse(inputSource);
result = handler.getResult();
} else {
// If a stream or system ID is set, we assume that the SAXSource is backed
// by a SAX parser and we only pass the InputSource to the unmarshaller.
// This effectively ignores the SAX parser and lets the unmarshaller take
// care of the parsing (in a potentially more efficient way).
result = unmarshaller.unmarshal(inputSource);
}
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws Exception {
if (inputSource.getByteStream() == null && inputSource.getCharacterStream() == null
&& inputSource.getSystemId() == null) {
// The InputSource neither has a stream nor a system ID set; this means that
// we are dealing with a custom SAXSource that is not backed by a SAX parser
// but that generates a sequence of SAX events in some other way.
// In this case, we need to use a ContentHandler to feed the SAX events into
// the unmarshaller.
UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();
reader.setContentHandler(handler);
reader.parse(inputSource);
result = handler.getResult();
} else {
// If a stream or system ID is set, we assume that the SAXSource is backed
// by a SAX parser and we only pass the InputSource to the unmarshaller.
// This effectively ignores the SAX parser and lets the unmarshaller take
// care of the parsing (in a potentially more efficient way).
result = unmarshaller.unmarshal(inputSource);
}
}
@Override
public void staxSource(XMLEventReader eventReader) throws JAXBException {
result = unmarshaller.unmarshal(eventReader);
}
@Override
public void staxSource(XMLEventReader eventReader) throws JAXBException {
result = unmarshaller.unmarshal(eventReader);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws JAXBException {
result = unmarshaller.unmarshal(streamReader);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws JAXBException {
result = unmarshaller.unmarshal(streamReader);
}
@Override
public void streamSource(InputStream inputStream) throws IOException, JAXBException {
result = unmarshaller.unmarshal(inputStream);
}
@Override
public void streamSource(InputStream inputStream) throws IOException, JAXBException {
result = unmarshaller.unmarshal(inputStream);
}
@Override
public void streamSource(Reader reader) throws IOException, JAXBException {
result = unmarshaller.unmarshal(reader);
}
@Override
public void streamSource(Reader reader) throws IOException, JAXBException {
result = unmarshaller.unmarshal(reader);
}
@Override
public void source(String systemId) throws Exception {
result = unmarshaller.unmarshal(new URL(systemId));
}
}
@Override
public void source(String systemId) throws Exception {
result = unmarshaller.unmarshal(new URL(systemId));
}
}
private class JaxbElementSourceCallback<T> implements TraxUtils.SourceCallback {
private class JaxbElementSourceCallback<T> implements TraxUtils.SourceCallback {
private final Unmarshaller unmarshaller;
private final Unmarshaller unmarshaller;
private final Class<T> declaredType;
private final Class<T> declaredType;
private JAXBElement<T> result;
private JAXBElement<T> result;
public JaxbElementSourceCallback(Class<T> declaredType) throws JAXBException {
this.unmarshaller = createUnmarshaller(declaredType);
this.declaredType = declaredType;
}
public JaxbElementSourceCallback(Class<T> declaredType) throws JAXBException {
this.unmarshaller = createUnmarshaller(declaredType);
this.declaredType = declaredType;
}
@Override
public void domSource(Node node) throws JAXBException {
result = unmarshaller.unmarshal(node, declaredType);
}
@Override
public void domSource(Node node) throws JAXBException {
result = unmarshaller.unmarshal(node, declaredType);
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws JAXBException {
result = unmarshaller.unmarshal(new SAXSource(reader, inputSource), declaredType);
}
@Override
public void saxSource(XMLReader reader, InputSource inputSource) throws JAXBException {
result = unmarshaller.unmarshal(new SAXSource(reader, inputSource), declaredType);
}
@Override
public void staxSource(XMLEventReader eventReader) throws JAXBException {
result = unmarshaller.unmarshal(eventReader, declaredType);
}
@Override
public void staxSource(XMLEventReader eventReader) throws JAXBException {
result = unmarshaller.unmarshal(eventReader, declaredType);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws JAXBException {
result = unmarshaller.unmarshal(streamReader, declaredType);
}
@Override
public void staxSource(XMLStreamReader streamReader) throws JAXBException {
result = unmarshaller.unmarshal(streamReader, declaredType);
}
@Override
public void streamSource(InputStream inputStream) throws IOException, JAXBException {
result = unmarshaller.unmarshal(new StreamSource(inputStream), declaredType);
}
@Override
public void streamSource(InputStream inputStream) throws IOException, JAXBException {
result = unmarshaller.unmarshal(new StreamSource(inputStream), declaredType);
}
@Override
public void streamSource(Reader reader) throws IOException, JAXBException {
result = unmarshaller.unmarshal(new StreamSource(reader), declaredType);
}
@Override
public void streamSource(Reader reader) throws IOException, JAXBException {
result = unmarshaller.unmarshal(new StreamSource(reader), declaredType);
}
@Override
public void source(String systemId) throws Exception {
result = unmarshaller.unmarshal(new StreamSource(systemId), declaredType);
}
}
@Override
public void source(String systemId) throws Exception {
result = unmarshaller.unmarshal(new StreamSource(systemId), declaredType);
}
}
private class Jaxb2ResultCallback implements TraxUtils.ResultCallback {
private class Jaxb2ResultCallback implements TraxUtils.ResultCallback {
private final Marshaller marshaller;
private final Marshaller marshaller;
private final Object jaxbElement;
private final Object jaxbElement;
private Jaxb2ResultCallback(Class<?> clazz, Object jaxbElement) throws JAXBException {
this.marshaller = createMarshaller(clazz);
this.jaxbElement = jaxbElement;
}
private Jaxb2ResultCallback(Class<?> clazz, Object jaxbElement) throws JAXBException {
this.marshaller = createMarshaller(clazz);
this.jaxbElement = jaxbElement;
}
@Override
public void domResult(Node node) throws JAXBException {
marshaller.marshal(jaxbElement, node);
}
@Override
public void domResult(Node node) throws JAXBException {
marshaller.marshal(jaxbElement, node);
}
@Override
public void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws JAXBException {
marshaller.marshal(jaxbElement, contentHandler);
}
@Override
public void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws JAXBException {
marshaller.marshal(jaxbElement, contentHandler);
}
@Override
public void staxResult(XMLEventWriter eventWriter) throws JAXBException {
marshaller.marshal(jaxbElement, eventWriter);
}
@Override
public void staxResult(XMLEventWriter eventWriter) throws JAXBException {
marshaller.marshal(jaxbElement, eventWriter);
}
@Override
public void staxResult(XMLStreamWriter streamWriter) throws JAXBException {
marshaller.marshal(jaxbElement, streamWriter);
}
@Override
public void staxResult(XMLStreamWriter streamWriter) throws JAXBException {
marshaller.marshal(jaxbElement, streamWriter);
}
@Override
public void streamResult(OutputStream outputStream) throws JAXBException {
marshaller.marshal(jaxbElement, outputStream);
}
@Override
public void streamResult(OutputStream outputStream) throws JAXBException {
marshaller.marshal(jaxbElement, outputStream);
}
@Override
public void streamResult(Writer writer) throws JAXBException {
marshaller.marshal(jaxbElement, writer);
}
@Override
public void streamResult(Writer writer) throws JAXBException {
marshaller.marshal(jaxbElement, writer);
}
@Override
public void result(String systemId) throws Exception {
marshaller.marshal(jaxbElement, new StreamResult(systemId));
}
}
@Override
public void result(String systemId) throws Exception {
marshaller.marshal(jaxbElement, new StreamResult(systemId));
}
}
private class JaxbStreamingPayload implements StreamingPayload {
private class JaxbStreamingPayload implements StreamingPayload {
private final Object jaxbElement;
private final Object jaxbElement;
private final Marshaller marshaller;
private final Marshaller marshaller;
private final QName name;
private final QName name;
private JaxbStreamingPayload(Class<?> clazz, Object jaxbElement) throws JAXBException {
JAXBContext jaxbContext = getJaxbContext(clazz);
this.marshaller = jaxbContext.createMarshaller();
this.marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
this.jaxbElement = jaxbElement;
JAXBIntrospector introspector = jaxbContext.createJAXBIntrospector();
this.name = introspector.getElementName(jaxbElement);
}
private JaxbStreamingPayload(Class<?> clazz, Object jaxbElement) throws JAXBException {
JAXBContext jaxbContext = getJaxbContext(clazz);
this.marshaller = jaxbContext.createMarshaller();
this.marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
this.jaxbElement = jaxbElement;
JAXBIntrospector introspector = jaxbContext.createJAXBIntrospector();
this.name = introspector.getElementName(jaxbElement);
}
@Override
public QName getName() {
return name;
}
@Override
public QName getName() {
return name;
}
@Override
public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException {
try {
marshaller.marshal(jaxbElement, streamWriter);
}
catch (JAXBException ex) {
throw new XMLStreamException("Could not marshal [" + jaxbElement + "]: " + ex.getMessage(), ex);
}
}
}
@Override
public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException {
try {
marshaller.marshal(jaxbElement, streamWriter);
}
catch (JAXBException ex) {
throw new XMLStreamException("Could not marshal [" + jaxbElement + "]: " + ex.getMessage(), ex);
}
}
}
}

View File

@@ -34,31 +34,31 @@ import org.springframework.ws.context.MessageContext;
*/
public class JaxbElementPayloadMethodProcessor extends AbstractJaxb2PayloadMethodProcessor {
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
Type genericType = parameter.getGenericParameterType();
return JAXBElement.class.equals(parameterType) && genericType instanceof ParameterizedType;
}
@Override
public JAXBElement<?> resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws JAXBException {
ParameterizedType parameterizedType = (ParameterizedType) parameter.getGenericParameterType();
Class<?> clazz = (Class) parameterizedType.getActualTypeArguments()[0];
return unmarshalElementFromRequestPayload(messageContext, clazz);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Class<?> parameterType = returnType.getParameterType();
return JAXBElement.class.isAssignableFrom(parameterType);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
Type genericType = parameter.getGenericParameterType();
return JAXBElement.class.equals(parameterType) && genericType instanceof ParameterizedType;
}
@Override
protected void handleReturnValueInternal(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws JAXBException {
JAXBElement<?> element = (JAXBElement<?>) returnValue;
marshalToResponsePayload(messageContext, element.getDeclaredType(), element);
}
public JAXBElement<?> resolveArgument(MessageContext messageContext, MethodParameter parameter)
throws JAXBException {
ParameterizedType parameterizedType = (ParameterizedType) parameter.getGenericParameterType();
Class<?> clazz = (Class) parameterizedType.getActualTypeArguments()[0];
return unmarshalElementFromRequestPayload(messageContext, clazz);
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Class<?> parameterType = returnType.getParameterType();
return JAXBElement.class.isAssignableFrom(parameterType);
}
@Override
protected void handleReturnValueInternal(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws JAXBException {
JAXBElement<?> element = (JAXBElement<?>) returnValue;
marshalToResponsePayload(messageContext, element.getDeclaredType(), element);
}
}

View File

@@ -35,38 +35,38 @@ import org.springframework.ws.context.MessageContext;
*/
public class XmlRootElementPayloadMethodProcessor extends AbstractJaxb2PayloadMethodProcessor {
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
return parameterType.isAnnotationPresent(XmlRootElement.class) ||
parameterType.isAnnotationPresent(XmlType.class);
}
@Override
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws JAXBException {
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isAnnotationPresent(XmlRootElement.class)) {
return unmarshalFromRequestPayload(messageContext, parameterType);
}
else {
JAXBElement<?> element = unmarshalElementFromRequestPayload(messageContext, parameterType);
return element != null ? element.getValue() : null;
}
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Class<?> parameterType = returnType.getParameterType();
return parameterType.isAnnotationPresent(XmlRootElement.class);
}
@Override
protected boolean supportsRequestPayloadParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
return parameterType.isAnnotationPresent(XmlRootElement.class) ||
parameterType.isAnnotationPresent(XmlType.class);
}
@Override
protected void handleReturnValueInternal(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws JAXBException {
Class<?> parameterType = returnType.getParameterType();
marshalToResponsePayload(messageContext, parameterType, returnValue);
}
public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws JAXBException {
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isAnnotationPresent(XmlRootElement.class)) {
return unmarshalFromRequestPayload(messageContext, parameterType);
}
else {
JAXBElement<?> element = unmarshalElementFromRequestPayload(messageContext, parameterType);
return element != null ? element.getValue() : null;
}
}
@Override
protected boolean supportsResponsePayloadReturnType(MethodParameter returnType) {
Class<?> parameterType = returnType.getParameterType();
return parameterType.isAnnotationPresent(XmlRootElement.class);
}
@Override
protected void handleReturnValueInternal(MessageContext messageContext, MethodParameter returnType, Object returnValue)
throws JAXBException {
Class<?> parameterType = returnType.getParameterType();
marshalToResponsePayload(messageContext, parameterType, returnValue);
}
}

View File

@@ -43,12 +43,12 @@ import org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationM
@Component
public @interface Endpoint {
/**
* The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an
* autodetected component.
*
* @return the suggested component name, if any
*/
String value() default "";
/**
* The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an
* autodetected component.
*
* @return the suggested component name, if any
*/
String value() default "";
}

View File

@@ -38,18 +38,18 @@ import javax.xml.XMLConstants;
@Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.METHOD})
public @interface Namespace {
/**
* Signifies the prefix of the namespace.
*
* @see #uri()
*/
String prefix() default XMLConstants.DEFAULT_NS_PREFIX;
/**
* Signifies the prefix of the namespace.
*
* @see #uri()
*/
String prefix() default XMLConstants.DEFAULT_NS_PREFIX;
/**
* Signifies the URI of the namespace.
*
* @see #prefix()
*/
String uri();
/**
* Signifies the URI of the namespace.
*
* @see #prefix()
*/
String uri();
}

View File

@@ -34,5 +34,5 @@ import java.lang.annotation.Target;
@Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.METHOD})
public @interface Namespaces {
Namespace[] value();
Namespace[] value();
}

View File

@@ -37,18 +37,18 @@ import java.lang.annotation.Target;
@Repeatable(PayloadRoots.class)
public @interface PayloadRoot {
/**
* Signifies the local part of the payload root element handled by the annotated method.
*
* @see #namespace()
*/
String localPart();
/**
* Signifies the local part of the payload root element handled by the annotated method.
*
* @see #namespace()
*/
String localPart();
/**
* Signifies the namespace of the payload root element handled by the annotated method.
*
* @see #localPart()
*/
String namespace() default "";
/**
* Signifies the namespace of the payload root element handled by the annotated method.
*
* @see #localPart()
*/
String namespace() default "";
}

Some files were not shown because too many files have changed in this diff Show More